This repository has been archived by the owner on Jan 13, 2022. It is now read-only.
/
views.py
4811 lines (4116 loc) · 165 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import json
import re
from datetime import datetime, timedelta
from urllib.parse import urlencode
from dateutil.rrule import rrulestr
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.postgres.search import SearchQuery, SearchRank
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Count
from django.db.models import F
from django.db.models import Q
from django.db.models import Sum
from django.db.models.expressions import RawSQL
from django.db.models.functions import Coalesce
from django.forms import HiddenInput
from django.http import Http404, HttpResponseBadRequest
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.http import urlquote
from django.utils.http import urlunquote_plus
from django.utils.translation import ugettext as _
from django.utils.translation.trans_real import get_languages
from django.views.defaults import bad_request
from django.views.generic import View, TemplateView, ListView, DetailView
from django.views.generic.base import RedirectView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.edit import FormMixin, ModelFormMixin
from django.views.generic.edit import FormView, ProcessFormView
import booking.models as booking_models
from booking.constants import LOGACTION_CREATE, AVAILABLE_SEATS_NO_LIMIT
from booking.forms import AcceptBookingForm, MultiProductVisitProductsForm
from booking.forms import AdminProductSearchForm
from booking.forms import AssignmentHelpForm
from booking.forms import BookerForm
from booking.forms import BookingForm
from booking.forms import BookingGrundskoleSubjectLevelForm
from booking.forms import BookingGymnasieSubjectLevelForm
from booking.forms import BookingListForm
from booking.forms import ClassBookingBaseForm
from booking.forms import ClassBookingForm
from booking.forms import ClassProductForm
from booking.forms import ConfirmForm
from booking.forms import EditBookerForm
from booking.forms import EmailComposeForm
from booking.forms import EmailReplyForm
from booking.forms import EmailTemplateForm
from booking.forms import EmailTemplatePreviewContextForm
from booking.forms import EvaluationForm
from booking.forms import EvaluationStatisticsForm
from booking.forms import GuestEmailComposeForm
from booking.forms import InternshipForm
from booking.forms import MultiProductVisitTempDateForm
from booking.forms import MultiProductVisitTempProductsForm
from booking.forms import OpenHouseForm
from booking.forms import OtherProductForm
from booking.forms import ProductAutosendFormSet
from booking.forms import ProductForm
from booking.forms import ProductInitialForm
from booking.forms import ProductStudyMaterialForm
from booking.forms import StudentForADayBookingBaseForm
from booking.forms import StudentForADayBookingForm
from booking.forms import StudentForADayForm
from booking.forms import StudyMaterialForm
from booking.forms import StudyProjectBookingBaseForm
from booking.forms import StudyProjectBookingForm
from booking.forms import StudyProjectForm
from booking.forms import TeacherBookingBaseForm
from booking.forms import TeacherBookingForm
from booking.forms import TeacherProductForm
from booking.forms import VisitSearchForm
from booking.logging import log_action
from booking.mixins import AccessDenied
from booking.mixins import AdminRequiredMixin
from booking.mixins import AutologgerMixin
from booking.mixins import BackMixin
from booking.mixins import BreadcrumbMixin
from booking.mixins import EditorRequiredMixin
from booking.mixins import HasBackButtonMixin
from booking.mixins import LoggedViewMixin
from booking.mixins import LoginRequiredMixin
from booking.mixins import ModalMixin
from booking.mixins import RoleRequiredMixin
from booking.mixins import SearchEngineMixin
from booking.mixins import UnitAccessRequiredMixin
from booking.models import BookerResponseNonce
from booking.models import Booking, Guest
from booking.models import CalendarEvent
from booking.models import EmailTemplate
from booking.models import EmailTemplateType
from booking.models import EventTime
from booking.models import GymnasieLevel
from booking.models import KUEmailMessage
from booking.models import KUEmailRecipient
from booking.models import MultiProductVisit
from booking.models import MultiProductVisitTemp
from booking.models import MultiProductVisitTempProduct
from booking.models import OrganizationalUnit
from booking.models import PostCode
from booking.models import Product
from booking.models import ProductGrundskoleFag
from booking.models import ProductGymnasieFag
from booking.models import Room
from booking.models import RoomResponsible
from booking.models import School
from booking.models import StudyMaterial
from booking.models import Subject
from booking.models import SurveyXactEvaluation, SurveyXactEvaluationGuest
from booking.models import Visit
from booking.utils import DummyRecipient
from booking.utils import TemplateSplit
from booking.utils import full_email
from booking.utils import merge_dicts
from user_profile.constants import FACULTY_EDITOR, ADMINISTRATOR
from user_profile.models import EDIT_ROLES
i18n_test = _(u"Dette tester oversættelses-systemet")
# Method for importing views from another module
def import_views(from_module):
module_prefix = from_module.__name__
import_dict = globals()
for name, value in from_module.__dict__.items():
# Skip stuff that is not classes
if not isinstance(value, type):
continue
# Skip stuff that is not views
if not issubclass(value, View):
continue
# Skip stuff that is not native to the booking.models module
if not value.__module__ == module_prefix:
continue
import_dict[name] = value
# Views to handle redirect of old locale-specific URLs starting with
# /da/ or /en/:
class LocaleRedirectView(RedirectView):
permanent = False
def get_redirect_url(self, *args, **kwargs):
# Redirect to the same URL without the first 3 characters (/en or /da)
return self.request.get_full_path()[3:]
# A couple of generic superclasses for crud views
# Our views will inherit from these and from django.views.generic classes
class MainPageView(TemplateView):
"""Display the main page."""
HEADING_RED = 'alert-danger'
HEADING_GREEN = 'alert-success'
HEADING_BLUE = 'alert-info'
HEADING_YELLOW = 'alert-warning'
template_name = 'frontpage.html'
def get_context_data(self, **kwargs):
context = {
'lists': [
{
'color': self.HEADING_GREEN,
'type': 'Product',
'title': _('Senest opdaterede tilbud'),
'queryset': Product.objects.get_latest_updated(
self.request.user
),
'limit': 10,
'button': {
'text': _('Vis alle'),
'link': reverse('product-customlist') + "?type=%s" %
ProductCustomListView.TYPE_LATEST_UPDATED
}
}, {
'color': self.HEADING_BLUE,
'type': 'Product',
'title': _('Senest bookede tilbud'),
'queryset': Product.objects.get_latest_booked(
self.request.user
),
'limit': 10,
'button': {
'text': _('Vis alle'),
'link': reverse('product-customlist') + "?type=%s" %
ProductCustomListView.TYPE_LATEST_BOOKED
}
}
]
}
for list in context['lists']:
if len(list['queryset']) > 10:
list['limited_qs'] = list['queryset'][:10]
context.update(kwargs)
return super(MainPageView, self).get_context_data(**context)
class ProductBookingDetailView(DetailView):
def on_display(self):
try:
self.object.ensure_statistics()
except Exception:
return
self.object.statistics.on_display()
def get(self, request, *args, **kwargs):
response = super(ProductBookingDetailView, self).\
get(request, *args, **kwargs)
self.on_display()
return response
class ProductBookingUpdateView(UpdateView):
def on_update(self):
try:
self.object.ensure_statistics()
except Exception:
return
self.object.statistics.on_update()
def form_valid(self, form):
self.on_update()
return super(ProductBookingUpdateView, self).form_valid(form)
class EmailComposeView(FormMixin, HasBackButtonMixin, TemplateView):
template_name = 'email/compose.html'
form_class = EmailComposeForm
recipients = []
template_type = None
template_context = {}
modal = True
RECIPIENT_BOOKER = 'booker'
RECIPIENT_USER = 'user'
RECIPIENT_CUSTOM = 'custom'
RECIPIENT_ROOMRESPONSIBLE = 'roomresponsible'
RECIPIENT_SEPARATOR = ':'
def get_template_type(self, request):
try: # see if there's a template key defined in the URL params
self.template_type = EmailTemplateType.objects.get(
id=int(request.GET.get("template", None))
)
except Exception:
pass
def dispatch(self, request, *args, **kwargs):
self.get_template_type(request)
return super(EmailComposeView, self).dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
form = self.get_form()
form.fields['recipients'].choices = self.recipients
recipient_ids = request.GET.getlist("recipients", None)
if recipient_ids is not None:
# If the URL defines recipients, add them and set them as defaults
form.fields['recipients'].choices = [
self.encode_recipient(recipient)
for recipient in self.lookup_recipients(recipient_ids)
]
form.initial['recipients'] = [
id
for (id, label) in form.fields['recipients'].choices
]
return self.render_to_response(
self.get_context_data(form=form)
)
def post(self, request, *args, **kwargs):
form = self.get_form()
form.fields['recipients'].choices = self.recipients
if form.is_valid():
data = form.cleaned_data
template = EmailTemplate(
subject=data['subject'],
body=data['body']
)
try:
typeid = int(request.POST.get("template", None))
template.type = EmailTemplateType.objects.get(id=typeid)
template.key = template.type.key
except (ValueError, TypeError):
pass
context = self.template_context
recipients = self.lookup_recipients(
form.cleaned_data['recipients']
)
KUEmailMessage.send_email(
template, context, recipients, self.object,
original_from_email=KUEmailRecipient.create(request.user)
)
return super(EmailComposeView, self).form_valid(form)
return self.render_to_response(
self.get_context_data(form=form)
)
def get_initial(self):
initial = super(EmailComposeView, self).get_initial()
if self.template_type is not None:
template = \
EmailTemplate.get_template(self.template_type, self.get_unit())
if template is not None:
initial['subject'] = template.subject
initial['body'] = template.body
initial['recipients'] = [id for (id, label) in self.recipients]
return initial
def get_form_kwargs(self):
kwargs = super(EmailComposeView, self).get_form_kwargs()
kwargs['view'] = self
return kwargs
def get_context_data(self, **kwargs):
context = {}
context['templates'] = EmailTemplate.get_template(
self.template_type, self.get_unit(), True
)
context['template_type'] = self.template_type.id \
if self.template_type else None
context['template_unit'] = self.get_unit()
context['modal'] = self.modal
context.update(kwargs)
return super(EmailComposeView, self).get_context_data(**context)
@staticmethod
def encode_recipient(recipient):
recipient_type = None
id = None
email = None
if isinstance(recipient, Booking):
recipient = recipient.booker
if isinstance(recipient, Guest):
recipient_type = EmailComposeView.RECIPIENT_BOOKER
id = recipient.id
email = recipient.get_full_email()
elif isinstance(recipient, User):
recipient_type = EmailComposeView.RECIPIENT_USER
id = recipient.username
email = full_email(recipient.email, recipient.get_full_name())
elif isinstance(recipient, RoomResponsible):
recipient_type = EmailComposeView.RECIPIENT_ROOMRESPONSIBLE
id = recipient.id
email = full_email(recipient.email, recipient.get_full_name())
key = recipient_type + EmailComposeView.RECIPIENT_SEPARATOR + str(id)
return key, email
@staticmethod
def lookup_recipient(recipient_key):
(recipient_type, id) = recipient_key.split(
EmailComposeView.RECIPIENT_SEPARATOR, 1
)
if recipient_type == EmailComposeView.RECIPIENT_BOOKER:
return Guest.objects.filter(id=id)
elif recipient_type == EmailComposeView.RECIPIENT_USER:
return User.objects.filter(username=id)
elif recipient_type == EmailComposeView.RECIPIENT_CUSTOM:
return id
@staticmethod
def lookup_recipients(recipient_ids):
booker_ids = []
user_ids = []
roomresponsible_ids = []
customs = []
if type(recipient_ids) != list:
recipient_ids = [recipient_ids]
for value in recipient_ids:
(recipient_type, id) = value.split(
EmailComposeView.RECIPIENT_SEPARATOR, 1
)
if recipient_type == "booking": # We allow booking ids for #13804
try:
id = Booking.objects.get(id=id).booker.id
recipient_type = EmailComposeView.RECIPIENT_BOOKER
except Exception:
pass
if recipient_type == EmailComposeView.RECIPIENT_BOOKER:
booker_ids.append(id)
elif recipient_type == EmailComposeView.RECIPIENT_USER:
user_ids.append(id)
elif recipient_type == EmailComposeView.RECIPIENT_CUSTOM:
customs.append(id)
elif recipient_type == EmailComposeView.RECIPIENT_ROOMRESPONSIBLE:
roomresponsible_ids.append(id)
return KUEmailRecipient.multiple(
Guest.objects.filter(id__in=booker_ids),
KUEmailRecipient.TYPE_GUEST
) + KUEmailRecipient.multiple(
User.objects.filter(username__in=user_ids)
) + KUEmailRecipient.multiple(
RoomResponsible.objects.filter(id__in=roomresponsible_ids),
KUEmailRecipient.TYPE_ROOM_RESPONSIBLE
) + KUEmailRecipient.multiple(customs)
def get_unit(self):
return self.request.user.userprofile.organizationalunit
def get_template_names(self):
if self.modal:
return ['email/compose_modal.html']
else:
return ['email/compose.html']
class EmailSuccessView(TemplateView):
template_name = "email/success.html"
class SearchView(SearchEngineMixin, BreadcrumbMixin, ListView):
"""Class for handling main search."""
model = Product
template_name = "product/searchresult.html"
context_object_name = "results"
paginate_by = 10
base_queryset = None
filters = None
from_datetime = None
to_datetime = None
admin_form = None
facet_queryset = None
needs_num_bookings = False
sort_grundskole_fag = False
sort_gymnasie_fag = False
t_from = None
t_to = None
is_public = True
# Search engine exclusion
no_index = True
boolean_choice = (
(1, _('Ja')),
(0, _('Nej')),
)
def dispatch(self, request, *args, **kwargs):
id_match_url = self.check_search_by_id()
if id_match_url:
return redirect(id_match_url)
self.t_from = self.get_date_from_request("from")
self.t_to = self.get_date_from_request("to")
self.is_public = not self.request.user.is_authenticated
# Public searches are always from todays date and onward
if self.is_public and self.t_from is None:
self.t_from = timezone.now()
return super(SearchView, self).dispatch(request, *args, **kwargs)
def check_search_by_id(self):
# Check if we're searching for a given id
if self.request.method.lower() != 'get':
return None
q = self.get_query_string()
if re.match(r'^#?\d+$', q):
if q[0] == "#":
q = q[1:]
try:
res = Product.objects.get(pk=q)
return reverse('product-view', args=[res.pk])
except Product.DoesNotExist:
pass
return None
def get_admin_form(self):
if self.admin_form is None:
if self.request.user.is_authenticated:
qdict = self.request.GET.copy()
qdict['q'] = self.get_query_string()
self.admin_form = AdminProductSearchForm(
qdict,
user=self.request.user
)
self.admin_form.is_valid()
else:
self.admin_form = False
return self.admin_form
def get_date_from_request(self, queryparam):
val = self.request.GET.get(queryparam)
if not val:
return None
try:
val = datetime.strptime(val, '%d-%m-%Y')
val = timezone.make_aware(val)
except Exception:
val = None
return val
def get_query_string(self):
return urlunquote_plus(self.request.GET.get("q", "")).strip()
search_prune = re.compile(r"[^\s\wæøåÆØÅ]+")
def get_base_queryset(self):
if self.base_queryset is None:
searchexpression = self.get_query_string()
if searchexpression:
searchexpression = SearchView.search_prune.sub(
'', searchexpression
)
# We run a raw query on individual words, ANDed together
# and with a wildcard at the end of each word
searchexpression = " & ".join([
"%s:*" % x.strip()
for x in searchexpression.split()
if len(x)
])
query = SearchQuery(searchexpression)
qs = self.model.objects.annotate(
rank=SearchRank(F('search_vector'), query)
).filter(search_vector=query).order_by('-rank')
else:
qs = self.model.objects.all()
needs_no_eventtime = Q(time_mode=Product.TIME_MODE_GUEST_SUGGESTED)
date_cond = Q()
if self.t_from:
date_cond &= Q(
needs_no_eventtime |
Q(eventtime__start__gt=self.t_from)
)
if self.t_to:
# End datetime is midnight of the next day
next_midnight = self.t_to + timedelta(hours=24)
date_cond &= Q(
needs_no_eventtime |
Q(eventtime__start__lte=next_midnight)
)
if self.is_public:
# Accept the product if it has bookable eventtimes in our range
eventtimes = EventTime.objects.filter(bookable=True)
if self.t_to is not None:
eventtimes = eventtimes.filter(start__lte=self.t_to)
if self.t_from is not None:
eventtimes = eventtimes.filter(end__gte=self.t_from)
# A product can have a calendar as well as
# a set of bookable eventtimes
date_cond &= Q(
Q(calendar__isnull=True) |
Q(
Q(calendar__calendarevent__in=CalendarEvent.get_events(
CalendarEvent.AVAILABLE, self.t_from, self.t_to
)) & ~
Q(calendar__calendarevent__in=CalendarEvent.get_events(
CalendarEvent.NOT_AVAILABLE, self.t_from, self.t_to
))
) |
Q(eventtime__in=eventtimes)
)
# Public users only want to search within bookable dates
ok_states = Visit.BOOKABLE_STATES
in_bookable_state = (
needs_no_eventtime |
Q(
Q(eventtime__bookable=True) &
Q(
Q(eventtime__visit__isnull=True) |
Q(eventtime__visit__workflow_status__in=ok_states)
)
)
)
res_controlled = [
Product.TIME_MODE_RESOURCE_CONTROLLED,
Product.TIME_MODE_RESOURCE_CONTROLLED_AUTOASSIGN
]
eventtime_cls = booking_models.EventTime
nonblocked = eventtime_cls.NONBLOCKED_RESOURCE_STATES
not_resource_blocked = (
(~Q(time_mode__in=res_controlled)) |
Q(
time_mode__in=res_controlled,
eventtime__resource_status__in=nonblocked
)
)
always_bookable = Q(
time_mode__in=[
Product.TIME_MODE_NONE,
Product.TIME_MODE_NO_BOOKING,
]
)
qs = qs.filter(
(in_bookable_state & not_resource_blocked & date_cond) |
always_bookable
)
else:
qs = qs.filter(date_cond)
self.from_datetime = self.t_from or ""
self.to_datetime = self.t_to or ""
qs = qs.distinct()
self.base_queryset = qs
return self.base_queryset
def annotate_for_filters(self, qs):
if self.needs_num_bookings:
# This old solution is slow as it causes postgresql to do a group
# by on all the fields which results in all the field being used
# for sorting, which takes a looooong time.
# qs = qs.annotate(
# num_bookings=Count("eventtime__visit__bookings")
# )
sql = '''
SELECT
COUNT(nb_bookings.id)
FROM
booking_product nb_products
JOIN
booking_eventtime nb_eventtimes ON (
nb_products.id = nb_eventtimes.product_id
)
JOIN
booking_visit nb_visits ON (
nb_eventtimes.visit_id = nb_visits.id
)
JOIN
booking_booking nb_bookings ON (
nb_visits.id = nb_bookings.visit_id
)
WHERE
nb_products.id = booking_product.id
'''
qs = qs.annotate(num_bookings=RawSQL(sql, tuple()))
if self.sort_grundskole_fag:
all_subject_id = int(Subject.get_all().id)
sql = """
SELECT
COUNT(nb_productgrundskolefag.subject_id)
FROM
booking_product nb_products
JOIN booking_productgrundskolefag nb_productgrundskolefag ON (
nb_products.id = nb_productgrundskolefag.product_id
)
WHERE
nb_products.id = booking_product.id
AND nb_productgrundskolefag.subject_id != %d
""" % all_subject_id
qs = qs.annotate(
num_grundskolefag=RawSQL(sql, tuple())
).order_by('-num_grundskolefag')
elif self.sort_gymnasie_fag:
all_subject_id = int(Subject.get_all().id)
sql = """
SELECT
COUNT(nb_productgymnasiefag.subject_id)
FROM
booking_product nb_products
JOIN booking_productgymnasiefag nb_productgymnasiefag ON (
nb_products.id = nb_productgymnasiefag.product_id
)
WHERE
nb_products.id = booking_product.id
AND nb_productgymnasiefag.subject_id != %d
""" % all_subject_id
qs = qs.annotate(
num_gymnasiefag=RawSQL(sql, tuple())
).order_by('-num_gymnasiefag')
return qs
def get_filters(self):
if self.filters is None:
self.filters = {}
for filter_method in (
self.filter_by_institution,
self.filter_by_type,
self.filter_by_gymnasiefag,
self.filter_by_grundskolefag
):
try:
filter_method()
except Exception as e:
print("Error while filtering query: %s" % e)
if not self.request.user.is_authenticated:
self.filter_for_public_view()
else:
self.filter_for_admin_view(self.get_admin_form())
return self.filters
def filter_for_public_view(self):
# Public users can only see active resources
self.filters["state__in"] = [Product.ACTIVE]
def filter_by_institution(self):
i = [x for x in self.request.GET.getlist("i")]
if i:
i.append(Subject.SUBJECT_TYPE_BOTH)
self.filters["institution_level__in"] = i
def filter_by_type(self):
t = self.request.GET.getlist("t")
if t:
self.filters["type__in"] = t
def filter_by_gymnasiefag(self):
f = self.request.GET.getlist("f")
if f:
self.filters["gymnasiefag__in"] = f + [Subject.get_all().pk]
self.sort_gymnasie_fag = True
def filter_by_grundskolefag(self):
g = self.request.GET.getlist("g")
if g:
self.filters["grundskolefag__in"] = g + [Subject.get_all().pk]
self.sort_grundskole_fag = True
def filter_for_admin_view(self, form):
for filter_method in (
self.filter_by_state,
self.filter_by_is_visit,
self.filter_by_has_bookings,
self.filter_by_unit,
):
try:
filter_method(form)
except Exception as e:
print("Error while admin-filtering query: %s" % e)
def filter_by_state(self, form):
s = form.cleaned_data.get("s", "")
if s != "":
self.filters["state"] = s
def filter_by_is_visit(self, form):
v = form.cleaned_data.get("v", "")
if v == "":
return
v = int(v)
if v == AdminProductSearchForm.IS_VISIT:
self.filters["time_mode__in"] = [
x[0] for x in Product.time_mode_choices
if x[0] != Product.TIME_MODE_NONE
]
else:
self.filters["time_mode"] = Product.TIME_MODE_NONE
def filter_by_has_bookings(self, form):
b = form.cleaned_data.get("b", "")
if b == "":
self.needs_num_bookings = False
return
b = int(b)
if b == AdminProductSearchForm.HAS_BOOKINGS:
self.needs_num_bookings = True
self.filters["num_bookings__gt"] = 0
elif b == AdminProductSearchForm.HAS_NO_BOOKINGS:
self.needs_num_bookings = True
self.filters["num_bookings"] = 0
def filter_by_unit(self, form):
u = form.cleaned_data.get("u", "")
if u == "":
return
u = int(u)
if u == AdminProductSearchForm.MY_UNIT:
self.filters["organizationalunit"] = \
self.request.user.userprofile.organizationalunit
elif u == AdminProductSearchForm.MY_FACULTY:
self.filters["organizationalunit"] = \
self.request.user.userprofile\
.organizationalunit.get_faculty_queryset()
elif u == AdminProductSearchForm.MY_UNITS:
self.filters["organizationalunit"] = \
self.user.userprofile.get_unit_queryset()
else:
self.filters["organizationalunit__pk"] = u
def get_facet_queryset(self):
if self.facet_queryset is None:
self.facet_queryset = Product.objects.filter(
pk__in=[x["pk"] for x in self.get_base_queryset().values("pk")]
)
self.facet_queryset = self.annotate_for_filters(
self.facet_queryset
)
return self.facet_queryset
def get_queryset(self):
filters = self.get_filters()
qs = self.get_base_queryset()
qs = self.annotate_for_filters(qs)
filter_args = [v for k, v in filters.items() if k.startswith('__')]
filter_kwargs = {
k: v for k, v in filters.items() if not k.startswith('__')
}
qs = qs.filter(*filter_args, **filter_kwargs)
qs = qs.prefetch_related(
'productgymnasiefag_set', 'productgrundskolefag_set'
)
return qs
def make_facet(self, facet_field, choice_tuples, selected,
selected_value='checked="checked"',
add_to_all=None, unsubjected=None):
hits = {}
# Remove filter for the field we want to facetize
filters = self.get_filters()
new_filter_args = [
v for k, v in filters.items()
if k.startswith('__') and not k.startswith('__' + facet_field)
]
new_filter_kwargs = {
k: v for k, v in filters.items()
if not k.startswith(facet_field) and not k.startswith('__')
}
facet_qs = Product.objects.filter(
pk__in=self.get_facet_queryset().filter(
*new_filter_args,
**new_filter_kwargs
)
)
qs = facet_qs.values(facet_field).annotate(hits=Count("pk"))
for item in qs:
hits[item[facet_field]] = item["hits"]
# This adds all hits on a certain keys to the hits of all other keys.
if add_to_all is not None:
keys = set(add_to_all)
to_add = 0
for key in keys:
if key in hits:
to_add = to_add + hits[key]
del hits[key]
for v, n in choice_tuples:
if v in keys:
continue
if v in hits:
hits[v] += to_add
else:
hits[v] = to_add
return self.choices_from_hits(choice_tuples, hits, unsubjected,
selected, selected_value=selected_value)
def choices_from_hits(self, choice_tuples, hits, additional, selected,
selected_value='checked="checked"'):
selected = set(selected)
choices = []
for value, name in choice_tuples:
if value not in hits:
continue
if str(value) in selected:
sel = 'checked="checked"'
else:
sel = ''
choices.append({
'label': name,
'value': value,
'selected': sel,
'hits': hits[value],
'additional': additional
})
return choices
def get_context_data(self, **kwargs):
context = {}
context['adminform'] = self.get_admin_form()
# Store the querystring without the page and pagesize arguments
qdict = self.request.GET.copy()
if "page" in qdict:
qdict.pop("page")
if "pagesize" in qdict:
qdict.pop("pagesize")
context["qstring"] = qdict.urlencode()
context["q"] = self.get_query_string()
context['pagesizes'] = [5, 10, 15, 20]
context["institution_choices"] = self.make_facet(
"institution_level",
self.model.institution_choices,
self.request.GET.getlist("i"),
add_to_all=[Subject.SUBJECT_TYPE_BOTH]
)
context["type_choices"] = self.make_facet(
"type",
self.model.resource_type_choices,
self.request.GET.getlist("t"),
)
context['hiddenrepeats'] = []
list = self.request.GET.getlist("i", None)
if list is not None:
for x in list:
context['hiddenrepeats'].append({'name': "i", 'value': x})
list = self.request.GET.getlist("a", None)
if list is not None:
for x in list:
context['hiddenrepeats'].append({'name': "a", 'value': x})
list = self.request.GET.getlist("t", None)
if list is not None:
for x in list:
context['hiddenrepeats'].append({'name': "t", 'value': x})
list = self.request.GET.getlist("f", None)
if list is not None:
for x in list:
context['hiddenrepeats'].append({'name': "f", 'value': x})
list = self.request.GET.getlist("from", None)
if list is not None:
for x in list:
context['hiddenrepeats'].append({'name': "from", 'value': x})
list = self.request.GET.getlist("to", None)
if list is not None:
for x in list:
context['hiddenrepeats'].append({'name': "to", 'value': x})
gym_subject_choices = []
gs_subject_choices = []
for s in Subject.objects.exclude(name=Subject.ALL_NAME):
val = (s.pk, s.name)
if s.subject_type & Subject.SUBJECT_TYPE_GYMNASIE:
gym_subject_choices.append(val)
if s.subject_type & Subject.SUBJECT_TYPE_GRUNDSKOLE:
gs_subject_choices.append(val)
gym_selected = self.request.GET.getlist("f")
context["gymnasie_selected"] = gym_selected
context["gymnasie_choices"] = self.make_facet(
"gymnasiefag",
gym_subject_choices,
gym_selected,
unsubjected=self.get_facet_queryset().filter(
gymnasiefag=Subject.get_all()
).count()
)
gs_selected = self.request.GET.getlist("g")
context["grundskole_selected"] = gs_selected
context["grundskole_choices"] = self.make_facet(
"grundskolefag",
gs_subject_choices,
gs_selected,
unsubjected=self.get_facet_queryset().filter(
grundskolefag=Subject.get_all()
).count()
)