-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathbase.py
More file actions
1805 lines (1447 loc) · 60.6 KB
/
base.py
File metadata and controls
1805 lines (1447 loc) · 60.6 KB
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
import csv
import json
from collections import Counter, defaultdict
from collections.abc import Callable
from datetime import timedelta
from http import HTTPStatus
from io import BytesIO, StringIO
from itertools import combinations
from typing import Any, Literal, get_args
import dateutil
from flask import (
abort,
flash,
jsonify,
redirect,
render_template,
request,
send_file,
session,
url_for,
)
from flask import (
current_app as app,
)
from flask.typing import ResponseReturnValue
from flask_login import current_user
from flask_mailman import EmailMessage
from sqlalchemy import and_, desc, func, select
from sqlalchemy.orm import joinedload, selectinload, undefer
from sqlalchemy_continuum.utils import version_class
from wtforms import FormField
from apps.common import get_next_url
from apps.common.email import enqueue_email
from main import db, external_url, get_or_404
from models.content import (
SCHEDULE_ITEM_INFOS,
Lottery,
Occurrence,
Proposal,
ProposalMessage,
ProposalRound,
ProposalState,
ProposalTag,
ProposalType,
ProposalVote,
Round,
ScheduleItem,
ScheduleItemState,
ScheduleItemType,
Tag,
Venue,
)
from models.content.attributes import convert_attributes_between_types
from models.permission import Permission
from models.purchase import AdmissionTicket
from models.user import User
from ..config import config
from . import (
admin_required,
cfp_review,
get_next_proposal_to,
schedule_required,
sort_proposals,
sort_schedule_items,
)
from .estimation import get_cfp_estimate
from .forms import (
UPDATE_PROPOSAL_ATTRIBUTES_FORM_TYPES,
UPDATE_SCHEDULE_ITEM_ATTRIBUTES_FORM_TYPES,
AcceptanceForm,
ChangeProposalOwner,
ChangeScheduleItemOwner,
CloseRoundForm,
ConvertProposalForm,
ConvertScheduleItemForm,
CreateOccurrenceForm,
InviteSpeakerForm,
LotteryForm,
PrivateNotesForm,
ReversionForm,
SendMessageForm,
UpdateOccurrenceForm,
UpdateProposalForm,
UpdateScheduleItemForm,
UpdateVotesForm,
)
from .majority_judgement import calculate_max_normalised_score
@cfp_review.route("/")
def main() -> ResponseReturnValue:
if current_user.is_anonymous:
return redirect(url_for("users.login", next=url_for(".main")))
if current_user.has_permission("cfp_admin"):
return redirect(url_for(".proposals"))
if current_user.has_permission("cfp_anonymiser"):
return redirect(url_for(".anonymisation"))
if current_user.has_permission("cfp_reviewer"):
return redirect(url_for(".review_list"))
abort(404)
@cfp_review.route("help")
def help():
if current_user.is_anonymous:
return redirect(url_for("users.login", next=url_for(".main")))
return render_template("cfp_review/help.html")
def bool_qs(val):
# Explicit true/false values are better than the implicit notset=&set=anything that bool does
if val in ["True", "1"]:
return True
if val in ["False", "0"]:
return False
raise ValueError("Invalid querystring boolean")
def filter_proposal_request() -> tuple[list[Proposal], bool]:
proposal_query = select(Proposal)
is_filtered = False
bool_names: list[str] = ["one_day", "needs_help", "needs_money"]
bool_vals = [request.args.get(n, type=bool_qs) for n in bool_names]
bool_dict = {n: v for n, v in zip(bool_names, bool_vals, strict=True) if v is not None}
if bool_dict:
is_filtered = True
proposal_query = proposal_query.filter_by(**bool_dict)
types = request.args.getlist("type")
if types:
is_filtered = True
proposal_query = proposal_query.where(Proposal.type.in_(types))
states = request.args.getlist("state")
if states:
is_filtered = True
proposal_query = proposal_query.where(Proposal.state.in_(states))
needs_ticket = request.args.get("needs_ticket", type=bool_qs)
if needs_ticket is True:
is_filtered = True
proposal_query = proposal_query.where(
~Proposal.user.has(User.will_have_ticket.is_(True)),
~Proposal.user.has(
User.owned_admission_tickets.any(AdmissionTicket.state.in_(["paid", "payment-pending"]))
),
)
tags = request.args.getlist("tags")
if "untagged" in tags:
if len(tags) > 1:
flash("'untagged' in 'tags' arg, other tags ignored")
is_filtered = True
proposal_query = proposal_query.where(~Proposal._tags.any())
elif tags:
is_filtered = True
proposal_query = proposal_query.where(Proposal._tags.any(Tag.tag.in_(tags)))
proposal_query = proposal_query.options(
selectinload(Proposal.user).selectinload(User.owned_tickets)
).options(selectinload(Proposal._tags))
proposals = list(db.session.scalars(proposal_query))
sort_proposals(proposals)
return proposals, is_filtered
def filter_schedule_item_request() -> tuple[list[ScheduleItem], bool]:
schedule_item_query = select(ScheduleItem)
is_filtered = False
bool_names: list[str] = []
bool_vals = [request.args.get(n, type=bool_qs) for n in bool_names]
bool_dict = {n: v for n, v in zip(bool_names, bool_vals, strict=True) if v is not None}
if bool_dict:
is_filtered = True
schedule_item_query = schedule_item_query.filter_by(**bool_dict)
types = request.args.getlist("type")
if types:
is_filtered = True
schedule_item_query = schedule_item_query.where(ScheduleItem.type.in_(types))
states = request.args.getlist("state")
if states:
is_filtered = True
schedule_item_query = schedule_item_query.where(ScheduleItem.state.in_(states))
official_content = sorted(request.args.getlist("official_content"))
if official_content == ["attendee"] or official_content == ["official"]:
is_filtered = True
official_content_bool = official_content == ["official"]
schedule_item_query = schedule_item_query.where(
ScheduleItem.official_content == official_content_bool
)
schedule_item_query = schedule_item_query.options(selectinload(ScheduleItem.occurrences)).options(
undefer(ScheduleItem.favourite_count)
)
schedule_items = list(db.session.scalars(schedule_item_query))
sort_schedule_items(schedule_items)
return schedule_items, is_filtered
@cfp_review.route("/proposals")
@admin_required
def proposals() -> ResponseReturnValue:
proposals, is_filtered = filter_proposal_request()
non_sort_query_string = request.args.to_dict(flat=False)
non_sort_query_string.pop("sort_by", None)
non_sort_query_string.pop("reverse", None)
tag_counts = dict(
db.session.query(Tag.tag, db.func.count(ProposalTag.c.proposal_id))
.select_from(Tag)
.outerjoin(ProposalTag)
.group_by(Tag.tag)
.order_by(Tag.tag)
.all()
)
tag_counts = {tag: [0, total_count] for tag, total_count in tag_counts.items()}
for proposal in proposals:
for tag in proposal.tags:
tag_counts[tag][0] += 1
return render_template(
"cfp_review/proposals.html",
proposals=proposals,
new_qs=non_sort_query_string,
is_filtered=is_filtered,
total_proposals=db.session.scalar(select(func.count(Proposal.id))),
tag_counts=tag_counts,
)
@cfp_review.route("/schedule-items")
@admin_required
def schedule_items() -> ResponseReturnValue:
schedule_items, is_filtered = filter_schedule_item_request()
non_sort_query_string: dict[str, list[str]] = request.args.to_dict(flat=False)
non_sort_query_string.pop("sort_by", None)
non_sort_query_string.pop("reverse", None)
return render_template(
"cfp_review/schedule_items.html",
schedule_items=schedule_items,
new_qs=non_sort_query_string,
is_filtered=is_filtered,
total_schedule_items=db.session.scalar(select(func.count(ScheduleItem.id))),
)
@cfp_review.route("/schedule-items.<format>")
@admin_required
def export_schedule_items(format: str) -> ResponseReturnValue:
fields = [
"id",
"state",
"names",
"pronouns",
"type",
"title",
"description",
"short_description",
"duration",
"arrival_period",
"departure_period",
"available_times",
"contact_telephone",
"contact_eventphone",
"official_content",
"equipment_required",
"funding_required",
"notice_required",
"additional_info",
# FIXME: do we need any of these?
# "tags",
# "favourite_count",
]
# Do not call this with untrusted field values
def get_field(proposal, field_path):
val = proposal
for field in field_path.split("."):
val = getattr(val, field)
return val
schedule_items, _ = filter_schedule_item_request()
if format == "csv":
mime = "text/csv"
buf = StringIO()
w = csv.writer(buf)
# Header row
w.writerow(fields)
for s in schedule_items:
cells = []
for field in fields:
cell = get_field(s, field)
cells.append(cell)
w.writerow(cells)
out = buf.getvalue()
elif format == "json":
mime = "application/json"
out = json.dumps(
[{a: get_field(s, a) for a in fields} for s in schedule_items],
default=str,
)
else:
abort(HTTPStatus.BAD_REQUEST, "Unsupported export format")
return send_file(
BytesIO(out.encode()),
mime,
as_attachment=True,
download_name=f"proposals.{format}",
)
ProposalEmailReason = Literal[
"accepted",
"still-considered",
"rejected",
"check-scheduled-duration",
"please-finalise",
"reserve-list",
"slot-scheduled",
"slot-moved",
]
def send_email_for_proposal(proposal: Proposal, reason: ProposalEmailReason) -> None:
from_email_ = config.from_email("CONTENT_EMAIL")
title = (proposal.schedule_item and proposal.schedule_item.title) or proposal.title
if reason == "accepted":
subject = f'''Your EMF {proposal.human_type} "{title}" has been accepted!'''
template = "cfp_review/email/accepted_msg.txt"
elif reason == "still-considered":
subject = f'''We're still considering your EMF {proposal.human_type} "{title}"'''
template = "cfp_review/email/still_considering.txt"
elif reason == "rejected":
# remember to set rejected_email_sent
subject = f'''Your EMF {proposal.human_type} "{title}" was not accepted.'''
template = "emails/cfp-rejected.txt"
elif reason == "reserve-list":
subject = f'''Your EMF {proposal.human_type} "{title}", and EMF tickets'''
template = "emails/cfp-reserve-list.txt"
from_email_ = config.from_email("SPEAKERS_EMAIL")
elif reason == "please-finalise":
# Can be sent before or after scheduling. We want them
# to update for the line-up, so the earlier the better.
subject = f'''We need information about your EMF {proposal.human_type} "{title}"'''
template = "emails/cfp-please-finalise.txt"
from_email_ = config.from_email("SPEAKERS_EMAIL")
elif reason == "check-scheduled-duration":
# This email is basically the same as "please-finalise" but less urgent
subject = f'''Your EMF {proposal.human_type} "{title}" is ready to schedule, please check your slot'''
template = "emails/cfp-check-scheduled-duration.txt"
from_email_ = config.from_email("SPEAKERS_EMAIL")
elif reason == "slot-scheduled":
subject = f'''Your EMF {proposal.human_type} "{title}" has been scheduled'''
template = "emails/cfp-slot-scheduled.txt"
from_email_ = config.from_email("SPEAKERS_EMAIL")
elif reason == "slot-moved":
# TODO: might be nice to highlight which slot has moved
subject = f'''Your EMF {proposal.human_type} slot has been moved ("{title}")'''
template = "emails/cfp-slot-moved.txt"
from_email_ = config.from_email("SPEAKERS_EMAIL")
else:
raise Exception(f"Invalid proposal email type {reason}")
app.logger.info("Sending %s email for proposal %s", reason, proposal.id)
text_body = render_template(
template,
user=proposal.user,
proposal=proposal,
reserve_ticket_link=app.config["RESERVE_LIST_TICKET_LINK"],
)
enqueue_email(
recipient=proposal.user,
from_email=from_email_,
subject=subject,
text_body=text_body,
)
@cfp_review.route("/proposals/<int:proposal_id>/convert", methods=["GET", "POST"])
@admin_required
def convert_proposal(proposal_id: int) -> ResponseReturnValue:
proposal = get_or_404(db, Proposal, proposal_id)
form = ConvertProposalForm()
types = get_args(ProposalType)
form.new_type.choices = [(t, t.title()) for t in types if t != proposal.type]
if form.validate_on_submit():
new_type = form.new_type.data
old_attributes = proposal.attributes
proposal.type = new_type # affects type_info
new_attributes = proposal.type_info.attributes_cls()
convert_attributes_between_types(old_attributes, new_attributes)
proposal.attributes = new_attributes
if proposal.schedule_item:
schedule_item: ScheduleItem = proposal.schedule_item
# There may be new attributes for the proposer to complete.
# We do not automatically tell them to finalise again, you must send a message.
schedule_item.state = "unpublished"
_convert_schedule_item(schedule_item, new_type)
db.session.commit()
return redirect(url_for(".update_proposal", proposal_id=proposal.id))
return render_template("cfp_review/convert_proposal.html", proposal=proposal, form=form)
@cfp_review.route("/schedule-items/<int:schedule_item_id>/convert", methods=["GET", "POST"])
@admin_required
def convert_schedule_item(schedule_item_id: int) -> ResponseReturnValue:
schedule_item = get_or_404(db, ScheduleItem, schedule_item_id)
if schedule_item.proposal:
# We don't want to get into having mismatched proposal/schedule_item types yet
flash("The schedule item is associated with a proposal, please convert this instead.")
return redirect(url_for(".convert_proposal", proposal_id=schedule_item.proposal_id))
form = ConvertScheduleItemForm()
types = get_args(ScheduleItemType)
form.new_type.choices = [(t, t.title()) for t in types if t != schedule_item.type]
if form.validate_on_submit():
new_type = form.new_type.data
_convert_schedule_item(schedule_item, new_type)
db.session.commit()
return redirect(url_for(".update_schedule_item", schedule_item_id=schedule_item.id))
return render_template("cfp_review/convert_schedule_item.html", schedule_item=schedule_item, form=form)
def _convert_schedule_item(schedule_item: ScheduleItem, new_type: ScheduleItemType) -> None:
# This can also be called by attendee content managers
# People's availability can vary based on type
schedule_item.available_times = None
for occurrence in schedule_item.occurrences:
# Fall back to the defaults, as we don't know why this was set
occurrence.allowed_venues = []
old_attributes = schedule_item.attributes
schedule_item.type = new_type # affects type_info
new_attributes = schedule_item.type_info.attributes_cls()
convert_attributes_between_types(old_attributes, new_attributes)
schedule_item.attributes = new_attributes
def find_next_proposal_id(prop):
if not request.args:
res = get_next_proposal_to(prop, prop.state)
return res.id if res else None
proposals, _ = filter_proposal_request()
try:
idx = proposals.index(prop) + 1
except ValueError:
return None
if len(proposals) <= idx:
return None
return proposals[idx].id
def get_update_proposal_type_form(proposal_type: ProposalType) -> type[UpdateProposalForm]:
class UpdateProposalFormWithAttributes(UpdateProposalForm):
pass
UpdateProposalFormWithAttributes.attributes = FormField(
UPDATE_PROPOSAL_ATTRIBUTES_FORM_TYPES[proposal_type]
)
return UpdateProposalFormWithAttributes
@cfp_review.route("/proposals/<int:proposal_id>", methods=["GET", "POST"])
@admin_required
def update_proposal(proposal_id: int) -> ResponseReturnValue:
def flash_commit_and_go(msg: str, next_page: str, proposal_id: int | None = None) -> ResponseReturnValue:
flash(msg)
app.logger.info(msg)
db.session.commit()
return redirect(url_for(next_page, proposal_id=proposal_id))
proposal = get_or_404(db, Proposal, proposal_id)
next_id = find_next_proposal_id(proposal)
Form = get_update_proposal_type_form(proposal.type)
form = Form(obj=proposal)
form.user_will_have_ticket.data = proposal.user.will_have_ticket
# TODO: this could move to UpdateProposalForm.__init__
tags = db.session.scalars(select(Tag).order_by(Tag.tag))
form.tags.choices = [(t.tag, t.tag) for t in tags]
if form.validate_on_submit():
form.populate_obj(proposal)
proposal.user.will_have_ticket = form.user_will_have_ticket.data
if form.update.data:
msg = f"Updating proposal {proposal_id}"
proposal.state = form.state.data
elif form.reject.data or form.reject_with_message.data:
msg = f"Rejecting proposal {proposal_id}"
proposal.state = "rejected"
if form.reject_with_message.data:
proposal.rejected_email_sent = True
send_email_for_proposal(proposal, reason="rejected")
elif form.accept.data:
msg = f"Manually accepting proposal {proposal_id}"
proposal.accept_proposal()
send_email_for_proposal(proposal, reason="accepted")
elif form.checked.data:
if proposal.type_info.review_type == "manual":
msg = f"Sending proposal {proposal_id} for manual review"
proposal.state = "manual-review"
elif proposal.type_info.review_type == "anonymous":
msg = f"Sending proposal {proposal_id} for anonymisation"
proposal.state = "checked"
else:
msg = f"Not changing state for automatically accepted proposal {proposal_id}"
if not next_id:
return flash_commit_and_go(msg, ".proposals")
return flash_commit_and_go(msg, ".update_proposal", proposal_id=next_id)
return flash_commit_and_go(msg, ".update_proposal", proposal_id=proposal_id)
return render_template(
"cfp_review/proposal.html",
proposal=proposal,
form=form,
next_id=next_id,
)
@cfp_review.route("/proposals/<int:proposal_id>/create-schedule-item", methods=["POST"])
@admin_required
def create_schedule_item_from_proposal(proposal_id: int) -> ResponseReturnValue:
"""
This is usually done on acceptance, but there might be a reason to pre-populate
a schedule with data before we tell the user that their talk has been accepted.
"""
proposal = get_or_404(db, Proposal, proposal_id)
if proposal.schedule_item:
flash("Proposal already has a schedule item")
return redirect(url_for(".update_proposal", proposal_id=proposal.id))
schedule_item = proposal.create_schedule_item()
db.session.add(schedule_item)
db.session.commit()
return redirect(url_for(".update_schedule_item", schedule_item_id=schedule_item.id))
def get_update_schedule_item_type_form(schedule_item_type: ScheduleItemType) -> type[UpdateScheduleItemForm]:
class UpdateScheduleItemFormWithAttributes(UpdateScheduleItemForm):
pass
UpdateScheduleItemFormWithAttributes.attributes = FormField(
UPDATE_SCHEDULE_ITEM_ATTRIBUTES_FORM_TYPES[schedule_item_type]
)
return UpdateScheduleItemFormWithAttributes
@cfp_review.route("/schedule-items/<int:schedule_item_id>", methods=["GET", "POST"])
@admin_required
def update_schedule_item(schedule_item_id: int) -> ResponseReturnValue:
schedule_item = get_or_404(db, ScheduleItem, schedule_item_id)
Form = get_update_schedule_item_type_form(schedule_item.type)
form = Form(obj=schedule_item)
if form.validate_on_submit():
form.populate_obj(schedule_item)
if form.update.data:
msg = f"Updating schedule item {schedule_item_id}"
flash(msg)
app.logger.info(msg)
db.session.commit()
return redirect(url_for(".update_schedule_item", schedule_item_id=schedule_item_id))
if request.method != "POST":
form.official_content.data = (schedule_item.official_content and "official") or "attendee"
occurrence_form = CreateOccurrenceForm()
return render_template(
"cfp_review/schedule_item.html",
schedule_item=schedule_item,
form=form,
occurrence_form=occurrence_form,
)
@cfp_review.route("/schedule-items/<int:schedule_item_id>/occurrences", methods=["POST"])
@admin_required
def occurrences(schedule_item_id: int) -> ResponseReturnValue:
schedule_item = get_or_404(db, ScheduleItem, schedule_item_id)
form = CreateOccurrenceForm()
if form.validate_on_submit():
occurrence_num = 1
for occurrence in schedule_item.occurrences:
if occurrence.occurrence_num == occurrence_num:
occurrence_num += 1
else:
break
occurrence = Occurrence(
schedule_item=schedule_item,
occurrence_num=occurrence_num,
state="unscheduled",
video_privacy=schedule_item.default_video_privacy,
)
schedule_item.occurrences.append(occurrence)
db.session.add(occurrence)
db.session.commit()
return redirect(
url_for(".update_occurrence", schedule_item_id=schedule_item.id, occurrence_id=occurrence.id)
)
return redirect(url_for(".update_schedule_item", schedule_item_id=schedule_item.id))
def get_update_occurrence_type_form(schedule_item_type: ScheduleItemType) -> type[UpdateOccurrenceForm]:
type_info = SCHEDULE_ITEM_INFOS[schedule_item_type]
if not type_info.supports_lottery:
return UpdateOccurrenceForm
class UpdateOccurrenceFormWithLottery(UpdateOccurrenceForm):
pass
UpdateOccurrenceFormWithLottery.lottery = FormField(LotteryForm)
return UpdateOccurrenceFormWithLottery
@cfp_review.route(
"/schedule-items/<int:schedule_item_id>/occurrences/<int:occurrence_id>", methods=["GET", "POST"]
)
@admin_required
def update_occurrence(schedule_item_id: int, occurrence_id: int) -> ResponseReturnValue:
occurrence: Occurrence | None = db.session.scalar(
select(Occurrence)
.filter_by(id=occurrence_id, schedule_item_id=schedule_item_id)
.options(selectinload(Occurrence.schedule_item))
)
if not occurrence:
abort(404)
Form = get_update_occurrence_type_form(occurrence.schedule_item.type)
form = Form(obj=occurrence)
valid_allowed_venues = set(occurrence.valid_allowed_venues)
# We don't block saving an occurrence if the valid list has changed
# allowed_venues is an input into the scheduler, not a constraint on us
valid_allowed_venues |= set(occurrence.allowed_venues)
if occurrence.potential_venue:
valid_allowed_venues.add(occurrence.potential_venue)
if occurrence.scheduled_venue:
valid_allowed_venues.add(occurrence.scheduled_venue)
venues_dict = {v.id: v for v in valid_allowed_venues}
allowed_venue_choices = [
(str(v.id), v.name) for v in sorted(valid_allowed_venues, key=lambda v: v.priority, reverse=True)
]
form.allowed_venue_ids.choices = allowed_venue_choices
form.scheduled_venue_id.choices = [("", "")] + allowed_venue_choices
form.potential_venue_id.choices = [("", "")] + allowed_venue_choices
if form.validate_on_submit():
if occurrence.schedule_item.type_info.supports_lottery and not occurrence.lottery:
occurrence.lottery = Lottery(
occurrence=occurrence,
)
db.session.add(occurrence.lottery)
form.populate_obj(occurrence)
# FIXME: this is horrible
allowed_times = form.allowed_times_str.data
assert allowed_times is not None
# Apparently this was required for Windows (presumably IE) users
# Let's see if it still happens
if "\r" in allowed_times:
app.logger.warning("Fixing up newlines")
allowed_times = allowed_times.replace("\r\n", "\n")
allowed_times = allowed_times.strip()
if occurrence.get_allowed_time_periods_serialised().strip() != allowed_times:
occurrence.allowed_times = allowed_times or None
assert form.allowed_venue_ids.data is not None
occurrence.allowed_venues = [venues_dict[v] for v in form.allowed_venue_ids.data]
db.session.commit()
return redirect(
url_for(".update_occurrence", schedule_item_id=schedule_item_id, occurrence_id=occurrence_id)
)
if request.method != "POST":
form.allowed_times_str.data = occurrence.allowed_times or ""
form.allowed_venue_ids.data = [v.id for v in occurrence.valid_allowed_venues]
if occurrence.schedule_item.type_info.supports_lottery:
form.lottery.max_tickets_per_entry.default = (
occurrence.schedule_item.type_info.default_max_tickets_per_entry
)
return render_template(
"cfp_review/occurrence.html",
schedule_item=occurrence.schedule_item,
occurrence=occurrence,
form=form,
)
def sort_messages(messages: list[Proposal]) -> None:
sort_keys: dict[str, Callable[[Proposal], Any]] = {
"unread": lambda p: (p.get_unread_count(current_user) > 0, p.messages[-1].created),
"date": lambda p: p.messages[-1].created,
"from": lambda p: p.user.name,
"title": lambda p: p.title,
"count": lambda p: len(p.messages),
}
sort_by_key = request.args.get("sort_by", "unread")
reverse = bool(request.args.get("reverse"))
# If unread sort order we have to have unread on top which means reverse sort
if sort_by_key is None or sort_by_key == "unread":
reverse = True
messages.sort(
key=sort_keys.get(sort_by_key, sort_keys["unread"]),
reverse=reverse,
)
@cfp_review.route("/messages")
@admin_required
def messages():
proposals_with_messages_query = (
select(Proposal)
.join(Proposal.messages)
.order_by(ProposalMessage.has_been_read, ProposalMessage.created.desc())
.options(joinedload(Proposal.messages))
)
filter_type = request.args.get("type")
if filter_type:
proposals_with_messages_query = proposals_with_messages_query.filter(Proposal.type == filter_type)
else:
filter_type = "all"
proposals_with_messages = list(db.session.scalars(proposals_with_messages_query).unique())
sort_messages(proposals_with_messages)
return render_template(
"cfp_review/messages.html",
proposals_with_messages=proposals_with_messages,
type=filter_type,
)
@cfp_review.route("/proposals/<int:proposal_id>/message", methods=["GET", "POST"])
@admin_required
def message_proposer(proposal_id):
form = SendMessageForm()
proposal = get_or_404(db, Proposal, proposal_id)
if form.validate_on_submit():
if form.send.data:
msg = ProposalMessage()
msg.is_to_admin = False
msg.from_user_id = current_user.id
msg.proposal_id = proposal_id
msg.message = form.message.data
db.session.add(msg)
db.session.commit()
app.logger.info("Sending message from %s to %s", current_user.id, proposal.user_id)
msg_url = external_url("cfp.proposal_messages", proposal_id=proposal_id)
msg = EmailMessage(
"New message about your EMF proposal",
from_email=config.from_email("CONTENT_EMAIL"),
to=[proposal.user.email],
)
msg.body = render_template(
"cfp_review/email/new_message.txt",
url=msg_url,
to_user=proposal.user,
from_user=current_user,
proposal=proposal,
)
msg.send()
count = proposal.mark_messages_read(current_user)
db.session.commit()
app.logger.info(f"Marked {count} messages to admin on proposal {proposal.id} as read")
return redirect(url_for(".message_proposer", proposal_id=proposal_id))
# Admin can see all messages sent in relation to a proposal
messages = ProposalMessage.query.filter_by(proposal_id=proposal_id).order_by("created").all()
return render_template(
"cfp_review/message_proposer.html",
form=form,
messages=messages,
proposal=proposal,
)
VersionedEntityType = Literal["proposal", "schedule-item", "occurrence"]
@cfp_review.route("/versions/<entity_type>")
@admin_required
def entity_changelog(entity_type: VersionedEntityType) -> ResponseReturnValue:
if entity_type == "proposal":
version_cls = version_class(Proposal)
elif entity_type == "schedule-item":
version_cls = version_class(ScheduleItem)
elif entity_type == "occurrence":
version_cls = version_class(Occurrence)
else:
abort(404)
size = int(request.args.get("size", "100"))
versions = version_cls.query.order_by(version_cls.transaction_id.desc(), version_cls.modified.desc())
paged_versions = db.paginate(versions, per_page=size, error_out=False)
return render_template(
"cfp_review/entity_changelog.html", versions=paged_versions, entity_type=entity_type
)
@cfp_review.route("/versions/<entity_type>/<int:entity_id>")
@admin_required
def entity_latest_version(entity_type: VersionedEntityType, entity_id: int) -> ResponseReturnValue:
entity: Proposal | ScheduleItem | Occurrence
if entity_type == "proposal":
entity = get_or_404(db, Proposal, entity_id)
elif entity_type == "schedule-item":
entity = get_or_404(db, ScheduleItem, entity_id)
elif entity_type == "occurrence":
entity = get_or_404(db, Occurrence, entity_id)
else:
abort(404)
last_txn_id = list(entity.versions)[-1].transaction_id # type: ignore[union-attr]
return redirect(
url_for(".entity_version", entity_type=entity_type, entity_id=entity_id, txn_id=last_txn_id)
)
@cfp_review.route("/versions/<entity_type>/<int:entity_id>/<int:txn_id>", methods=["GET", "POST"])
@admin_required
def entity_version(entity_type: VersionedEntityType, entity_id: int, txn_id: int) -> ResponseReturnValue:
entity: Proposal | ScheduleItem | Occurrence
if entity_type == "proposal":
entity = get_or_404(db, Proposal, entity_id)
elif entity_type == "schedule-item":
entity = get_or_404(db, ScheduleItem, entity_id)
elif entity_type == "occurrence":
entity = get_or_404(db, Occurrence, entity_id)
else:
abort(404)
form = ReversionForm()
version = entity.versions.filter_by(transaction_id=txn_id).one() # type: ignore[union-attr]
if form.validate_on_submit():
app.logger.info(f"Reverting {entity_type} {entity_id} to transaction {txn_id}")
version.revert()
db.session.commit()
return redirect(url_for(".entity_latest_version", entity_type=entity_type, entity_id=entity_id))
return render_template(
"cfp_review/entity_version.html",
form=form,
entity_type=entity_type,
entity=entity,
version=version,
)
@cfp_review.route("/message-batch", methods=["GET", "POST"])
@admin_required
def message_batch():
proposals, _is_filtered = filter_proposal_request()
form = SendMessageForm()
if form.validate_on_submit():
if form.send.data:
for proposal in proposals:
msg = ProposalMessage()
msg.is_to_admin = False
msg.from_user_id = current_user.id
msg.proposal_id = proposal.id
msg.message = form.message.data
db.session.add(msg)
db.session.commit()
app.logger.info("Sending message from %s to %s", current_user.id, proposal.user_id)
msg_url = external_url("cfp.proposal_messages", proposal_id=proposal.id)
msg = EmailMessage(
"New message about your EMF proposal",
from_email=config.from_email("CONTENT_EMAIL"),
to=[proposal.user.email],
)
msg.body = render_template(
"cfp_review/email/new_message.txt",
url=msg_url,
to_user=proposal.user,
from_user=current_user,
proposal=proposal,
)
msg.send()
flash(f"Messaged {len(proposals)} proposals", "info")
return redirect(url_for(".proposals", **request.args))
return render_template("cfp_review/message_batch.html", form=form, proposals=proposals)
def sort_for_vote_summary(proposals_with_state_counts: list[tuple[Proposal, dict[str, int]]]) -> None:
sort_keys: dict[str, Callable[[tuple[Proposal, dict[str, int]]], Any]] = {
# Notes == unread first then by date
"notes": lambda p: (
p[0].get_unread_vote_note_count() > 0,
p[0].get_total_vote_note_count(),
),
"date": lambda p: p[0].created,
"title": lambda p: p[0].title.lower(),
"votes": lambda p: p[1].get("voted", 0),
"blocked": lambda p: p[1].get("blocked", 0),
"recused": lambda p: p[1].get("recused", 0),
}
proposals_with_state_counts.sort(
key=sort_keys.get(request.args.get("sort_by", "notes"), sort_keys["notes"]),
reverse=bool(request.args.get("reverse")),
)
@cfp_review.route("/votes")
@admin_required
def vote_summary() -> ResponseReturnValue:
proposal_query = select(Proposal).options(joinedload(Proposal.votes)).order_by("modified")