summaryrefslogtreecommitdiff
path: root/postgresqleu/confreg/models.py
blob: 33871c45afc493fad4192eb2ec685aedeef51efc (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.db.models import Q
from django.db.models.expressions import F
from django.contrib.auth.models import User
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator, MaxValueValidator, RegexValidator
from django.utils.dateformat import DateFormat
from django.utils.functional import cached_property
from django.utils import timezone
from django.template.defaultfilters import slugify
from django.contrib.postgres.fields import DateTimeRangeField, JSONField
from django.contrib.postgres.indexes import GinIndex
from django.core.serializers.json import DjangoJSONEncoder

from postgresqleu.util.validators import validate_lowercase, validate_urlname
from postgresqleu.util.validators import TwitterValidator
from postgresqleu.util.validators import PictureUrlValidator
from postgresqleu.util.forms import ChoiceArrayField
from postgresqleu.util.fields import LowercaseEmailField, ImageBinaryField, PdfBinaryField
from postgresqleu.util.time import today_conference
from postgresqleu.util.db import exec_no_result

import base64
import pytz
from decimal import Decimal

from postgresqleu.countries.models import Country
from postgresqleu.invoices.models import Invoice, VatRate, InvoicePaymentMethod
from postgresqleu.newsevents.models import NewsPosterProfile

from .regtypes import special_reg_types

SKILL_CHOICES = (
    (0, "Beginner"),
    (1, "Intermediate"),
    (2, "Advanced"),
)

TWITTER_POST_CHOICES = (
    (0, "Nobody can post"),
    (1, "Admins can post without approval, volunteers can't post"),
    (2, "Volunteers can post, require admin approval"),
    (3, "Volunteers can post, require volunteer or admin approval"),
    (4, "Volunteers and admins can post without approval"),
)

# NOTE! The contents of these arrays must also be matched with the
# database table confreg_status_strings. This one is managed by
# manually creating a separate migration in case the contents change.
STATUS_CHOICES = (
    (0, "Submitted"),
    (1, "Approved"),
    (2, "Not Accepted"),
    (3, "Pending"),      # Approved, but not confirmed
    (4, "Reserve"),      # Reserve list
    (5, 'Pending reserve'),  # Reserve list, but not confirmed
    (6, 'Withdrawn'),    # Withdrawn by speaker
)
STATUS_CHOICES_LONG = (
    (0, "Submitted, not processed yet"),
    (1, "Approved and confirmed"),
    (2, "Not Accepted"),
    (3, "Pending speaker confirmation"),               # Approved, but not confirmed
    (4, "Reserve-listed in case of cancels/changes"),  # Reserve list
    (5, "Pending reserve-list confirmation"),          # Reserve list, but not confirmed
    (6, "Withdrawn by speaker"),
)
STATUS_CHOICES_SHORT = (
    (0, "submitted"),
    (1, "approved"),
    (2, "notaccepted"),
    (3, "pending"),               # Approved, but not confirmed
    (4, "reserve"),  # Reserve list
    (5, "pendreserve"),
    (6, "withdrawn"),
)


def get_status_string(val):
    return next((t for v, t in STATUS_CHOICES if v == val))


def get_status_string_long(val):
    return next((t for v, t in STATUS_CHOICES_LONG if v == val))


def get_status_string_short(val):
    return next((t for v, t in STATUS_CHOICES_SHORT if v == val))


valid_status_transitions = {
    0: {3: 'Talk approved', 2: 'Talk not accepted', 5: 'Talk added to reserve list'},
    1: {6: 'Talk withdrawn', },
    2: {0: 'Talk processing reset', },
    3: {0: 'Talk unapproved', 1: 'Speaker confirms', 6: 'Speaker declines'},
    4: {1: 'Last-minute reservelist', 3: 'Activated from reservelist', 6: 'Talk withdrawn'},
    5: {4: 'Talk confirmed to reservelist', 6: 'Speaker withdraws'},
    6: {0: 'Talk processing reset', },
}


def color_validator(value):
    if not value.startswith('#'):
        raise ValidationError('Color values must start with #')
    if len(value) != 7:
        raise ValidationError('Color values must be # + 7 characters')
    for n in range(0, 3):
        try:
            int(value[n * 2 + 1:n * 2 + 2 + 1], 16)
        except ValueError:
            raise ValidationError('Invalid value in color specification')


class ConferenceSeries(models.Model):
    name = models.CharField(max_length=64, blank=False, null=False)
    sortkey = models.IntegerField(null=False, default=100)
    intro = models.TextField(blank=True, null=False)
    visible = models.BooleanField(null=False, default=True)
    administrators = models.ManyToManyField(User, blank=True)

    _safe_attributes = ('name', 'intro', 'visible')

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('sortkey', 'name')
        verbose_name_plural = "Conference series"


class ConferenceSeriesOptOut(models.Model):
    # Users opting out of communications about a specific conference
    series = models.ForeignKey(ConferenceSeries, null=False, blank=False, on_delete=models.CASCADE)
    user = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE)

    class Meta:
        unique_together = (
            ('user', 'series'),
        )


class GlobalOptOut(models.Model):
    # Users who are opting out of *all* future communications
    user = models.OneToOneField(User, null=False, blank=False, primary_key=True, on_delete=models.CASCADE)


