diff --git a/kaehmy/views.py b/kaehmy/views.py index 948e24c..aff149b 100644 --- a/kaehmy/views.py +++ b/kaehmy/views.py @@ -25,28 +25,38 @@ from webapp.models import processHooks def list_view(request, *args, **kwargs): """Kaehmy application list""" - role_filter = request.GET.get('role', None) - if role_filter is not None and str(role_filter) != '-1': - applications = Application.objects.filter(custom_roles__id=role_filter) | Application.objects.filter(preset_roles__id=role_filter) + role_filter = request.GET.get("role", None) + if role_filter is not None and str(role_filter) != "-1": + applications = Application.objects.filter( + custom_roles__id=role_filter + ) | Application.objects.filter(preset_roles__id=role_filter) else: applications = Application.objects.all() - applications = applications.order_by('-timestamp') - filter_options_preset = PresetRole.objects.annotate(form_count=Count('forms')).filter(form_count__gt=0) - filter_options_preset_list = [(r.id, r.name, r.form_count) for r in filter_options_preset] - filter_options_custom = CustomRole.objects.annotate(form_count=Count('forms')).filter(form_count__gt=0) - filter_options_custom_list = [(r.id, r.name, r.form_count) for r in filter_options_custom] + applications = applications.order_by("-timestamp") + filter_options_preset = PresetRole.objects.annotate( + form_count=Count("forms") + ).filter(form_count__gt=0) + filter_options_preset_list = [ + (r.id, r.name, r.form_count) for r in filter_options_preset + ] + filter_options_custom = CustomRole.objects.annotate( + form_count=Count("forms") + ).filter(form_count__gt=0) + filter_options_custom_list = [ + (r.id, r.name, r.form_count) for r in filter_options_custom + ] filter_options = filter_options_preset_list + filter_options_custom_list filter_options.sort(key=lambda f: f[1]) context = { - 'applications': applications, - 'application_count': len(applications), - 'filter_options': filter_options + "applications": applications, + "application_count": len(applications), + "filter_options": filter_options, } - return render(request, 'kaehmy:list.html', context) + return render(request, "kaehmy:list.html", context) @ensure_csrf_cookie @@ -57,23 +67,21 @@ def comment(request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): comment = form.save() - email = comment.parent.email name = comment.name - subject = 'Kaehmyysi tai kommenttiisi on vastattu!' - body = (f'{name.capitalize()} on vastannut kaehmyhakemukseesi tai kommenttiisi kaehmypalvelussa.\r\n\r\n' - 'Käy lukemassa viesti osoitteessa https://{URL}/kaehmy') + to_email = comment.parent.email + subject = "Kaehmyysi tai kommenttiisi on vastattu!" + email_body = ( + f"{name.capitalize()} on vastannut kaehmyhakemukseesi tai kommenttiisi kaehmypalvelussa.\r\n\r\n" + "Käy lukemassa viesti osoitteessa https://{URL}/kaehmy" + ) + send_email(to=to_email, subject=subject, body=email_body) + logging.debug(f"Sent kaehmy comment email to recipient <{to_email}>") - send_email(email, subject, body) - logging.debug( - f'Sent kaehmy comment email to recipient <{email}>') - - return redirect('/kaehmy') + return redirect("/kaehmy") else: - context = { - 'error': form.errors - } - return render(request, 'kaehmy:error.html', context) + context = {"error": form.errors} + return render(request, "kaehmy:error.html", context) @require_http_methods(["GET"]) @@ -88,24 +96,24 @@ def statistics_view(request, *args, **kwargs): for preset in preset_roles: people = [form.name for form in preset.forms.all()] - role_list.append((preset.name, len(people), ', '.join(people))) + role_list.append((preset.name, len(people), ", ".join(people))) for custom in custom_roles: people = [form.name for form in custom.forms.all()] - role_list.append((custom.name, len(people), ', '.join(people))) + role_list.append((custom.name, len(people), ", ".join(people))) context = { - 'applications': applications, - 'application_count': len(applications), - 'role_list': role_list + "applications": applications, + "application_count": len(applications), + "role_list": role_list, } - return render(request, 'kaehmy:statistics.html', context) + return render(request, "kaehmy:statistics.html", context) @require_http_methods(["GET"]) def view(request, *args, **kwargs): """Render Kaehmy form page.""" form = ApplicationForm() - return render(request, 'kaehmy:kaehmy.html', {'form': form}) + return render(request, "kaehmy:kaehmy.html", {"form": form}) @ensure_csrf_cookie @@ -115,46 +123,47 @@ def submit(request, *args, **kwargs): form = ApplicationForm(request.POST) if form.is_valid(): application = form.save() - custom_name = form.cleaned_data.get('custom_role_name') - custom_is_board = form.cleaned_data.get('custom_role_is_board') + custom_name = form.cleaned_data.get("custom_role_name") + custom_is_board = form.cleaned_data.get("custom_role_is_board") if len(custom_name) > 0: - custom_role = CustomRole( - name=custom_name, is_board=custom_is_board) + custom_role = CustomRole(name=custom_name, is_board=custom_is_board) custom_role.save() application.custom_roles.add(custom_role) - url = f'https://{URL}/kaehmy' + url = f"https://{URL}/kaehmy" + name = form.cleaned_data.get("name", "Anonymous") + email_body = ( + f"Moikka {name}!\r\n\r\nHienoa, että kilta kiinnostaa! Kaehmysi on vastaanotettu.\r\n" + "Mahdollisista kommenteista tulee ilmoitus sähköpostitse.\r\n\r\n" + "Käy katsomassa kaehmytilanne osoitteessa {url}" + ) - email = form.cleaned_data.get('email', '') - name = form.cleaned_data.get('name', 'Anonymous') - subject = 'Arwokas kirjattu kirje mahdolliselle tulewalle kiltahenkilölle' - body = ('Moikka {}!\r\n\r\nHienoa, että kilta kiinnostaa! Kaehmysi on vastaanotettu.\r\n' - 'Mahdollisista kommenteista tulee ilmoitus sähköpostitse.\r\n\r\n' - 'Käy katsomassa kaehmytilanne osoitteessa {}').format(name, url) + to_email = form.cleaned_data.get("email", "") + subject = "Arwokas kirjattu kirje mahdolliselle tulewalle kiltahenkilölle" - send_email(email, subject, body) - logging.debug('Sent kaehmy email to recipient <{}>'.format(email)) + send_email(to_email, subject, email_body) + logging.debug(f"Sent kaehmy email to recipient <{to_email}>") - processHooks(message=f'Uusi New kaehmy! {name} -> {url}', eventType="kaehmy") + processHooks(message=f"Uusi New kaehmy! {name} -> {url}", eventType="kaehmy") else: - context = { - 'error': form.errors - } - return render(request, 'kaehmy:error.html', context) - return HttpResponseRedirect('/kaehmy') + context = {"error": form.errors} + return render(request, "kaehmy:error.html", context) + return HttpResponseRedirect("/kaehmy") -@require_http_methods(['GET']) -@login_required(login_url='/admin/login') +@require_http_methods(["GET"]) +@login_required(login_url="/admin/login") def export_view(request, *args, **kwargs): def make_table(queryset): - table = ExportTable(queryset, - request=request, - exclude=['id'], - attrs={'class': 'table table-bordered table-hover'}) + table = ExportTable( + queryset, + request=request, + exclude=["id"], + attrs={"class": "table table-bordered table-hover"}, + ) - table.paginate(page=request.GET.get('page', 1), per_page=9999) + table.paginate(page=request.GET.get("page", 1), per_page=9999) table_html = convert_table_to_html(table, request) return table_html @@ -163,7 +172,7 @@ def export_view(request, *args, **kwargs): board = filter(lambda q: q.has_any_board_role(), kaehmys) context = { - 'non_board_table': make_table(non_board), - 'board_table': make_table(board), + "non_board_table": make_table(non_board), + "board_table": make_table(board), } - return render(request, 'kaehmy:export.html', context) + return render(request, "kaehmy:export.html", context) diff --git a/locale/en/LC_MESSAGES/django.mo b/locale/en/LC_MESSAGES/django.mo index 061d4f0..b725197 100644 Binary files a/locale/en/LC_MESSAGES/django.mo and b/locale/en/LC_MESSAGES/django.mo differ diff --git a/locale/en/LC_MESSAGES/django.po b/locale/en/LC_MESSAGES/django.po index ac3a7f3..d088811 100644 --- a/locale/en/LC_MESSAGES/django.po +++ b/locale/en/LC_MESSAGES/django.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2022-01-13 00:07+0200\n" +"POT-Creation-Date: 2022-01-13 22:18+0200\n" "PO-Revision-Date: 2017-11-02 23:09+0200\n" "Last-Translator: \n" "Language-Team: \n" @@ -37,7 +37,7 @@ msgstr "Sössö articles" msgid "Today's lunch" msgstr "" -#: infoscreen/models.py:212 webapp/models.py:73 +#: infoscreen/models.py:212 webapp/models.py:93 msgid "Events" msgstr "Events" @@ -113,7 +113,7 @@ msgid "Delete" msgstr "Delete" #: infoscreen/templates/tabs/add_remove.html:23 kaehmy/models.py:57 -#: kaehmy/templates/list.html:36 webapp/models.py:147 webapp/models.py:176 +#: kaehmy/templates/list.html:36 webapp/models.py:188 webapp/models.py:223 msgid "Name" msgstr "Name" @@ -327,7 +327,7 @@ msgstr "" msgid "Custom role name" msgstr "" -#: kaehmy/models.py:105 webapp/models.py:177 +#: kaehmy/models.py:105 webapp/models.py:224 msgid "Board member" msgstr "Board member" @@ -419,8 +419,6 @@ msgid "Päivämääriä & deadlineja" msgstr "Dates and deadlines" #: kaehmy/templates/kaehmy.html:31 -#, fuzzy -#| msgid "Vaalikokous, osa 1 (puheenjohtajan valinta)" msgid "Vaalikokous, osa 1 (puheenjohtajan valinta) ja hallitustyrkkypaneeli" msgstr "Election meeting, part 1 (chairman election)" @@ -437,14 +435,7 @@ msgid "Vaalikokous, osa 3 (toimarien valinta)" msgstr "Election meeting, part 3 (non-board election)" #: kaehmy/templates/kaehmy.html:77 -#, fuzzy, python-format -#| msgid "" -#| "\n" -#| " Hyväksyn tietosuojaselosteen ja " -#| "tietojeni tallentamisen.\n" -#| " " +#, python-format msgid "" "\n" " Hyväksyn ") try: webhook_message = render_to_string( - 'ohlhafv:tgmsg.tpl', { - 'challenge': challenge, - 'url': url}) + "ohlhafv:tgmsg.tpl", {"challenge": challenge, "url": url} + ) processHooks(message=webhook_message, eventType="ohlhafv") except Exception: pass - logging.debug( - 'Sent ohlhafv email to recipient <{}>'.format(email)) else: pass - return HttpResponseRedirect('/ohlhafv/list/') + return HttpResponseRedirect("/ohlhafv/list/") @ensure_csrf_cookie @@ -63,9 +62,9 @@ def ohlhafv_submit(request, *args, **kwargs): def ohlhafv_list(request, *args, **kwargs): """Present Ohlhafv challenges list.""" challenges = OhlhafvChallenge.objects.all() - challenges = challenges.order_by('-id') + challenges = challenges.order_by("-id") context = { - 'challenges': challenges, - 'challenge_count': len(challenges), + "challenges": challenges, + "challenge_count": len(challenges), } - return render(request, 'ohlhafv:list.html', context) + return render(request, "ohlhafv:list.html", context) diff --git a/webapp/utils.py b/webapp/utils.py index c311eba..c1f6dff 100644 --- a/webapp/utils.py +++ b/webapp/utils.py @@ -1,18 +1,30 @@ """Webapp utils.""" -from django.utils import timezone -import sendgrid -from sendgrid.helpers.mail import * - -from datetime import timedelta import logging -from django.template.loader import render_to_string -from django.core.files.base import ContentFile import base64 import uuid -from sikweb.settings import FRONTEND_URL, EMAIL_API_KEY, DEFAULT_EMAIL_FROM_ADDR, ENABLE_AUTOMATIC_EMAILS import imghdr import markdown +import sendgrid +from django.utils import timezone +from sendgrid.helpers.mail import ( + Email, + To, + Subject, + Mail, + HtmlContent, + PlainTextContent, +) +from django.template.loader import render_to_string +from django.core.files.base import ContentFile +from sikweb.settings import ( + FRONTEND_URL, + EMAIL_API_KEY, + DEFAULT_EMAIL_FROM, + DEFAULT_EMAIL_FROM_ADDR, + ENABLE_AUTOMATIC_EMAILS, +) +from datetime import timedelta def get_file_extension(file_name, decoded_file): @@ -25,15 +37,15 @@ def decode_base64_file(data): # Check if this is a base64 string if isinstance(data, str): # Check if the base64 string is in the "data:" format - if 'data:' in data and ';base64,' in data: + if "data:" in data and ";base64," in data: # Break out the header from the base64 content - header, data = data.split(';base64,') + header, data = data.split(";base64,") # Try to decode the file. Return validation error if it fails. try: decoded_file = base64.b64decode(data) except TypeError: - TypeError('invalid_image') + TypeError("invalid_image") # Generate file name: file_name = str(uuid.uuid4()) @@ -41,7 +53,10 @@ def decode_base64_file(data): # Get the file name extension: file_extension = get_file_extension(file_name, decoded_file) - complete_file_name = "%s.%s" % (file_name, file_extension, ) + complete_file_name = "%s.%s" % ( + file_name, + file_extension, + ) return ContentFile(decoded_file, name=complete_file_name) @@ -51,50 +66,51 @@ def month_from_now(): return timezone.now() + timedelta(days=30) -def send_email(to, subject, body, html=False): - if not ENABLE_AUTOMATIC_EMAILS: +def send_email(to: str, subject: str, body: str, html: bool = False): + if ENABLE_AUTOMATIC_EMAILS is False: logging.debug("Skipping email") logging.debug(f"to: {to}") logging.debug(f"subject: {subject}") logging.debug(f"body: {body}") return - from_email = DEFAULT_EMAIL_FROM_ADDR - to_email = to - sub = subject + from_email = Email(email=DEFAULT_EMAIL_FROM_ADDR, name=DEFAULT_EMAIL_FROM) + to_email = To(email=to) + sub = Subject(subject=subject) html_content = None plain_text_content = None - if (html): - html_content = HtmlContent(body) + if html: + html_content = HtmlContent(content=body) else: - plain_text_content = PlainTextContent(body) + plain_text_content = PlainTextContent(content=body) mail = Mail( from_email=from_email, to_emails=to_email, subject=sub, html_content=html_content, - plain_text_content=plain_text_content + plain_text_content=plain_text_content, ) try: - sg = sendgrid.SendGridAPIClient(EMAIL_API_KEY) + sg = sendgrid.SendGridAPIClient(api_key=EMAIL_API_KEY) response = sg.send(mail) if response.status_code != 202: - raise Exception(f'Failed to send email: {response.body}') + raise Exception(f"Failed to send email: {response.body}") except Exception as ex: - logging.exception('Failed to send email.') + logging.exception("Failed to send email.") def send_signup_email(to, subject, id, uuid, content): message = render_to_string( - 'webapp:signup_email.html', { - 'url': f"https://{FRONTEND_URL}/signup/edit/{id}/{uuid}", - 'content': markdown.markdown(content), - } + "webapp:signup_email.html", + { + "url": f"https://{FRONTEND_URL}/signup/edit/{id}/{uuid}", + "content": markdown.markdown(content), + }, ) return send_email(to, subject, message, True)