Advertisement
Guest User

Untitled

a guest
Aug 24th, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.02 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. from __future__ import print_function, unicode_literals, division, absolute_import
  3.  
  4. import socketio
  5.  
  6. from django.db.models import F
  7. from django.conf import settings
  8. from django.utils import timezone
  9. from django.template.defaultfilters import date as date_filter
  10.  
  11. from rest_framework import serializers
  12.  
  13. from sk_auth.audit import get_client_ip
  14. from sk_subscription.models import ActiveSubscription, SubscriptionAllergy
  15. from sk_school.models import School, Student, Employee
  16. from sk_kiosk.models import KioskCheckIn
  17. from sk_kiosk.exceptions import KioskCheckInException
  18.  
  19. class LoginSerializer(serializers.Serializer):
  20. """
  21. Inntak þegar skóli er að skrá sig inn.
  22. """
  23. username = serializers.CharField(required=True, allow_blank=False)
  24. password = serializers.CharField(required=True, allow_blank=False)
  25.  
  26. def validate_username(self, value):
  27. try:
  28. school = School.objects.filter(pin__isnull=False).get(uuid=value)
  29.  
  30. return school
  31. except School.DoesNotExist:
  32. raise serializers.ValidationError('Skóli er ekki til.')
  33.  
  34. def validate(self, data):
  35. school = data.get('username')
  36. pin = data.get('password')
  37.  
  38. if school.pin_locked is not None and school.pin_locked > timezone.now():
  39. raise serializers.ValidationError('Of margar tilraunir. Vinsamlegast reyndu aftur eftir {}.'.format(date_filter(school.pin_locked, 'j. F Y H:i')))
  40.  
  41. if str(school.pin) != pin:
  42. if school.pin_attempt > 3:
  43. pin_locked = timezone.now() + timezone.timedelta(minutes=5)
  44. School.objects.filter(pk=school.pk).update(pin_attempt=F('pin_attempt') + 1, pin_locked=pin_locked)
  45. raise serializers.ValidationError('Lykilorð er ekki rétt. Of margar tilraunir. Vinsamlegast reyndu aftur eftir {}.'.format(date_filter(pin_locked, 'j. F Y H:i')))
  46. else:
  47. School.objects.filter(pk=school.pk).update(pin_attempt=F('pin_attempt') + 1)
  48. raise serializers.ValidationError('Lykilorð er ekki rétt. Vinsamlegast reyndu aftur.')
  49.  
  50. return data
  51.  
  52.  
  53. def create(self, validated_data):
  54. school = validated_data.get('username')
  55.  
  56. School.objects.filter(pk=school.pk).update(pin_attempt=0, pin_locked=None)
  57.  
  58. return school
  59.  
  60.  
  61. class CheckInSerializer(serializers.Serializer):
  62. """
  63. Inntak þegar nemandi eða starfsmaður er að skrá sig í mat.
  64. """
  65. pin = serializers.CharField(required=True, allow_blank=False)
  66.  
  67. def validate_pin(self, data):
  68. try:
  69. student = Student.objects.only('id', 'uuid', 'ssn', 'name', ).get(pin=data)
  70. return dict(is_student=True, is_employee=False, student=student)
  71. except Student.DoesNotExist:
  72. pass
  73.  
  74. try:
  75. employee = Employee.objects.only('id', 'uuid', 'ssn', 'name', ).get(pin=data)
  76. return dict(is_student=False, is_employee=True, employee=employee)
  77. except Employee.DoesNotExist:
  78. pass
  79.  
  80. return dict(is_employee=False, is_student=False, pin=data)
  81.  
  82. def validate(self, data):
  83. student_or_employee = data['pin']
  84.  
  85. if not student_or_employee['is_student'] and not student_or_employee['is_employee']:
  86. external_sio = socketio.KombuManager(settings.KIOSK_MESSAGE_QUEUE, channel='kiosk-socketio', write_only=True)
  87. external_sio.emit('checkin-error', data={
  88. 'name': None,
  89. 'detail': 'PIN númer ekki til.',
  90. 'code': 'invalid_pin',
  91. }, namespace='/kiosk', room=str(self.context['school'].uuid))
  92. raise KioskCheckInException(name=None, detail='PIN númer ekki til.', code='invalid_pin')
  93.  
  94. is_student = False
  95. is_employee = False
  96. employee = None
  97. student = None
  98.  
  99. if 'is_student' in student_or_employee and student_or_employee['is_student']:
  100. is_student = True
  101. student = student_or_employee['student']
  102. elif 'is_employee' in student_or_employee and student_or_employee['is_employee']:
  103. is_employee = True
  104. employee = student_or_employee['employee']
  105.  
  106. active_subscription_queryset = ActiveSubscription.objects.all()
  107.  
  108. active_subscription_queryset = active_subscription_queryset.select_related('subscription')
  109. active_subscription_queryset = active_subscription_queryset.only(
  110. 'id', 'uuid', 'subscription__id', 'subscription__uuid', 'subscription__allergies_other',
  111. )
  112.  
  113. now = timezone.now()
  114. weekday = now.weekday()
  115.  
  116. active_subscription_queryset = active_subscription_queryset.filter(school=self.context['school'])
  117. active_subscription_queryset = active_subscription_queryset.filter(monday=True) if weekday == 0 else active_subscription_queryset
  118. active_subscription_queryset = active_subscription_queryset.filter(tuesday=True) if weekday == 1 else active_subscription_queryset
  119. active_subscription_queryset = active_subscription_queryset.filter(wednesday=True) if weekday == 2 else active_subscription_queryset
  120. active_subscription_queryset = active_subscription_queryset.filter(thursday=True) if weekday == 3 else active_subscription_queryset
  121. active_subscription_queryset = active_subscription_queryset.filter(friday=True) if weekday == 4 else active_subscription_queryset
  122.  
  123. if weekday > 4:
  124. external_sio = socketio.KombuManager(settings.KIOSK_MESSAGE_QUEUE, channel='kiosk-socketio', write_only=True)
  125. external_sio.emit('checkin-error', data={
  126. 'name': None,
  127. 'detail': 'Aðeins er hægt að skrá á virkum dögum.',
  128. 'code': 'invalid_weekday',
  129. }, namespace='/kiosk', room=str(self.context['school'].uuid))
  130. raise KioskCheckInException(name=None, detail='Aðeins er hægt að skrá á virkum dögum.', code='invalid_weekday')
  131.  
  132. active_subscription_queryset = active_subscription_queryset.filter(enabled=True)
  133. active_subscription_queryset = active_subscription_queryset.filter(valid_from__lte=now)
  134. active_subscription_queryset = active_subscription_queryset.filter(valid_to__gte=now)
  135.  
  136. if is_student:
  137. active_subscription_queryset = active_subscription_queryset.filter(subscription__student=student)
  138. elif is_employee:
  139. active_subscription_queryset = active_subscription_queryset.filter(subscription__employee=employee)
  140.  
  141. try:
  142. active_subscription = active_subscription_queryset.get()
  143. except ActiveSubscription.DoesNotExist:
  144. if is_student:
  145. external_sio = socketio.KombuManager(settings.KIOSK_MESSAGE_QUEUE, channel='kiosk-socketio', write_only=True)
  146. external_sio.emit('checkin-error', data={
  147. 'name': student.name,
  148. 'ssn': student.ssn,
  149. 'detail': 'Ekki í áskrift í dag.',
  150. 'code': 'invalid_subscription',
  151. }, namespace='/kiosk', room=str(self.context['school'].uuid))
  152. KioskCheckIn.objects.create(
  153. active_subscription=None,
  154. ip=get_client_ip(self.context['request']),
  155. school=self.context['school'],
  156. student=student,
  157. employee=employee,
  158. invalid=True,
  159. invalid_reason='Ekki í áskrift í dag.',
  160. )
  161. raise KioskCheckInException(name=student.name, detail='Ekki í áskrift í dag.', code='invalid_subscription')
  162.  
  163. elif is_employee:
  164. external_sio = socketio.KombuManager(settings.KIOSK_MESSAGE_QUEUE, channel='kiosk-socketio', write_only=True)
  165. external_sio.emit('checkin-error', data={
  166. 'name': employee.name,
  167. 'ssn': employee.ssn,
  168. 'detail': 'Ekki í áskrift í dag.',
  169. 'code': 'invalid_subscription',
  170. }, namespace='/kiosk', room=str(self.context['school'].uuid))
  171. KioskCheckIn.objects.create(
  172. active_subscription=None,
  173. ip=get_client_ip(self.context['request']),
  174. school=self.context['school'],
  175. student=student,
  176. employee=employee,
  177. invalid=True,
  178. invalid_reason='Ekki í áskrift í dag.',
  179. )
  180. raise KioskCheckInException(name=employee.name, detail='Ekki í áskrift í dag.', code='invalid_subscription')
  181.  
  182. data['active_subscription'] = active_subscription
  183. data['student'] = student
  184. data['employee'] = employee
  185.  
  186. return data
  187.  
  188. def create(self, validated_data):
  189. active_subscription = validated_data.get('active_subscription')
  190.  
  191. subscription_allergy_queryset = SubscriptionAllergy.objects.filter(
  192. subscription_id=active_subscription.subscription_id,
  193. allergy__isnull=False
  194. )
  195.  
  196. subscription_allergy_queryset = subscription_allergy_queryset.select_related('allergy')
  197. subscription_allergy_queryset = subscription_allergy_queryset.only(
  198. 'id', 'uuid', 'allergy__id', 'allergy__uuid', 'allergy__name', 'certificate',
  199. )
  200.  
  201. kiosk_checkin = KioskCheckIn.objects.create(
  202. active_subscription = active_subscription,
  203. ip=get_client_ip(self.context['request']),
  204. school=self.context['school'],
  205. student=validated_data['student'],
  206. employee=validated_data['employee'],
  207. invalid=False,
  208. invalid_reason=None,
  209. )
  210.  
  211. # connect to the redis queue through Kombu
  212. external_sio = socketio.KombuManager(settings.KIOSK_MESSAGE_QUEUE, channel='kiosk-socketio', write_only=True)
  213.  
  214. emit_data = None
  215. pin_data = validated_data.get('pin')
  216. if pin_data.get('is_student', False):
  217. emit_data = {
  218. 'is_student': True,
  219. 'is_employee': False,
  220. 'subscription': {
  221. 'allergies_other': active_subscription.subscription.allergies_other,
  222. 'allergies': [{
  223. 'allergy': {
  224. 'name': subscription_allergy.allergy.name,
  225. },
  226. 'certificate': True if subscription_allergy.certificate else False,
  227. } for subscription_allergy in subscription_allergy_queryset]
  228. },
  229. 'info': {
  230. 'id': str(pin_data.get('student').uuid),
  231. 'ssn': pin_data.get('student').ssn,
  232. 'name': pin_data.get('student').name,
  233. }
  234. }
  235. elif pin_data.get('is_employee', False):
  236. emit_data = {
  237. 'is_student': False,
  238. 'is_employee': True,
  239. 'subscription': {
  240. 'allergies_other': active_subscription.subscription.allergies_other,
  241. 'allergies': [{
  242. 'allergy': {
  243. 'name': subscription_allergy.allergy.name,
  244. },
  245. 'certificate': True if subscription_allergy.certificate else False,
  246. } for subscription_allergy in subscription_allergy_queryset]
  247. },
  248. 'info': {
  249. 'id': str(pin_data.get('employee').uuid),
  250. 'ssn': pin_data.get('employee').ssn,
  251. 'name': pin_data.get('employee').name,
  252. }
  253. }
  254.  
  255. external_sio.emit('checkin', data=emit_data, namespace='/kiosk', room=str(self.context['school'].uuid))
  256.  
  257. return emit_data
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement