-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsettings.py
1626 lines (1353 loc) · 52.5 KB
/
settings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import datetime
import json
import re
import yaml
from functools import cached_property
from cryptography.fernet import InvalidToken
from lxml import etree
from onegov.core.widgets import transform_structure
from onegov.core.widgets import XML_LINE_OFFSET
from onegov.form import Form
from onegov.form.fields import (ChosenSelectField, URLPanelField,
ChosenSelectMultipleEmailField)
from onegov.form.fields import ColorField
from onegov.form.fields import CssField
from onegov.form.fields import MarkupField
from onegov.form.fields import MultiCheckboxField
from onegov.form.fields import PreviewField
from onegov.form.fields import TagsField
from onegov.form.validators import StrictOptional
from onegov.gever.encrypt import encrypt_symmetric, decrypt_symmetric
from onegov.gis import CoordinatesField
from onegov.org import _
from onegov.org.forms.fields import (
HtmlField,
UploadOrSelectExistingMultipleFilesField,
)
from onegov.org.forms.user import AVAILABLE_ROLES
from onegov.org.forms.util import TIMESPANS
from onegov.org.theme import user_options
from onegov.ticket import handlers
from onegov.ticket import TicketPermission
from onegov.user import User
from purl import URL
from wtforms.fields import BooleanField
from wtforms.fields import EmailField
from wtforms.fields import FloatField
from wtforms.fields import IntegerField
from wtforms.fields import PasswordField
from wtforms.fields import RadioField
from wtforms.fields import StringField
from wtforms.fields import TextAreaField
from wtforms.fields import URLField
from wtforms.validators import InputRequired
from wtforms.validators import NumberRange
from wtforms.validators import Optional
from wtforms.validators import URL as UrlRequired
from wtforms.validators import ValidationError
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Sequence
from onegov.org.models import Organisation
from onegov.org.request import OrgRequest
from onegov.org.theme import OrgTheme
from webob import Response
from wtforms import Field
from wtforms.fields.choices import _Choice
ERROR_LINE_RE = re.compile(r'line ([0-9]+)')
class GeneralSettingsForm(Form):
""" Defines the settings form for onegov org. """
if TYPE_CHECKING:
request: OrgRequest
name = StringField(
label=_('Name'),
validators=[InputRequired()])
logo_url = StringField(
label=_('Logo'),
description=_('URL pointing to the logo'),
render_kw={'class_': 'image-url'})
square_logo_url = StringField(
label=_('Logo (Square)'),
description=_('URL pointing to the logo'),
render_kw={'class_': 'image-url'})
reply_to = EmailField(
_('E-Mail Reply Address (Reply-To)'), [InputRequired()],
description=_('Replies to automated e-mails go to this address.'))
primary_color = ColorField(
label=_('Primary Color'))
font_family_sans_serif = ChosenSelectField(
label=_('Default Font Family'),
choices=[],
validators=[InputRequired()]
)
locales = RadioField(
label=_('Languages'),
choices=(
('de_CH', _('German')),
('fr_CH', _('French')),
('it_CH', _('Italian'))
),
validators=[InputRequired()]
)
custom_css = CssField(
label=_('Additional CSS'),
render_kw={'rows': 8},
)
standard_image = StringField(
description=_(
'Will be used if an image is needed, but none has been set'),
fieldset=_('Images'),
label=_('Standard Image'),
render_kw={'class_': 'image-url'}
)
@property
def theme_options(self) -> dict[str, Any]:
options = self.model.theme_options
if self.primary_color.data is None:
options['primary-color'] = user_options['primary-color']
else:
options['primary-color'] = self.primary_color.data
font_family = self.font_family_sans_serif.data
if font_family not in self.theme.font_families.values():
options['font-family-sans-serif'] = self.default_font_family
else:
options['font-family-sans-serif'] = font_family
# override the options using the default values if no value was given
for key in options:
if not options[key]:
options[key] = user_options[key]
return options
@theme_options.setter
def theme_options(self, options: dict[str, Any]) -> None:
self.primary_color.data = options.get('primary-color')
self.font_family_sans_serif.data = options.get(
'font-family-sans-serif') or self.default_font_family
@cached_property
def theme(self) -> OrgTheme:
return self.request.app.settings.core.theme
@property
def default_font_family(self) -> str | None:
return self.theme.default_options.get('font-family-sans-serif')
def populate_obj(self, model: Organisation) -> None: # type:ignore
super().populate_obj(model)
model.theme_options = self.theme_options
model.custom_css = self.custom_css.data or ''
def process_obj(self, model: Organisation) -> None: # type:ignore
super().process_obj(model)
self.theme_options = model.theme_options or {}
self.custom_css.data = model.custom_css or ''
def populate_font_families(self) -> None:
self.font_family_sans_serif.choices = [
(value, label) for label, value in self.theme.font_families.items()
]
def on_request(self) -> None:
self.populate_font_families()
@self.request.after
def clear_locale(response: Response) -> None:
response.delete_cookie('locale')
class FooterSettingsForm(Form):
footer_left_width = IntegerField(
label=_('Column width left side'),
fieldset=_('Footer Division'),
default=3,
validators=[InputRequired()]
)
footer_center_width = IntegerField(
label=_('Column width for the center'),
fieldset=_('Footer Division'),
default=5,
validators=[InputRequired()]
)
footer_right_width = IntegerField(
label=_('Column width right side'),
fieldset=_('Footer Division'),
default=4,
validators=[InputRequired()]
)
contact = TextAreaField(
label=_('Contact'),
description=_('The address and phone number of the municipality'),
render_kw={'rows': 8},
fieldset=_('Information'))
contact_url = URLField(
label=_('Contact Link'),
description=_('URL pointing to a contact page'),
fieldset=_('Information'),
render_kw={'class_': 'internal-url'},
validators=[UrlRequired(), Optional()]
)
opening_hours = TextAreaField(
label=_('Opening Hours'),
description=_('The opening hours of the municipality'),
render_kw={'rows': 8},
fieldset=_('Information'))
opening_hours_url = URLField(
label=_('Opening Hours Link'),
description=_('URL pointing to an opening hours page'),
fieldset=_('Information'),
render_kw={'class_': 'internal-url'},
validators=[UrlRequired(), Optional()]
)
hide_onegov_footer = BooleanField(
label=_('Hide OneGov Cloud information'),
description=_(
'This includes the link to the marketing page, and the link '
'to the privacy policy.'
),
fieldset=_('Information')
)
facebook_url = URLField(
label=_('Facebook'),
description=_('URL pointing to the Facebook site'),
fieldset=_('Social Media'),
validators=[UrlRequired(), Optional()]
)
twitter_url = URLField(
label=_('Twitter'),
description=_('URL pointing to the Twitter site'),
fieldset=_('Social Media'),
validators=[UrlRequired(), Optional()]
)
youtube_url = URLField(
label=_('YouTube'),
description=_('URL pointing to the YouTube site'),
fieldset=_('Social Media'),
validators=[UrlRequired(), Optional()]
)
instagram_url = URLField(
label=_('Instagram'),
description=_('URL pointing to the Instagram site'),
fieldset=_('Social Media'),
validators=[UrlRequired(), Optional()]
)
linkedin_url = URLField(
label=_('Linkedin'),
description=_('URL pointing to the LinkedIn site'),
fieldset=_('Social Media'),
validators=[UrlRequired(), Optional()]
)
tiktok_url = URLField(
label=_('TikTok'),
description=_('URL pointing to the TikTok site'),
fieldset=_('Social Media'),
validators=[UrlRequired(), Optional()]
)
custom_link_1_name = StringField(
label=_('Name'),
description='Name of the Label',
fieldset=_('Custom Link 1')
)
custom_link_1_url = URLField(
label=_('URL'),
description=_('URL to internal/external site'),
fieldset=_('Custom Link 1'),
validators=[UrlRequired(), Optional()]
)
custom_link_2_name = StringField(
label=_('Name'),
description='Name of the Label',
fieldset=_('Custom Link 2')
)
custom_link_2_url = URLField(
label=_('URL'),
description=_('URL to internal/external site'),
fieldset=_('Custom Link 2'),
validators=[UrlRequired(), Optional()]
)
custom_link_3_name = StringField(
label=_('Name'),
description='Name of the Label',
fieldset=_('Custom Link 3')
)
custom_link_3_url = URLField(
label=_('URL'),
description=_('URL to internal/external site'),
fieldset=_('Custom Link 3'),
validators=[UrlRequired(), Optional()]
)
partner_1_name = StringField(
label=_('Name'),
description=_('Name of the partner'),
fieldset=_('First Partner'))
partner_1_img = StringField(
label=_('Image'),
description=_('Logo of the partner'),
render_kw={'class_': 'image-url'},
fieldset=_('First Partner'))
partner_1_url = URLField(
label=_('Website'),
description=_("The partner's website"),
fieldset=_('First Partner'),
validators=[UrlRequired(), Optional()]
)
partner_2_name = StringField(
label=_('Name'),
description=_('Name of the partner'),
fieldset=_('Second Partner'))
partner_2_img = StringField(
label=_('Image'),
description=_('Logo of the partner'),
render_kw={'class_': 'image-url'},
fieldset=_('Second Partner'))
partner_2_url = URLField(
label=_('Website'),
description=_("The partner's website"),
fieldset=_('Second Partner'),
validators=[UrlRequired(), Optional()]
)
partner_3_name = StringField(
label=_('Name'),
description=_('Name of the partner'),
fieldset=_('Third Partner'))
partner_3_img = StringField(
label=_('Image'),
description=_('Logo of the partner'),
render_kw={'class_': 'image-url'},
fieldset=_('Third Partner'))
partner_3_url = URLField(
label=_('Website'),
description=_("The partner's website"),
fieldset=_('Third Partner'),
validators=[UrlRequired(), Optional()]
)
partner_4_name = StringField(
label=_('Name'),
description=_('Name of the partner'),
fieldset=_('Fourth Partner'))
partner_4_img = StringField(
label=_('Image'),
description=_('Logo of the partner'),
render_kw={'class_': 'image-url'},
fieldset=_('Fourth Partner'))
partner_4_url = URLField(
label=_('Website'),
description=_("The partner's website"),
fieldset=_('Fourth Partner'),
validators=[UrlRequired(), Optional()]
)
def ensure_correct_footer_column_width(self) -> bool | None:
for col in ('left', 'center', 'right'):
if getattr(self, f'footer_{col}_width').data <= 0:
field = getattr(self, f'footer_{col}_width')
field.errors.append(
_('The width of the column must be greater than 0')
)
return False
assert self.footer_left_width.data is not None
assert self.footer_center_width.data is not None
assert self.footer_right_width.data is not None
summed_cols = sum([
self.footer_left_width.data,
self.footer_center_width.data,
self.footer_right_width.data
])
if summed_cols != 12:
for col in ('left', 'center', 'right'):
field = getattr(self, f'footer_{col}_width')
field.errors.append(
_('The sum of all the footer columns must be equal to 12')
)
return False
return None
class SocialMediaSettingsForm(Form):
og_logo_default = StringField(
label=_('Image'),
description=_('Default social media preview image for rich link '
'previews. Optimal size is 1200:630 px.'),
fieldset='OpenGraph',
render_kw={'class_': 'image-url'}
)
class FaviconSettingsForm(Form):
favicon_win_url = StringField(
label=_('Icon 16x16 PNG (Windows)'),
description=_('URL pointing to the icon'),
render_kw={'class_': 'image-url'},
)
favicon_mac_url = StringField(
label=_('Icon 32x32 PNG (Mac)'),
description=_('URL pointing to the icon'),
render_kw={'class_': 'image-url'},
)
favicon_apple_touch_url = StringField(
label=_('Icon 57x57 PNG (iPhone, iPod, iPad)'),
description=_('URL pointing to the icon'),
render_kw={'class_': 'image-url'},
)
favicon_pinned_tab_safari_url = StringField(
label=_('Icon SVG 20x20 (Safari)'),
description=_('URL pointing to the icon'),
render_kw={'class_': 'image-url'},
)
class LinksSettingsForm(Form):
disable_page_refs = BooleanField(
label=_('Disable page references'),
description=_(
"Disable showing the copy link '#' for the site reference. "
"The references themselves will still work. "
"Those references are only showed for logged in users.")
)
open_files_target_blank = BooleanField(
label=_('Open files in separate window')
)
class HeaderSettingsForm(Form):
announcement = StringField(
label=_('Announcement'),
fieldset=_('Announcement'),
)
announcement_url = StringField(
label=_('Announcement URL'),
fieldset=_('Announcement'),
)
announcement_bg_color = ColorField(
label=_('Announcement bg color'),
fieldset=_('Announcement')
)
announcement_font_color = ColorField(
label=_('Announcement font color'),
fieldset=_('Announcement')
)
announcement_is_private = BooleanField(
label=_('Only show Announcement for logged-in users'),
fieldset=_('Announcement')
)
header_links = StringField(
label=_('Header links'),
fieldset=_('Header links'),
render_kw={'class_': 'many many-links'}
)
left_header_name = StringField(
label=_('Text'),
description=_(''),
fieldset=_('Text header left side')
)
left_header_url = URLField(
label=_('URL'),
description=_('Optional'),
fieldset=_('Text header left side'),
validators=[UrlRequired(), Optional()]
)
left_header_color = ColorField(
label=_('Font color'),
fieldset=_('Text header left side')
)
left_header_rem = FloatField(
label=_('Relative font size'),
fieldset=_('Text header left side'),
validators=[
NumberRange(0.5, 7)
],
default=1
)
header_additions_fixed = BooleanField(
label=_(
'Keep header links and/or header text fixed to top on scrolling'),
fieldset=_('Header fixation')
)
@property
def header_options(self) -> dict[str, Any]:
return {
'header_links': self.json_to_links(self.header_links.data) or None,
'left_header_name': self.left_header_name.data or None,
'left_header_url': self.left_header_url.data or None,
'left_header_color': self.left_header_color.data,
'left_header_rem': self.left_header_rem.data,
'announcement': self.announcement.data,
'announcement_url': self.announcement_url.data,
'announcement_bg_color': self.announcement_bg_color.data,
'announcement_font_color':
self.announcement_font_color.data,
'announcement_is_private': self.announcement_is_private.data,
'header_additions_fixed': self.header_additions_fixed.data
}
@header_options.setter
def header_options(self, options: dict[str, Any]) -> None:
if not options.get('header_links'):
self.header_links.data = self.links_to_json(None)
else:
self.header_links.data = self.links_to_json(
options.get('header_links')
)
self.left_header_name.data = options.get('left_header_name')
self.left_header_url.data = options.get('left_header_url')
self.left_header_color.data = options.get(
'left_header_color', '#000000'
)
self.left_header_rem.data = options.get('left_header_rem', 1)
self.announcement.data = options.get('announcement', '')
self.announcement_url.data = options.get('announcement_url', '')
self.announcement_bg_color.data = options.get(
'announcement_bg_color', '#FBBC05')
self.announcement_font_color.data = options.get(
'announcement_font_color', '#000000')
self.announcement_is_private.data = options.get(
'announcement_is_private', '')
self.header_additions_fixed.data = options.get(
'header_additions_fixed', '')
if TYPE_CHECKING:
link_errors: dict[int, str]
else:
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.link_errors = {}
def populate_obj(self, model: Organisation) -> None: # type:ignore
super().populate_obj(model)
model.header_options = self.header_options
def process_obj(self, model: Organisation) -> None: # type:ignore
super().process_obj(model)
self.header_options = model.header_options or {}
def validate_header_links(self, field: StringField) -> None:
for text, url in self.json_to_links(self.header_links.data):
if text and not url:
raise ValidationError(_('Please add an url to each link'))
if url and not re.match(r'^(http://|https://|/)', url):
raise ValidationError(
_('Your URLs must start with http://,'
' https:// or / (for internal links)')
)
def json_to_links(
self,
text: str | None = None
) -> list[tuple[str | None, str | None]]:
if not text:
return []
return [
(value['text'], link)
for value in json.loads(text).get('values', [])
if (link := value['link']) or value['text']
]
def links_to_json(
self,
header_links: Sequence[tuple[str | None, str | None]] | None = None
) -> str:
header_links = header_links or []
return json.dumps({
'labels': {
'text': self.request.translate(_('Text')),
'link': self.request.translate(_('URL')),
'add': self.request.translate(_('Add')),
'remove': self.request.translate(_('Remove')),
},
'values': [
{
'text': l[0],
'link': l[1],
'error': self.link_errors.get(ix, '')
} for ix, l in enumerate(header_links)
]
})
class HomepageSettingsForm(Form):
homepage_cover = HtmlField(
label=_('Homepage Cover'),
render_kw={'rows': 10})
homepage_structure = TextAreaField(
fieldset=_('Structure'),
label=_('Homepage Structure (for advanced users only)'),
description=_('The structure of the homepage'),
render_kw={'rows': 32, 'data-editor': 'xml'})
# see homepage.py
redirect_homepage_to = RadioField(
label=_('Homepage redirect'),
default='no',
choices=[
('no', _('No')),
('directories', _('Yes, to directories')),
('events', _('Yes, to events')),
('forms', _('Yes, to forms')),
('publications', _('Yes, to publications')),
('reservations', _('Yes, to reservations')),
('path', _('Yes, to a non-listed path')),
])
redirect_path = StringField(
label=_('Path'),
validators=[InputRequired()],
depends_on=('redirect_homepage_to', 'path'))
def validate_redirect_path(self, field: StringField) -> None:
if not field.data:
return
url = URL(field.data)
if url.scheme() or url.host():
raise ValidationError(
_('Please enter a path without schema or host'))
def validate_homepage_structure(self, field: TextAreaField) -> None:
if field.data:
try:
registry = self.request.app.config.homepage_widget_registry
widgets = registry.values()
transform_structure(widgets, field.data)
except etree.XMLSyntaxError as exception:
correct_line = exception.position[0] - XML_LINE_OFFSET
correct_msg = 'line {}'.format(correct_line)
correct_msg = ERROR_LINE_RE.sub(correct_msg, exception.msg)
field.render_kw = field.render_kw or {}
field.render_kw['data-highlight-line'] = correct_line
raise ValidationError(correct_msg) from exception
class ModuleSettingsForm(Form):
hidden_people_fields = MultiCheckboxField(
label=_('Hide these fields for non-logged-in users'),
fieldset=_('People'),
choices=[
('salutation', _('Salutation')),
('academic_title', _('Academic Title')),
('born', _('Born')),
('profession', _('Profession')),
('political_party', _('Political Party')),
('parliamentary_group', _('Parliamentary Group')),
('email', _('E-Mail')),
('phone', _('Phone')),
('phone_direct', _('Direct Phone Number or Mobile')),
('organisation', _('Organisation')),
('website', _('Website')),
('website_2', _('Website 2')),
('location_address', _('Location address')),
('location_code_city', _('Location Code and City')),
('postal_address', _('Postal address')),
('postal_code_city', _('Postal Code and City')),
('notes', _('Notes')),
('external_user_id', _('External ID'))
])
mtan_session_duration_seconds = IntegerField(
label=_('Duration of mTAN session'),
description=_('Specify in number of seconds'),
fieldset=_('mTAN Access'),
validators=[Optional()]
)
mtan_access_window_requests = IntegerField(
label=_(
'Prevent further accesses to protected resources '
'after this many have been accessed'
),
description=_('Leave empty to disable limiting requests'),
fieldset=_('mTAN Access'),
validators=[Optional()]
)
mtan_access_window_seconds = IntegerField(
label=_(
'Prevent further accesses to protected resources '
'in this time frame'
),
description=_('Specify in number of seconds'),
fieldset=_('mTAN Access'),
validators=[Optional()]
)
class MapSettingsForm(Form):
default_map_view = CoordinatesField(
label=_('The default map view. This should show the whole town'),
render_kw={
'data-map-type': 'crosshair'
})
geo_provider = RadioField(
label=_('Geo provider'),
default='geo-mapbox',
choices=[
('geo-admin', _('Swisstopo (Default)')),
('geo-admin-aerial', _('Swisstopo Aerial')),
('geo-mapbox', 'Mapbox'),
('geo-vermessungsamt-winterthur', 'Vermessungsamt Winterthur'),
('geo-zugmap-basisplan', 'ZugMap Basisplan Farbig'),
('geo-zugmap-orthofoto', 'ZugMap Orthofoto'),
('geo-bs', 'Geoportal Basel-Stadt'),
])
class AnalyticsSettingsForm(Form):
analytics_code = MarkupField(
label=_('Analytics Code'),
description=_('JavaScript for web statistics support'),
render_kw={'rows': 10, 'data-editor': 'html'})
# Points the user to the analytics url e.g. matomo or plausible
analytics_url = URLPanelField(
label=_('Analytics URL'),
description=_('URL pointing to the analytics page'),
render_kw={'readonly': True},
validators=[UrlRequired(), Optional()],
text='',
kind='panel',
hide_label=False
)
def derive_analytics_url(self) -> str:
analytics_code = self.analytics_code.data or ''
if 'analytics.seantis.ch' in analytics_code:
data_domain = analytics_code.split(
'data-domain="', 1)[1].split('"', 1)[0]
return f'https://analytics.seantis.ch/{data_domain}'
elif 'matomo' in analytics_code:
return 'https://stats.seantis.ch'
else:
return ''
def populate_obj(self, model: Organisation) -> None: # type:ignore
super().populate_obj(model)
def process_obj(self, model: Organisation) -> None: # type:ignore
super().process_obj(model)
self.analytics_url.text = self.derive_analytics_url()
class HolidaySettingsForm(Form):
cantonal_holidays = MultiCheckboxField(
label=_('Cantonal holidays'),
choices=[
('AG', _('Aargau')),
('AR', _('Appenzell Ausserrhoden')),
('AI', _('Appenzell Innerrhoden')),
('BL', _('Basel-Landschaft')),
('BS', _('Basel-Stadt')),
('BE', _('Berne')),
('FR', _('Fribourg')),
('GE', _('Geneva')),
('GL', _('Glarus')),
('GR', _('Grisons')),
('JU', _('Jura')),
('LU', _('Lucerne')),
('NE', _('Neuchâtel')),
('NW', _('Nidwalden')),
('OW', _('Obwalden')),
('SH', _('Schaffhausen')),
('SZ', _('Schwyz')),
('SO', _('Solothurn')),
('SG', _('St. Gallen')),
('TG', _('Thurgau')),
('TI', _('Ticino')),
('UR', _('Uri')),
('VS', _('Valais')),
('VD', _('Vaud')),
('ZG', _('Zug')),
('ZH', _('Zürich')),
])
other_holidays = TextAreaField(
label=_('Other holidays'),
description=('31.10 - Halloween'),
render_kw={'rows': 10})
preview = PreviewField(
label=_('Preview'),
fields=('cantonal_holidays', 'other_holidays'),
events=('change', 'click', 'enter'),
url=lambda meta: meta.request.link(
meta.request.app.org,
name='holiday-settings-preview'
))
school_holidays = TextAreaField(
label=_('School holidays'),
description=('12.03.2022 - 21.03.2022'),
render_kw={'rows': 10})
def validate_other_holidays(self, field: TextAreaField) -> None:
if not field.data:
return
for line in field.data.splitlines():
if not line.strip():
continue
if line.count('-') < 1:
raise ValidationError(_('Format: Day.Month - Description'))
if line.count('-') > 1:
raise ValidationError(_('Please enter one date per line'))
date, _description = line.split('-', 1)
if date.count('.') < 1:
raise ValidationError(_('Format: Day.Month - Description'))
if date.count('.') > 1:
raise ValidationError(_('Please enter only day and month'))
def parse_date(self, date: str) -> datetime.date:
day, month, year = date.split('.', 2)
try:
return datetime.date(int(year), int(month), int(day))
except (ValueError, TypeError) as exception:
raise ValidationError(_(
'${date} is not a valid date',
mapping={'date': date}
)) from exception
def validate_school_holidays(self, field: TextAreaField) -> None:
if not field.data:
return
for line in field.data.splitlines():
if not line.strip():
continue
if line.count('-') < 1:
raise ValidationError(
_('Format: Day.Month.Year - Day.Month.Year')
)
if line.count('-') > 1:
raise ValidationError(_('Please enter one date pair per line'))
start, end = line.split('-', 1)
if start.count('.') != 2:
raise ValidationError(
_('Format: Day.Month.Year - Day.Month.Year')
)
if end.count('.') != 2:
raise ValidationError(
_('Format: Day.Month.Year - Day.Month.Year')
)
start_date = self.parse_date(start)
end_date = self.parse_date(end)
if end_date <= start_date:
raise ValidationError(
_('End date needs to be after start date')
)
# FIXME: Use TypedDict?
@property
def holiday_settings(self) -> dict[str, Any]:
def parse_other_holidays_line(line: str) -> tuple[int, int, str]:
date, desc = line.strip().split('-', 1)
day, month = date.split('.')
return int(month), int(day), desc.strip()
def parse_school_holidays_line(
line: str
) -> tuple[int, int, int, int, int, int]:
start, end = line.strip().split('-', 1)
start_day, start_month, start_year = start.split('.', 2)
end_day, end_month, end_year = end.split('.', 2)
return (
int(start_year), int(start_month), int(start_day),
int(end_year), int(end_month), int(end_day)
)
return {
'cantons': self.cantonal_holidays.data,
'school': (
parse_school_holidays_line(l)
for l in (self.school_holidays.data or '').splitlines()
if l.strip()
),
'other': (
parse_other_holidays_line(l)
for l in (self.other_holidays.data or '').splitlines()
if l.strip()
)
}
@holiday_settings.setter
def holiday_settings(self, data: dict[str, Any]) -> None:
data = data or {}
def format_other(d: tuple[int, int, str]) -> str:
return f'{d[1]:02d}.{d[0]:02d} - {d[2]}'
def format_school(d: tuple[int, int, int, int, int, int]) -> str:
return (
f'{d[2]:02d}.{d[1]:02d}.{d[0]:04d} - '
f'{d[5]:02d}.{d[4]:02d}.{d[3]:04d}'
)
self.cantonal_holidays.data = data.get(
'cantons', ())
self.other_holidays.data = '\n'.join(
format_other(d) for d in data.get('other', ()))
self.school_holidays.data = '\n'.join(
format_school(d) for d in data.get('school', ()))
def populate_obj(self, model: Organisation) -> None: # type:ignore
model.holiday_settings = self.holiday_settings
def process_obj(self, model: Organisation) -> None: # type:ignore
self.holiday_settings = model.holiday_settings