class Conference(models.Model):
    urlname = models.CharField(max_length=32, blank=False, null=False, unique=True, validators=[validate_lowercase, validate_urlname, ], verbose_name="URL name")
    conferencename = models.CharField(max_length=64, blank=False, null=False, verbose_name="Conference name")
    startdate = models.DateField(blank=False, null=False, verbose_name="Start date", db_index=True)
    enddate = models.DateField(blank=False, null=False, verbose_name="End date")
    location = models.CharField(max_length=128, blank=False, null=False)
    promoactive = models.BooleanField(default=False, verbose_name="Promotion active")
    promopicurl = models.URLField(blank=True, null=False, verbose_name="URL to promo picture", validators=[PictureUrlValidator(aspect=2.3)])
    promotext = models.TextField(null=False, blank=True, max_length=1000, verbose_name="Promotion text")
    tzname = models.CharField(max_length=100, blank=False, null=False, verbose_name="Time zone", default=settings.TIME_ZONE)
    contactaddr = LowercaseEmailField(blank=False, null=False, verbose_name="Contact address")
    sponsoraddr = LowercaseEmailField(blank=False, null=False, verbose_name="Sponsor address")
    notifyaddr = LowercaseEmailField(blank=False, null=False, verbose_name="Notification address")
    notifyregs = models.BooleanField(blank=False, null=False, default=False, verbose_name="Notify about registrations")
    notifysessionstatus = models.BooleanField(blank=False, null=False, default=False, verbose_name="Notify about session status changes by speakers")
    notifyvolunteerstatus = models.BooleanField(blank=False, null=False, default=False, verbose_name="Notify about volunteer schedule changes")
    active = models.BooleanField(blank=False, null=False, default=False, verbose_name="Registration open")
    callforpapersopen = models.BooleanField(blank=False, null=False, default=False, verbose_name="Call for papers open")
    callforsponsorsopen = models.BooleanField(blank=False, null=False, default=False, verbose_name="Call for sponsors open")
    feedbackopen = models.BooleanField(blank=False, null=False, default=False, verbose_name="Session feedback open")
    conferencefeedbackopen = models.BooleanField(blank=False, null=False, default=False, verbose_name="Conference feedback open")
    allowedit = models.BooleanField(blank=False, null=False, default=True, verbose_name="Allow editing registrations")
    scheduleactive = models.BooleanField(blank=False, null=False, default=False, verbose_name="Schedule publishing active")
    sessionsactive = models.BooleanField(blank=False, null=False, default=False, verbose_name="Session list publishing active")
    cardsactive = models.BooleanField(blank=False, null=False, default=False, verbose_name="Card publishing active", help_text='Publish "cards" for sessions and speakers')
    checkinactive = models.BooleanField(blank=False, null=False, default=False, verbose_name="Check-in active")
    schedulewidth = models.IntegerField(blank=False, default=600, null=False, verbose_name="Width of HTML schedule")
    pixelsperminute = models.FloatField(blank=False, default=1.5, null=False, verbose_name="Vertical pixels per minute")
    confurl = models.CharField(max_length=128, blank=False, null=False, validators=[validate_lowercase, ], verbose_name="Conference URL")
    twitter_timewindow_start = models.TimeField(null=False, blank=False, default='00:00', verbose_name="Don't post tweets before")
    twitter_timewindow_end = models.TimeField(null=False, blank=False, default='23:59:59', verbose_name="Don't post tweets after")
    twitter_postpolicy = models.IntegerField(null=False, blank=False, default=0, choices=TWITTER_POST_CHOICES,
                                             verbose_name="Posting policy")

    administrators = models.ManyToManyField(User, blank=True)
    testers = models.ManyToManyField(User, blank=True, related_name="testers_set", help_text="Users who can bypass the '<function> is open' check and access pages before they're open, in order to test")
    talkvoters = models.ManyToManyField(User, blank=True, related_name="talkvoters_set", help_text="Users who can view talks pre-approval, vote on the talks, and leave comments")
    staff = models.ManyToManyField(User, blank=True, related_name="staff_set", help_text="Users who can register as staff")
    volunteers = models.ManyToManyField('ConferenceRegistration', blank=True, related_name="volunteers_set", help_text="Users who volunteer")
    checkinprocessors = models.ManyToManyField('ConferenceRegistration', blank=True, related_name="checkinprocessors_set", verbose_name="Check-in processors", help_text="Users who process checkins")
    asktshirt = models.BooleanField(blank=False, null=False, default=True, verbose_name="Field: t-shirt", help_text="Include field for T-shirt size")
    askfood = models.BooleanField(blank=False, null=False, default=True, verbose_name="Field: dietary", help_text="Include field for dietary needs")
    asktwitter = models.BooleanField(null=False, blank=False, default=False, verbose_name="Field: twitter name", help_text="Include field for twitter name")
    asknick = models.BooleanField(null=False, blank=False, default=False, verbose_name="Field: nick", help_text="Include field for nick")
    askbadgescan = models.BooleanField(null=False, blank=False, default=False, verbose_name="Field: badge scanning", help_text="Include field for allowing sponsors to scan badge")
    askshareemail = models.BooleanField(null=False, blank=False, default=False, verbose_name="Field: share email", help_text="Include field for sharing email with sponsors")
    askphotoconsent = models.BooleanField(null=False, blank=False, default=True, verbose_name="Field: photo consent", help_text="Include field for getting photo consent")
    skill_levels = models.BooleanField(blank=False, null=False, default=True)
    additionalintro = models.TextField(blank=True, null=False, verbose_name="Additional options intro", help_text="Additional text shown just before the list of available additional options")
    jinjadir = models.CharField(max_length=200, blank=True, null=True, default=None, help_text="Full path to new style jinja repository root", verbose_name="Jinja directory")
    callforpapersintro = models.TextField(blank=True, null=False, verbose_name="Call for papers intro")
    callforpaperstags = models.BooleanField(blank=False, null=False, default=False, verbose_name='Use tags')

    sendwelcomemail = models.BooleanField(blank=False, null=False, default=False, verbose_name="Send welcome email", help_text="Send an email to attendees once their registration is completed.")
    welcomemail = models.TextField(blank=True, null=False, verbose_name="Welcome email contents")
    tickets = models.BooleanField(blank=False, null=False, default=False, verbose_name="Use tickets", help_text="Generate and send tickets to all attendees once their registration is completed.")
    queuepartitioning = models.IntegerField(blank=True, null=True, choices=((1, 'By last name'), (2, 'By first name'), ), verbose_name="Queue partitioning", help_text="If queue partitioning is used, partition by what?")

    lastmodified = models.DateTimeField(auto_now=True, null=False, blank=False)
    accounting_object = models.CharField(max_length=30, blank=True, null=True, verbose_name="Accounting object name")
    vat_registrations = models.ForeignKey(VatRate, null=True, blank=True, verbose_name='VAT rate for registrations', related_name='vat_registrations', on_delete=models.CASCADE)
    vat_sponsorship = models.ForeignKey(VatRate, null=True, blank=True, verbose_name='VAT rate for sponsorships', related_name='vat_sponsorship', on_delete=models.CASCADE)
    invoice_autocancel_hours = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1), ], verbose_name="Autocancel invoices", help_text="Automatically cancel invoices after this many hours")
    paymentmethods = models.ManyToManyField(InvoicePaymentMethod, blank=True, verbose_name='Invoice payment options')
    attendees_before_waitlist = models.IntegerField(blank=False, null=False, default=0, validators=[MinValueValidator(0), ], verbose_name="Attendees before waitlist", help_text="Maximum number of attendees before enabling waitlist management. 0 for no waitlist management")
    series = models.ForeignKey(ConferenceSeries, null=False, blank=False, on_delete=models.CASCADE)
    personal_data_purged = models.DateTimeField(null=True, blank=True, help_text="Personal data for registrations for this conference have been purged")
    initial_common_countries = models.ManyToManyField(Country, blank=True, help_text="Initial set of common countries")

    # Attributes that are safe to access in jinja templates
    _safe_attributes = ('active', 'askfood', 'askbadgescan', 'askshareemail', 'asktshirt', 'asktwitter', 'asknick',
                        'callforpapersintro', 'callforpapersopen', 'callforpaperstags', 'allowedit',
                        'conferencefeedbackopen', 'confurl', 'contactaddr', 'tickets',
                        'conferencedatestr', 'location', 'welcomemail',
                        'feedbackopen', 'skill_levels', 'urlname', 'conferencename',
                        'series',
    )

    def safe_export(self):
        d = dict((a, getattr(self, a) and str(getattr(self, a))) for a in self._safe_attributes)
        return d

    def __str__(self):
        return self.conferencename

    class Meta:
        ordering = ['-startdate', ]

    @cached_property
    def tzobj(self):
        return pytz.timezone(self.tzname)

    def localize_datetime(self, dt):
        return self.tzobj.localize(dt)

    @property
    def conferencedatestr(self):
        if self.enddate and not self.startdate == self.enddate:
            return "%s - %s" % (
                self.startdate.strftime("%Y-%m-%d"),
                self.enddate.strftime("%Y-%m-%d")
            )
        else:
            return self.startdate.strftime("%Y-%m-%d")

    @property
    def remove_fields(self):
        if not self.asktshirt:
            yield 'shirtsize'
        if not self.asknick:
            yield 'nick'
        if not self.asktwitter:
            yield 'twittername'
        if not self.askbadgescan:
            yield 'badgescan'
        if not self.askshareemail:
            yield 'shareemail'
        if not self.askphotoconsent:
            yield 'photoconsent'

    @property
    def pending_session_notifications(self):
        # How many speaker notifications are currently pending for this
        # conference. Note that this will always be zero if the conference
        # is in the past (so we don't end up with unnecessary db queries)
        if self.enddate:
            if self.enddate < today_conference():
                return 0
        else:
            if self.startdate < tday_conference():
                return 0
        return self.conferencesession_set.exclude(status=F('lastnotifiedstatus')).exclude(speaker__isnull=True).count()

    def waitlist_active(self):
        if self.attendees_before_waitlist == 0:
            # Never on waitlist if waitlisting is not turned on
            return False

        # Any registrations that are completed, has an invoice, or has a
        # bulk payment will count against the total.
        num = ConferenceRegistration.objects.filter(Q(conference=self) & (Q(payconfirmedat__isnull=False, canceledat__isnull=True) | Q(invoice__isnull=False) | Q(bulkpayment__isnull=False))).count()
        if num >= self.attendees_before_waitlist:
            return True

        return False

    @cached_property
    def has_social_broadcast(self):
        return self.conferencemessaging_set.filter(broadcast=True, provider__active=True).exists()

    @property
    def needs_data_purge(self):
        return self.enddate < today_conference() and not self.personal_data_purged

    def clean(self):
        cc = super(Conference, self).clean()
        if self.sendwelcomemail and not self.welcomemail:
            raise ValidationError("Must specify an actual welcome mail if it's enabled!")
        return cc


class RegistrationClass(models.Model):
    conference = models.ForeignKey(Conference, null=False, on_delete=models.CASCADE)
    regclass = models.CharField(max_length=64, null=False, blank=False, verbose_name="Registration class")
    badgecolor = models.CharField(max_length=20, null=False, blank=True, verbose_name="Badge color", help_text='Badge background color in hex format', validators=[color_validator, ])
    badgeforegroundcolor = models.CharField(max_length=20, null=False, blank=True, verbose_name="Badge foreground", help_text='Badge foreground color in hex format', validators=[color_validator, ])

    def __str__(self):
        return self.regclass

    def colortuple(self):
        return tuple([int(self.badgecolor[n * 2 + 1:n * 2 + 2 + 1], 16) for n in range(0, 3)])

    @property
    def bgcolortuplestr(self):
        if len(self.badgecolor):
            return ','.join(map(str, self.colortuple()))
        else:
            return None

    def foregroundcolortuple(self):
        if len(self.badgeforegroundcolor):
            return tuple([int(self.badgeforegroundcolor[n * 2 + 1:n * 2 + 2 + 1], 16) for n in range(0, 3)])
        else:
            return None

    @property
    def fgcolortuplestr(self):
        if self.badgeforegroundcolor:
            return ','.join(map(str, self.foregroundcolortuple()))
        else:
            return None

    class Meta:
        verbose_name_plural = 'Registration classes'

    def safe_export(self):
        attribs = ['regclass', 'badgecolor', 'badgeforegroundcolor', 'bgcolortuplestr', 'fgcolortuplestr']
        d = dict((a, getattr(self, a) and str(getattr(self, a))) for a in attribs)
        return d


class RegistrationDay(models.Model):
    conference = models.ForeignKey(Conference, null=False, on_delete=models.CASCADE)
    day = models.DateField(null=False, blank=False)

    class Meta:
        ordering = ('day', )
        unique_together = (
            ('conference', 'day'),
        )

    def __str__(self):
        return self.day.strftime('%a, %d %b')

    def shortday(self):
        df = DateFormat(self.day)
        return df.format('D jS')

    def isoday(self):
        df = DateFormat(self.day)
        return df.format('Y-m-d')


class RegistrationType(models.Model):
    conference = models.ForeignKey(Conference, null=False, on_delete=models.CASCADE)
    regtype = models.CharField(max_length=64, null=False, blank=False, verbose_name="Registration type")
    regclass = models.ForeignKey(RegistrationClass, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Registration class")
    cost = models.DecimalField(decimal_places=2, max_digits=10, null=False, default=0, help_text="Cost excluding VAT.")
    active = models.BooleanField(null=False, blank=False, default=True)
    activeuntil = models.DateField(null=True, blank=True, verbose_name="Active until", help_text="Registration available up to and including this date.")
    inlist = models.BooleanField(null=False, blank=False, default=True)
    sortkey = models.IntegerField(null=False, blank=False, default=10)
    specialtype = models.CharField(max_length=5, blank=True, null=True, choices=special_reg_types, verbose_name="Special type")
    require_phone = models.BooleanField(null=False, blank=False, default=False, help_text="Require phone number to be entered")
    days = models.ManyToManyField(RegistrationDay, blank=True)
    alertmessage = models.TextField(null=False, blank=True, verbose_name="Alert message", help_text="Message shown in popup to user when completing the registration")
    upsell_target = models.BooleanField(null=False, blank=False, default=False, help_text='Is target registration type for upselling in order to add additional options')
    invoice_autocancel_hours = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1), ], verbose_name="Autocancel invoices", help_text="Automatically cancel invoices after this many hours")
    requires_option = models.ManyToManyField('ConferenceAdditionalOption', blank=True, help_text='Requires at least one of the selected additional options to be picked')

    class Meta:
        ordering = ['conference', 'sortkey', ]

    def __str__(self):
        if self.cost == 0:
            return self.regtype
        else:
            return "%s (%s %s)" % (self.regtype,
                                   settings.CURRENCY_ABBREV,
                                   self.total_cost)

    @property
    def total_cost(self):
        if self.conference.vat_registrations:
            return "%.2f incl VAT" % (self.cost * (1 + self.conference.vat_registrations.vatpercent / Decimal(100.0)))
        else:
            return self.cost

    @property
    def available_days(self):
        dd = list(self.days.all())
        if len(dd) == 1:
            return dd[0].shortday()
        return ", ".join([x.shortday() for x in dd[:-1]]) + " and " + dd[-1].shortday()

    def safe_export(self):
        attribs = ['regtype', 'specialtype']
        d = dict((a, getattr(self, a) and str(getattr(self, a))) for a in attribs)
        d['regclass'] = self.regclass and self.regclass.safe_export()
        d['days'] = [dd.day.strftime('%Y-%m-%d') for dd in self.days.all()]
        return d

    def validate_object_delete(self):
        # Most deletions are blocked by foreign keys, but registration types are referenced
        # from inside JSON objects in the sponsor system. So build an ugly app-level
        # foreign key...

        # Can't import this model globally as it causes a circular dependency
        from postgresqleu.confsponsor.models import SponsorshipBenefit
        from postgresqleu.confsponsor.benefitclasses import get_benefit_id

        if SponsorshipBenefit.objects.filter(level__conference=self.conference,
                                             benefit_class=get_benefit_id('entryvouchers.EntryVouchers'),
                                             class_parameters__type=self.regtype).exists():
            raise ValidationError("A sponsorship benefit is using this registration type")


class ShirtSize(models.Model):
    shirtsize = models.CharField(max_length=32)
    sortkey = models.IntegerField(default=100, null=False, blank=False)

    def __str__(self):
        return self.shirtsize

    class Meta:
        ordering = ('sortkey', 'shirtsize',)


class ConferenceAdditionalOption(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    name = models.CharField(max_length=100, null=False, blank=False)
    cost = models.DecimalField(decimal_places=2, max_digits=10, null=False, default=0, help_text="Cost excluding VAT.")
    maxcount = models.IntegerField(null=False, verbose_name="Maximum number of uses")
    public = models.BooleanField(null=False, blank=False, default=True, help_text='Visible on public forms (opposite of admin only)')
    upsellable = models.BooleanField(null=False, blank=False, default=True, help_text='Can this option be purchased after the registration is completed')
    invoice_autocancel_hours = models.IntegerField(blank=True, null=True, validators=[MinValueValidator(1), ], verbose_name="Autocancel invoices", help_text="Automatically cancel invoices after this many hours")
    requires_regtype = models.ManyToManyField(RegistrationType, blank=True, verbose_name="Requires registration type", help_text='Can only be picked with selected registration types')
    mutually_exclusive = models.ManyToManyField('self', blank=True, help_text='Mutually exlusive with these additional options', symmetrical=True)
    additionaldays = models.ManyToManyField(RegistrationDay, blank=True, verbose_name="Adds access to days", help_text='Adds access to additional conference day(s), even if the registration type does not')

    class Meta:
        ordering = ['name', ]

    def __str__(self):
        # This is what renders in the multichoice checkboxes, so make
        # it nice for the end user.
        if self.cost > 0:
            if self.conference.vat_registrations:
                coststr = " (%s %.2f)" % (settings.CURRENCY_ABBREV, self.cost * (1 + self.conference.vat_registrations.vatpercent / Decimal(100.0)))
            else:
                coststr = " (%s %s)" % (settings.CURRENCY_ABBREV, self.cost)
        else:
            coststr = ""
        if self.maxcount == -1:
            return "%s%s (currently not available)" % (self.name, coststr)
        if self.maxcount > 0:
            usedcount = self.conferenceregistration_set.count() + self.pendingadditionalorder_set.filter(payconfirmedat__isnull=True).count()
            return "%s%s (%s of %s available)" % (self.name, coststr,
                                                  self.maxcount - usedcount,
                                                  self.maxcount)
        return "%s%s" % (self.name, coststr)


class BulkPayment(models.Model):
    # User that owns this bulk payment
    user = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE)

    # We attach it to a specific conference
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)

    # Invoice, once one has been created
    invoice = models.ForeignKey(Invoice, null=True, blank=True, on_delete=models.CASCADE)
    numregs = models.IntegerField(null=False, blank=False)

    createdat = models.DateTimeField(null=False, blank=False, auto_now_add=True)
    paidat = models.DateTimeField(null=True, blank=True)

    def ispaid(self):
        return self.paidat and True or False
    ispaid.boolean = True

    def adminstring(self):
        return "%s at %s" % (self.user, self.createdat)

    @property
    def payment_method_description(self):
        if not self.paidat:
            return "not paid."
        if self.invoice:
            if self.invoice.paidat:
                return "paid with invoice #{0}.\nInvoice {1}".format(self.invoice.id, self.invoice.payment_method_description)
            else:
                return "supposedly paid with invoice #{0}, which is not flagged as paid. SOMETHING IS WRONG!".format(self.invoice.id)
        else:
            return "no invoice assigned. SOMETHING IS WRONG!"

    def __str__(self):
        return "Bulk payment for %s created %s (%s registrations, %s%s): %s" % (
            self.conference,
            self.createdat,
            self.numregs,
            settings.CURRENCY_SYMBOL,
            self.invoice.total_amount,
            self.paidat and 'Paid' or 'Not paid yet')


class ConferenceRegistration(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    regtype = models.ForeignKey(RegistrationType, null=True, blank=True, verbose_name="Registration type", on_delete=models.CASCADE)
    attendee = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    registrator = models.ForeignKey(User, null=False, blank=False, related_name="registrator", on_delete=models.CASCADE)
    firstname = models.CharField(max_length=100, null=False, blank=False, verbose_name="First name")
    lastname = models.CharField(max_length=100, null=False, blank=False, verbose_name="Last name")
    email = LowercaseEmailField(null=False, blank=False, verbose_name="E-mail address")
    company = models.CharField(max_length=100, null=False, blank=True, verbose_name="Company")
    address = models.TextField(max_length=200, null=False, blank=True, verbose_name="Address")
    country = models.ForeignKey(Country, null=True, blank=True, verbose_name="Country", on_delete=models.CASCADE)
    phone = models.CharField(max_length=100, null=False, blank=True, verbose_name="Phone number")
    shirtsize = models.ForeignKey(ShirtSize, null=True, blank=True, verbose_name="Preferred T-shirt size", on_delete=models.CASCADE)
    dietary = models.CharField(max_length=100, null=False, blank=True, verbose_name="Special dietary needs")
    additionaloptions = models.ManyToManyField(ConferenceAdditionalOption, blank=True, verbose_name="Additional options")
    twittername = models.CharField(max_length=100, null=False, blank=True, verbose_name="Twitter account", validators=[TwitterValidator, ])
    nick = models.CharField(max_length=100, null=False, blank=True, verbose_name="Nickname")
    badgescan = models.BooleanField(null=False, blank=False, default=True, verbose_name="Allow sponsors get contact information by scanning badge")
    shareemail = models.BooleanField(null=False, blank=False, default=False, verbose_name="Share e-mail address with sponsors")
    photoconsent = models.NullBooleanField(null=True, blank=False, verbose_name="Consent to having your photo taken at the event by the organisers")

    # Admin fields!
    payconfirmedat = models.DateTimeField(null=True, blank=True, verbose_name="Payment confirmed at")
    payconfirmedby = models.CharField(max_length=16, null=True, blank=True, verbose_name="Payment confirmed by")
    created = models.DateTimeField(null=False, blank=False, verbose_name="Registration created")
    canceledat = models.DateTimeField(null=True, blank=True, verbose_name="Canceled at")
    lastmodified = models.DateTimeField(null=False, blank=False, auto_now=True)
    checkedinat = models.DateTimeField(null=True, blank=True, verbose_name="Checked in at")
    checkedinby = models.ForeignKey('ConferenceRegistration', null=True, blank=True, verbose_name="Checked by by", on_delete=models.CASCADE)

    # If an invoice is generated, link to it here so we can find our
    # way back easily.
    invoice = models.ForeignKey(Invoice, null=True, blank=True, on_delete=models.CASCADE)
    bulkpayment = models.ForeignKey(BulkPayment, null=True, blank=True, on_delete=models.CASCADE)

    # Any voucher codes. This is just used as temporary storage, and as
    # such we don't try to make it a foreign key. Must be re-validated
    # everytime it's used.
    # It's also used for discount codes - another reason to not use a
    # foreign key :)
    vouchercode = models.CharField(max_length=100, null=False, blank=True, verbose_name='Voucher or discount code')

    # Token to uniquely identify this registration in case we want to
    # access it without a login.
    regtoken = models.TextField(null=False, blank=False, unique=True)
    # Token to identify this user. Only exists for confirmed registrations and is
    # used for example to check in to the conference.
    idtoken = models.TextField(null=False, blank=False, unique=True)
    # Token used to identify this user publicly. This can for example be printed
    # as a QR code on a badge, for others to scan.
    publictoken = models.TextField(null=False, blank=False, unique=True)

    # Messaging configuration
    messaging = models.ForeignKey('ConferenceMessaging', null=True, blank=True, on_delete=models.SET_NULL)
    messaging_copiedfrom = models.ForeignKey(Conference, null=True, blank=True, on_delete=models.SET_NULL, related_name='reg_messaging_copiedfrom')
    messaging_config = JSONField(null=False, blank=False, default=dict)

    @property
    def fullname(self):
        return "%s %s" % (self.firstname, self.lastname)

    @property
    def countryname(self):
        if self.country:
            return self.country.name
        else:
            return ''

    def has_invoice(self):
        # Return if this registration has an invoice, whether through
        # a direct invoice or a bulk payment.
        if self.invoice is not None:
            return True
        if self.bulkpayment is not None:
            return True
        return False
    has_invoice.boolean = True

    @property
    def invoice_status(self):
        if self.canceledat:
            return "registration canceled"
        elif self.payconfirmedat:
            return "paid and confirmed"
        elif self.invoice:
            return "invoice generated, not paid"
        elif self.bulkpayment:
            return "bulk invoice generated, not paid"
        else:
            return "pending"

    @property
    def can_edit(self):
        # Can this registration be edited by the end user (which also implies
        # it can be deleted)
        return not (self.payconfirmedat or self.invoice or self.bulkpayment)

    def short_regtype(self):
        if self.regtype:
            return self.regtype.regtype[:30]
        return None
    short_regtype.short_description = 'Reg type'

    @property
    def additionaloptionlist(self):
        return ",\n".join([a.name for a in self.additionaloptions.all()])

    @property
    def ismultireg(self):
        return self.registrator_id != self.attendee_id

    @property
    def is_volunteer(self):
        return self.volunteers_set.exists()

    @property
    def is_checkinprocessor(self):
        return self.checkinprocessors_set.exists()

    @cached_property
    def sponsorscanner_token(self):
        qq = self.sponsorscanner_set.all()[:1]
        if qq:
            return qq[0].token
        return None

    @property
    def is_badgescanner(self):
        return self.sponsorscanner_token is not None

    @cached_property
    def is_tweeter(self):
        if self.conference.has_social_broadcast:
            if self.conference.twitter_postpolicy != 0:
                if self.conference.administrators.filter(pk=self.attendee_id).exists():
                    return True
            if self.conference.twitter_postpolicy in (2, 3, 4) and self.is_volunteer:
                return True
        return False

    @property
    def queuepartition(self):
        if self.conference.queuepartitioning == 1:
            k = self.lastname[0].upper()
        elif self.conference.queuepartitioning == 2:
            k = self.firstname[0].upper()
        else:
            return None

        if k >= 'A' and k <= 'Z':
            return k
        return "Other"

    @property
    def payment_method_description(self):
        if not self.payconfirmedat:
            return "Not paid."
        if self.payconfirmedby == "no payment reqd":
            return "Registration does not require payment."
        if self.payconfirmedby == "Multireg/nopay":
            return "Registration is part of multi payment batch that does not require payment."
        if self.payconfirmedby == "Invoice paid":
            if self.invoice:
                return "Paid by individual invoice #{0}.\n Invoice {1}".format(self.invoice.id, self.invoice.payment_method_description)
            else:
                return "Paid by individual invoice, since canceled without refund"
        if self.payconfirmedby == "Bulk paid":
            if self.bulkpayment:
                return "Paid by bulk payment #{0} ({1} total registrations).\n Bulk {2}".format(self.bulkpayment.id, self.bulkpayment.numregs, self.bulkpayment.payment_method_description)
            else:
                return "Paid by bulk payment, which has since been canceled"
        if self.payconfirmedby.startswith("Manual/"):
            return "Manually confirmed"

        return "Payment details not available"

    @property
    def paymenticon(self):
        if self.invoice:
            return 'euro'
        if self.bulkpayment:
            return 'list-alt'
        return 'ban-circle'

    @property
    def alldays(self):
        if self.regtype:
            days = set(self.regtype.days.all())
        else:
            days = set()
        for ao in self.additionaloptions.all():
            days.update(ao.additionaldays.all())
        return sorted(days, key=lambda x: x.day)

    @cached_property
    def access_days(self):
        days = self.alldays

        if not days:
            # Registration days not in use
            return None

        if len(days) == 1:
            return days[0].shortday()

        return ", ".join([x.shortday() for x in days[:-1]]) + " and " + days[-1].shortday()

    @property
    def regdatestr(self):
        days = self.alldays

        if not days:
            return None

        if len(days) == 1:
            return days[0].isoday()

        # If the days are continous, then we list the first and last day
        if all((days[i + 1].day - days[i].day).days == 1 for i in range(len(days) - 1)):
            # Continous range
            return "{} - {}".format(days[0].isoday(), days[-1].isoday())

        return ", ".join([d.isoday() for d in days])

    def get_field_string(self, field):
        r = getattr(self, field)
        if isinstance(r, bool):
            return r and 'Yes' or 'No'
        return getattr(self, field)

    # ID token inluding the identifier
    @property
    def fullidtoken(self):
        if self.idtoken:
            return 'ID${0}$ID'.format(self.idtoken)
        return ''

    # Public token including the identifier
    @property
    def fullpublictoken(self):
        if self.publictoken:
            return 'AT${0}$AT'.format(self.publictoken)
        return ''

    # For the admin interface (mainly)
    def __str__(self):
        return "%s: %s %s <%s>" % (self.conference, self.firstname, self.lastname, self.email)

    # For exporting "safe attributes" to external systems
    def safe_export(self):
        attribs = ['firstname', 'lastname', 'email', 'company', 'address', 'country', 'countryname', 'phone', 'shirtsize', 'dietary', 'twittername', 'nick', 'badgescan', 'shareemail', 'fullidtoken', 'fullpublictoken', 'queuepartition', 'alldays', 'regdatestr', ]
        d = dict((a, getattr(self, a) and str(getattr(self, a))) for a in attribs)
        if self.regtype:
            d['regtype'] = self.regtype.safe_export()
        else:
            d['regtype'] = None
        d['additionaloptions'] = [{'id': ao.id, 'name': ao.name} for ao in self.additionaloptions.all()]
        return d


class ConferenceRegistrationLog(models.Model):
    reg = models.ForeignKey(ConferenceRegistration, null=False, blank=False, on_delete=models.CASCADE)
    user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    ts = models.DateTimeField(null=False, blank=False, auto_now_add=True)
    txt = models.CharField(max_length=8000, null=False, blank=False)

    class Meta:
        indexes = [
            models.Index(fields=['reg', '-ts']),
        ]


class RegistrationWaitlistEntry(models.Model):
    registration = models.OneToOneField(ConferenceRegistration, primary_key=True, on_delete=models.CASCADE)
    enteredon = models.DateTimeField(null=False, blank=False, auto_now_add=True)
    offeredon = models.DateTimeField(null=True, blank=True)
    offerexpires = models.DateTimeField(null=True, blank=True)

    _safe_attributes = ('enteredon', 'offeredon', 'offerexpires')

    @property
    def offers_made(self):
        return self.registrationwaitlisthistory_set.filter(text__startswith='Made offer').count()


class RegistrationWaitlistHistory(models.Model):
    waitlist = models.ForeignKey(RegistrationWaitlistEntry, null=False, blank=False, on_delete=models.CASCADE)
    time = models.DateTimeField(null=False, blank=False, auto_now_add=True)
    text = models.CharField(max_length=200, null=False, blank=False)

    class Meta:
        ordering = ('-time',)


class Track(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    trackname = models.CharField(max_length=100, null=False, blank=False, verbose_name="Track name")
    color = models.CharField(max_length=20, null=False, blank=True, validators=[color_validator, ], verbose_name="Background color")
    fgcolor = models.CharField(max_length=20, null=False, blank=False, validators=[color_validator, ], verbose_name="Foreground color", default='#000000')
    sortkey = models.IntegerField(null=False, default=100, blank=False)
    incfp = models.BooleanField(null=False, default=False, blank=False, verbose_name="In call for papers")
    showcompany = models.BooleanField(null=False, default=False, blank=False, verbose_name="Show company name",
                                      help_text="Show the company name on the schedule")
    speakerreg = models.BooleanField(null=False, blank=False, default=True, verbose_name="Allow speaker reg",
                                     help_text="Confirmed speakers on this track are allowed to register as speakers, if enabled")

    json_included_attributes = ['trackname', 'color', 'fgcolor', 'sortkey', 'incfp', 'showcompany']

    def __str__(self):
        return self.trackname


class Room(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    roomname = models.CharField(max_length=20, null=False, blank=False, verbose_name="Room name")
    sortkey = models.IntegerField(null=False, blank=False, default=100)
    url = models.URLField(max_length=200, null=False, blank=True, verbose_name='URL',
                          help_text="Link to information about the room")
    comment = models.CharField(max_length=200, null=False, blank=True,
                               help_text='Internal comment for planning')
    availabledays = models.ManyToManyField(RegistrationDay, blank=True, verbose_name='Available days',
                                           help_text='Only used for schedule creation, not actual viewing!')

    json_included_attributes = ['roomname', 'sortkey']

    def __str__(self):
        return self.roomname

    class Meta:
        ordering = ['sortkey', 'roomname', ]


def _get_upload_path(instance, filename):
    return "%s" % instance.id


class Speaker(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, unique=True, on_delete=models.CASCADE)
    fullname = models.CharField(max_length=100, null=False, blank=False, verbose_name="Full name")
    twittername = models.CharField(max_length=32, null=False, blank=True, validators=[TwitterValidator, ],
                                   verbose_name='Twitter name')
    company = models.CharField(max_length=100, null=False, blank=True)
    abstract = models.TextField(null=False, blank=True, verbose_name="Bio")
    photo = ImageBinaryField(blank=True, null=True, verbose_name="Photo", max_length=1000000, max_resolution=(128, 128))
    lastmodified = models.DateTimeField(auto_now=True, null=False, blank=False)
    speakertoken = models.TextField(null=False, blank=False, unique=True)

    _safe_attributes = ('id', 'name', 'fullname', 'twittername', 'company', 'abstract', 'photo', 'has_photo', 'photo_data', 'lastmodified', )
    json_included_attributes = ['fullname', 'twittername', 'company', 'abstract', 'lastmodified']

    @property
    def name(self):
        return self.fullname

    @property
    def email(self):
        if self.user:
            return self.user.email
        else:
            return None

    def _display_user(self):
        if self.user:
            if self.user.email:
                return "{0} <{1}>".format(self.user.username, self.user.email)
            else:
                return self.user.username

    def has_abstract(self):
        return len(self.abstract) > 0
    has_abstract.boolean = True

    def has_photo(self):
        return (self.photo is not None and self.photo != "")
    has_photo.boolean = True

    @cached_property
    def photo_data(self):
        return base64.b64encode(self.photo).decode('ascii')

    @property
    def photofile(self):
        return self.photo

    def __str__(self):
        return self.name

    def __reduce_ex__(self, protocol):
        r = super(Speaker, self).__reduce_ex__(protocol)
        # Ooh, this is ugly. But this is to ensure that the 'photo' part of the
        # pickled value works (because memoryviews can't be pickled)
        if isinstance(r[2]['photo'], memoryview):
            r[2]['photo'] = bytes(r[2]['photo'])
        return r

    class Meta:
        ordering = ['fullname', ]


class DeletedItems(models.Model):
    itemid = models.IntegerField(null=False, blank=False)
    type = models.CharField(max_length=16, blank=False, null=False)
    deltime = models.DateTimeField(blank=False, null=False)


class ConferenceSessionScheduleSlot(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    starttime = models.DateTimeField(null=False, blank=False, verbose_name="Start time")
    endtime = models.DateTimeField(null=False, blank=False, verbose_name="End time")

    def __str__(self):
        return "%s - %s" % (self.starttime, self.endtime)


class ConferenceSessionTag(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    tag = models.CharField(max_length=32, null=False, blank=False)
    slug = models.CharField(max_length=32, null=False, blank=False)

    def __str__(self):
        return self.tag

    def save(self, *args, **kwargs):
        self.slug = slugify(self.tag)
        super(ConferenceSessionTag, self).save(*args, **kwargs)

    class Meta:
        unique_together = (
            ('conference', 'tag'),
            ('conference', 'slug'),
        )


class ConferenceSession(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    speaker = models.ManyToManyField(Speaker, blank=True, verbose_name="Speakers")
    title = models.CharField(max_length=200, null=False, blank=False)
    starttime = models.DateTimeField(null=True, blank=True)
    endtime = models.DateTimeField(null=True, blank=True)
    track = models.ForeignKey(Track, null=True, blank=True, on_delete=models.CASCADE)
    room = models.ForeignKey(Room, null=True, blank=True, on_delete=models.CASCADE)
    cross_schedule = models.BooleanField(null=False, default=False)
    can_feedback = models.BooleanField(null=False, default=True)
    abstract = models.TextField(null=False, blank=True)
    skill_level = models.IntegerField(null=False, default=1, choices=SKILL_CHOICES)
    htmlicon = models.CharField(max_length=100, null=False, blank=True, verbose_name="HTML Icon", help_text="HTML representing an icon used for this session on the schedule (and optionally elsewhere)")
    status = models.IntegerField(null=False, default=0, choices=STATUS_CHOICES)
    lastnotifiedstatus = models.IntegerField(null=False, default=0, choices=STATUS_CHOICES)
    lastnotifiedtime = models.DateTimeField(null=True, blank=True, verbose_name="Notification last sent")
    submissionnote = models.TextField(null=False, blank=True, verbose_name="Submission notes")
    initialsubmit = models.DateTimeField(null=True, blank=True, verbose_name="Submitted")
    tentativescheduleslot = models.ForeignKey(ConferenceSessionScheduleSlot, null=True, blank=True, on_delete=models.CASCADE)
    tentativeroom = models.ForeignKey(Room, null=True, blank=True, related_name='tentativeroom', on_delete=models.CASCADE)
    lastmodified = models.DateTimeField(auto_now=True, null=False, blank=False)
    reminder_sent = models.BooleanField(null=False, default=False, verbose_name='Speaker reminder(s) sent')
    tags = models.ManyToManyField(ConferenceSessionTag, blank=True)

    # NOTE! Any added fields need to be considered for inclusion in
    # forms.CallForPapersForm and in views.callforpapers_copy()!

    # Not a db field, but set from the view to track if the current user
    # has given any feedback on this session.
    has_given_feedback = False

    @property
    def speaker_list(self):
        if self.id:
            return ", ".join([s.name for s in self.speaker.all()])
        else:
            return "<none>"

    @property
    def skill_level_string(self):
        return next((t for v, t in SKILL_CHOICES if v == self.skill_level))

    @property
    def status_string(self):
        return get_status_string(self.status)

    @property
    def status_string_long(self):
        return get_status_string_long(self.status)

    @property
    def status_string_short(self):
        return get_status_string_short(self.status)

    @property
    def lastnotified_status_string(self):
        return get_status_string(self.lastnotifiedstatus)

    @property
    def lastnotified_status_string_long(self):
        return get_status_string_long(self.lastnotifiedstatus)

    @property
    def has_feedback(self):
        return self.conferencesessionfeedback_set.exists()

    def __str__(self):
        return "%s: %s (%s)" % (
            self.speaker_list,
            self.title,
            self.starttime,
        )

    @property
    def shorttitle(self):
        return "%s (%s)" % (
            self.title,
            self.starttime,
        )

    class Meta:
        ordering = ['starttime', ]


class ConferenceSessionSlides(models.Model):
    session = models.ForeignKey(ConferenceSession, null=False, blank=False, on_delete=models.CASCADE)
    name = models.CharField(max_length=100, null=False, blank=False)
    url = models.URLField(max_length=1000, null=False, blank=True, verbose_name='URL')
    content = PdfBinaryField(null=True, blank=True, max_length=20000000000, verbose_name='Upload PDF')

    _safe_attributes = ('id', 'name', 'url', 'content')

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('session', 'name', )


class ConferenceSessionVote(models.Model):
    session = models.ForeignKey(ConferenceSession, null=False, blank=False, on_delete=models.CASCADE)
    voter = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE)
    vote = models.IntegerField(null=True, blank=False)
    comment = models.TextField(null=True, blank=True)

    class Meta:
        unique_together = (('session', 'voter',), )


class ConferenceSessionFeedback(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    session = models.ForeignKey(ConferenceSession, null=False, blank=False, on_delete=models.CASCADE)
    attendee = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE)
    topic_importance = models.IntegerField(null=False, blank=False)
    content_quality = models.IntegerField(null=False, blank=False)
    speaker_knowledge = models.IntegerField(null=False, blank=False)
    speaker_quality = models.IntegerField(null=False, blank=False)
    speaker_feedback = models.TextField(null=False, blank=True, verbose_name='Comments to the speaker')
    conference_feedback = models.TextField(null=False, blank=True, verbose_name='Comments to the conference organizers')

    def __str__(self):
        return str("%s - %s (%s)") % (self.conference, self.session, self.attendee)


class ConferenceFeedbackQuestion(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    question = models.CharField(max_length=100, null=False, blank=False)
    isfreetext = models.BooleanField(blank=False, null=False, default=False)
    textchoices = models.CharField(max_length=500, null=False, blank=True)
    sortkey = models.IntegerField(null=False, default=100)
    newfieldset = models.CharField(max_length=100, null=False, blank=True)

    def __str__(self):
        return "%s: %s" % (self.conference, self.question)

    class Meta:
        ordering = ['conference', 'sortkey', ]


class ConferenceFeedbackAnswer(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    question = models.ForeignKey(ConferenceFeedbackQuestion, null=False, blank=False, on_delete=models.CASCADE)
    attendee = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE)
    rateanswer = models.IntegerField(null=True)
    textanswer = models.TextField(null=False, blank=True)

    def __str__(self):
        return "%s - %s: %s" % (self.conference, self.attendee, self.question.question)

    class Meta:
        ordering = ['conference', 'attendee', 'question', ]


class VolunteerSlot(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    timerange = DateTimeRangeField(null=False, blank=False)
    title = models.CharField(max_length=50, null=False, blank=False)
    min_staff = models.IntegerField(null=False, blank=False, default=1, validators=[MinValueValidator(1)])
    max_staff = models.IntegerField(null=False, blank=False, default=1, validators=[MinValueValidator(1)])

    class Meta:
        ordering = ['timerange', ]

    def __str__(self):
        return self._display_timerange()

    def _display_timerange(self):
        return "{0} - {1}".format(timezone.localtime(self.timerange.lower), timezone.localtime(self.timerange.upper))

    @property
    def countvols(self):
        return self.volunteerassignment_set.all().count()

    @property
    def weekday(self):
        return timezone.localtime(self.timerange.lower).strftime('%Y-%m-%d (%A)')


class VolunteerAssignment(models.Model):
    slot = models.ForeignKey(VolunteerSlot, null=False, blank=False, on_delete=models.CASCADE)
    reg = models.ForeignKey(ConferenceRegistration, null=False, blank=False, on_delete=models.CASCADE)
    vol_confirmed = models.BooleanField(null=False, blank=False, default=False, verbose_name="Confirmed by volunteer")
    org_confirmed = models.BooleanField(null=False, blank=False, default=False, verbose_name="Confirmed by organizers")

    _safe_attributes = ('id', 'slot', 'reg', 'vol_confirmed', 'org_confirmed')


class PrepaidBatch(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    regtype = models.ForeignKey(RegistrationType, null=False, blank=False, on_delete=models.CASCADE)
    buyer = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE)
    buyername = models.CharField(max_length=100, null=True, blank=True)
    sponsor = models.ForeignKey('confsponsor.Sponsor', null=True, blank=True, verbose_name="Optional sponsor", on_delete=models.CASCADE)

    def __str__(self):
        return "%s: %s for %s" % (self.conference, self.regtype, self.buyer)

    class Meta:
        verbose_name_plural = "Prepaid batches"
        ordering = ['conference', 'id', ]


class PrepaidVoucher(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    vouchervalue = models.CharField(max_length=100, null=False, blank=False, unique=True)
    batch = models.ForeignKey(PrepaidBatch, null=False, blank=False, on_delete=models.CASCADE)
    user = models.ForeignKey(ConferenceRegistration, null=True, blank=True, on_delete=models.CASCADE)
    usedate = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return self.vouchervalue

    class Meta:
        ordering = ['batch', 'vouchervalue', ]


class DiscountCode(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    code = models.CharField(max_length=100, null=False, blank=False)
    discountamount = models.DecimalField(decimal_places=2, max_digits=10, null=False, default=0, verbose_name="Discount amount")
    discountpercentage = models.IntegerField(null=False, blank=False, default=0, verbose_name="Discount percentage")
    regonly = models.BooleanField(null=False, blank=False, default=False, verbose_name="Registration only", help_text="Apply percentage discount only to the registration cost, not additional options. By default, it's applied to both.")
    validuntil = models.DateField(blank=True, null=True, verbose_name="Valid until", help_text="Valid up to and including this date.")
    maxuses = models.IntegerField(null=False, blank=False, default=0, verbose_name="Max uses")
    requiresoption = models.ManyToManyField(ConferenceAdditionalOption, blank=True, verbose_name="Requires option", help_text='Requires this option to be set in order to be valid')
    requiresregtype = models.ManyToManyField(RegistrationType, blank=True, verbose_name="Requires registration type", help_text='Require a specific registration type to be valid')
    public = models.BooleanField(null=False, blank=False, default=False, help_text="Is the existance of this discount code public")

    registrations = models.ManyToManyField(ConferenceRegistration, blank=True)

    # If this discount code is purchased by a sponsor, track it here.
    sponsor = models.ForeignKey('confsponsor.Sponsor', null=True, blank=True, verbose_name="Optional sponsor.", help_text="Note that if a sponsor is picked, an invoice will be generated once the discount code closes!!!", on_delete=models.CASCADE)
    sponsor_rep = models.ForeignKey(User, null=True, blank=True, verbose_name="Optional sponsor representative.", help_text="Must be set if the sponsor field is set!", on_delete=models.CASCADE)
    is_invoiced = models.BooleanField(null=False, blank=False, default=False, verbose_name="Has an invoice been sent for this discount code.")

    def __str__(self):
        return self.code

    class Meta:
        unique_together = (('conference', 'code',), )
        ordering = ('conference', 'code',)

    @property
    def count(self):
        return self.registrations.count()


class SavedReportDefinition(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, null=False, blank=False)
    definition = JSONField(blank=False, null=False, encoder=DjangoJSONEncoder)

    class Meta:
        ordering = ('title', )
        unique_together = (
            ('conference', 'title'),
        )


class AttendeeMail(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    regclasses = models.ManyToManyField(RegistrationClass, blank=True, verbose_name="Registration classes")
    registrations = models.ManyToManyField(ConferenceRegistration, blank=True, verbose_name="Registrations")
    pending_regs = models.ManyToManyField(User, blank=True, verbose_name="Pending registrations")
    tovolunteers = models.BooleanField(null=False, blank=False, default=False, verbose_name="To volunteers")
    tocheckin = models.BooleanField(null=False, blank=False, default=False, verbose_name="To check-in processors")
    addopts = models.ManyToManyField(ConferenceAdditionalOption, blank=True, verbose_name="Attendees with options")
    sentat = models.DateTimeField(null=False, blank=False, auto_now_add=True)
    subject = models.CharField(max_length=100, null=False, blank=False)
    message = models.TextField(max_length=8000, null=False, blank=False)

    def __str__(self):
        return "%s: %s" % (timezone.localtime(self.sentat).strftime("%Y-%m-%d %H:%M"), self.subject)

    class Meta:
        ordering = ('-sentat', )


class PendingAdditionalOrder(models.Model):
    reg = models.ForeignKey(ConferenceRegistration, null=False, blank=False, on_delete=models.CASCADE)
    options = models.ManyToManyField(ConferenceAdditionalOption, blank=False)
    newregtype = models.ForeignKey(RegistrationType, null=True, blank=True, on_delete=models.CASCADE)
    createtime = models.DateTimeField(null=False, blank=False)
    invoice = models.ForeignKey(Invoice, null=True, blank=True, on_delete=models.CASCADE)
    payconfirmedat = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return "%s" % (self.reg, )

    @property
    def invoice_status(self):
        if self.payconfirmedat:
            return "paid and confirmed"
        elif self.invoice:
            return "invoice generated, not paid"
        else:
            return "pending"


class RefundPattern(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    percent = models.IntegerField(null=False, verbose_name="Percent to refund", validators=[MinValueValidator(1), MaxValueValidator(100)])
    fees = models.IntegerField(null=False, verbose_name="Fees not to refund", help_text="This amount will be deducted from the calculated refund amount")
    fromdate = models.DateField(null=True, blank=True, verbose_name="From date", help_text="Suggest for refunds starting from this date")
    todate = models.DateField(null=True, blank=True, verbose_name="To date", help_text="Suggest for refunds until this date")


class AggregatedTshirtSizes(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    size = models.ForeignKey(ShirtSize, null=False, blank=False, on_delete=models.CASCADE)
    num = models.IntegerField(null=False, blank=False)

    class Meta:
        unique_together = (('conference', 'size'), )


class AggregatedDietary(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    dietary = models.CharField(max_length=100, null=False, blank=False)
    num = models.IntegerField(null=False, blank=False)

    class Meta:
        unique_together = (('conference', 'dietary'), )


AccessTokenPermissions = (
    ('regtypes', 'Registration types and counters'),
    ('discounts', 'Discount codes'),
    ('discountspublic', 'Public discount codes'),
    ('vouchers', 'Voucher codes'),
    ('sponsors', 'Sponsors and counts'),
    ('addopts', 'Additional options and counts'),
)


class AccessToken(models.Model):
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    token = models.CharField(max_length=200, null=False, blank=False)
    description = models.TextField(null=False, blank=False)
    permissions = ChoiceArrayField(
        models.CharField(max_length=32, blank=False, null=False, choices=AccessTokenPermissions)
    )

    class Meta:
        unique_together = (('conference', 'token'), )

    def __str__(self):
        return self.token

    def _display_permissions(self):
        return ", ".join(self.permissions)


class ConferenceNews(models.Model):
    conference = models.ForeignKey(Conference, null=False, on_delete=models.CASCADE)
    datetime = models.DateTimeField(blank=False, default=timezone.now)
    title = models.CharField(max_length=128, blank=False)
    summary = models.TextField(blank=False)
    author = models.ForeignKey(NewsPosterProfile, on_delete=models.CASCADE)
    inrss = models.BooleanField(null=False, default=True, verbose_name="Include in RSS feed")
    tweeted = models.BooleanField(null=False, blank=False, default=False)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-datetime', ]
        verbose_name_plural = 'Conference News'

    _safe_attributes = ('id', 'datetime', 'title', 'summary', 'author', 'inrss')


class ConferenceHashtag(models.Model):
    conference = models.ForeignKey(Conference, null=False, on_delete=models.CASCADE)
    hashtag = models.CharField(max_length=32, null=False, blank=False,
                               validators=[RegexValidator('^[#@]', 'Enter a hashtag (starting with #) or username (starting with @)'), ])

    def __str__(self):
        return self.hashtag

    class Meta:
        unique_together = (
            ('conference', 'hashtag', )
        )
        ordering = ['hashtag', ]


class MessagingProvider(models.Model):
    series = models.ForeignKey(ConferenceSeries, null=True, blank=True, on_delete=models.CASCADE)
    internalname = models.CharField(max_length=100, null=False, blank=False, verbose_name='Internal name')
    publicname = models.CharField(max_length=100, null=False, blank=False, verbose_name='Public name')
    classname = models.CharField(max_length=200, null=False, blank=False, verbose_name="Implementation class")
    active = models.BooleanField(null=False, blank=False, default=False)
    config = JSONField(blank=False, null=False, default=dict, encoder=DjangoJSONEncoder)
    route_incoming = models.ForeignKey(Conference, null=True, blank=True, verbose_name="Route incoming messages to", on_delete=models.SET_NULL, related_name='incoming_messaging_route_for')
    private_checkpoint = models.BigIntegerField(null=False, blank=False, default=0)
    private_lastpoll = models.DateTimeField(null=False, blank=False, auto_now_add=True)
    public_checkpoint = models.BigIntegerField(null=False, blank=False, default=0)
    public_lastpoll = models.DateTimeField(null=False, blank=False, auto_now_add=True)

    def __str__(self):
        return self.internalname

    class Meta:
        ordering = ('internalname', )


class ConferenceMessaging(models.Model):
    conference = models.ForeignKey(Conference, null=False, on_delete=models.CASCADE)
    provider = models.ForeignKey(MessagingProvider, null=False, blank=False, on_delete=models.CASCADE)

    broadcast = models.BooleanField(null=False, blank=False, default=False, verbose_name='Broadcasts')
    privatebcast = models.BooleanField(null=False, blank=False, default=False, verbose_name='Attendee only broadcasts')
    notification = models.BooleanField(null=False, blank=False, default=False, verbose_name='Private notifications')
    orgnotification = models.BooleanField(null=False, blank=False, default=False, verbose_name='Organizer notifications')
    config = JSONField(blank=False, null=False, default=dict)

    class Meta:
        verbose_name = 'messaging configuration'
        ordering = ('provider__name', )
        unique_together = (
            ('conference', 'provider'),
        )

    def __str__(self):
        return self.provider.publicname

    @property
    def full_info(self):
        if self.notification and self.privatebcast:
            return "{} - personal notifications and announcements".format(self)
        elif self.notification:
            return "{} - personal notifications only".format(self)
        elif self.privatebcast:
            return "{} - announcements only".format(self)
        else:
            return str(self)


class ConferenceTweetQueue(models.Model):
    conference = models.ForeignKey(Conference, null=True, on_delete=models.CASCADE)
    datetime = models.DateTimeField(blank=False, default=timezone.now, verbose_name="Date and time",
                                    help_text="Date and time to send tweet")
    contents = models.CharField(max_length=1000, null=False, blank=False)
    image = ImageBinaryField(null=True, blank=True, max_length=1000000)
    imagethumb = ImageBinaryField(null=True, blank=True, max_length=100000)
    approved = models.BooleanField(null=False, default=False, blank=False)
    author = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    approvedby = models.ForeignKey(User, null=True, blank=True, related_name="tweetapprovals", on_delete=models.CASCADE)
    sent = models.BooleanField(null=False, default=False, blank=False)
    postids = JSONField(null=False, blank=False, default=dict)
    replytotweetid = models.BigIntegerField(null=True, blank=True, verbose_name="Reply to tweet")
    remainingtosend = models.ManyToManyField(MessagingProvider, blank=True)

    class Meta:
        ordering = ['sent', 'datetime', ]
        verbose_name_plural = 'Conference Tweets'
        verbose_name = 'Conference Tweet'
        indexes = [
            GinIndex(name='tweetqueue_postids_idx', fields=['postids'], opclasses=['jsonb_path_ops']),
        ]

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        # When we are saving, *if* we have not yet been sent, materialize a list of
        # which providers to send to.
        if self.approved and not self.sent:
            if self.conference:
                self.remainingtosend.set(MessagingProvider.objects.filter(active=True, conferencemessaging__conference=self.conference, conferencemessaging__broadcast=True))
            else:
                self.remainingtosend.set(MessagingProvider.objects.filter(active=True, series__isnull=True))
            exec_no_result("NOTIFY pgeu_broadcast")


class ConferenceIncomingTweet(models.Model):
    conference = models.ForeignKey(Conference, null=False, on_delete=models.CASCADE)
    provider = models.ForeignKey(MessagingProvider, null=True, on_delete=models.SET_NULL)
    statusid = models.BigIntegerField(null=False, blank=False)
    created = models.DateTimeField(null=False, blank=False)
    processedat = models.DateTimeField(null=True, blank=True)
    processedby = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    text = models.CharField(max_length=512, null=False, blank=False)
    replyto_statusid = models.BigIntegerField(null=True, blank=True, db_index=True)
    author_id = models.BigIntegerField(null=False, blank=False)
    author_screenname = models.CharField(max_length=50, null=False, blank=False)
    author_name = models.CharField(max_length=100, null=False, blank=False)
    author_image_url = models.URLField(max_length=1024, null=False, blank=False)
    quoted_statusid = models.BigIntegerField(null=True, blank=True)
    quoted_text = models.CharField(max_length=512, null=True, blank=True)
    quoted_permalink = models.URLField(max_length=1024, null=True, blank=True)
    retweetstate = models.IntegerField(null=False, blank=False, default=0, choices=((0, 'No retweet'), (1, 'Scheduled'), (2, 'Retweeted')))

    class Meta:
        unique_together = (
            ('statusid', 'provider'),
        )


class ConferenceIncomingTweetMedia(models.Model):
    incomingtweet = models.ForeignKey(ConferenceIncomingTweet, null=False, blank=False, on_delete=models.CASCADE)
    sequence = models.IntegerField(null=False, blank=False)
    mediaurl = models.URLField(max_length=1024, null=False, blank=False)

    class Meta:
        unique_together = (
            ('incomingtweet', 'sequence'),
        )


# Either reg *or* channel is set!
class NotificationQueue(models.Model):
    time = models.DateTimeField(null=False, blank=False)
    expires = models.DateTimeField(null=False, blank=False)
    messaging = models.ForeignKey(ConferenceMessaging, null=False, blank=False, on_delete=models.CASCADE)
    reg = models.ForeignKey(ConferenceRegistration, null=True, blank=True, on_delete=models.CASCADE)
    channel = models.CharField(max_length=50, null=True, blank=True)
    msg = models.TextField(null=False, blank=False)


class IncomingDirectMessage(models.Model):
    provider = models.ForeignKey(MessagingProvider, null=False, blank=False, on_delete=models.CASCADE)
    time = models.DateTimeField(null=False, blank=False)
    postid = models.BigIntegerField(null=False, blank=False)
    internallyprocessed = models.BooleanField(null=False, blank=False, default=False)
    sender = JSONField(null=False, blank=False, default=dict)
    txt = models.TextField(null=False, blank=True)

    class Meta:
        unique_together = (
            ('postid', 'provider', ),
        )


class CrossConferenceEmail(models.Model):
    sentat = models.DateTimeField(null=False, blank=False, auto_now_add=True)
    sentby = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE)
    senderaddr = LowercaseEmailField(null=False, blank=False, verbose_name='Sender address')
    sendername = models.CharField(max_length=100, null=False, blank=False, verbose_name='Sender name')
    subject = models.CharField(max_length=80, null=False, blank=False)
    text = models.TextField(blank=False, null=False)

    @property
    def rules_included(self):
        return CrossConferenceEmailRule.objects.filter(email=self, isexclude=False)

    @property
    def rules_excluded(self):
        return CrossConferenceEmailRule.objects.filter(email=self, isexclude=True)


class CrossConferenceEmailRule(models.Model):
    email = models.ForeignKey(CrossConferenceEmail, null=False, blank=False, on_delete=models.CASCADE)
    conference = models.ForeignKey(Conference, null=False, blank=False, on_delete=models.CASCADE)
    isexclude = models.BooleanField(null=False, blank=False)
    ruletype = models.CharField(max_length=10, null=False, blank=False)
    ruleref = models.IntegerField(null=False, blank=False)
    canceled = models.BooleanField(null=False)

    @property
    def displaystr(self):
        if self.ruletype == 'rt':
            if self.ruleref == -1:
                ruledetails = 'All registrations'
            else:
                ruledetails = 'Registrations of type {}'.format(RegistrationType.objects.get(conference=self.conference, id=self.ruleref).regtype)

        elif self.ruletype == 'sp':
            if self.ruleref == -1:
                ruledetails = 'All speakers'
            elif self.ruleref == -2:
                ruledetails = 'All speakers with sessions in status accepted and reserve'
            else:
                ruledetails = 'Speakers with sessions in status {}'.format(get_status_string(self.ruleref))
        else:
            return 'Unknown rule type'

        if self.canceled:
            ruledetails += ' (including canceled registrations)'

        return "{}: {}".format(
            self.conference,
            ruledetails,
        )


class CrossConferenceEmailRecipient(models.Model):
    email = models.ForeignKey(CrossConferenceEmail, null=False, blank=False, on_delete=models.CASCADE)
    address = LowercaseEmailField(null=False, blank=False)

    class Meta:
        unique_together = (
            ('email', 'address'),
        )