cmsmanage/paperwork/views.py

189 lines
5.7 KiB
Python
Raw Normal View History

from django.conf import settings
from django.contrib import staticfiles
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.shortcuts import get_object_or_404, render
from django.views.generic import ListView
import django_tables2 as tables
import requests
import weasyprint
from django_mysql.models import GroupConcat
from django_tables2 import SingleTableMixin
from django_tables2.export.views import ExportMixin
from membershipworks.models import Member
from .models import Certification, Department, InstructorOrVendor, Waiver
WIKI_URL = settings.WIKI_URL
class MemberCertificationListView(ListView):
template_name = "paperwork/member_certifications.dj.html"
context_object_name = "certifications"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["show_outdated"] = (
self.request.GET.get("show_outdated", "false").lower() == "true"
)
return context
def get_queryset(self):
self.member = get_object_or_404(Member, uid=self.kwargs["uid"])
return Certification.objects.filter(member=self.member)
@login_required
def department_certifications(request):
if request.user.is_superuser:
departments = Department.objects.prefetch_related(
"shop_lead_flag__members"
).all()
elif member := Member.from_user(request.user) is not None:
departments = Department.objects.filter_by_shop_lead(member)
else:
departments = []
certifications = Certification.objects.filter(
certification_version__definition__department__in=departments
).prefetch_related(
"certification_version__definition__department",
"member",
)
return render(
request,
"paperwork/department_certifications.dj.html",
{"departments": departments, "certifications": certifications},
)
def certification_pdf(request, cert_name):
wiki_page = f"{cert_name.replace('_', ' ')} Certification"
r = requests.get(
WIKI_URL + "/api.php",
params={
"action": "askargs",
"conditions": wiki_page,
"printouts": "Version|Approval Date|Approval status",
"format": "json",
"api_version": "2",
"origin": "*",
},
)
results = r.json()["query"]["results"]
if wiki_page not in results:
return HttpResponseNotFound(
f'No such certification found on wiki: <a href="{WIKI_URL}/wiki/{wiki_page}">{wiki_page}</a>'
)
printouts = results[wiki_page]["printouts"]
if printouts["Approval status"] != ["approve"]:
return HttpResponseBadRequest(
f'Certification is not yet approved on wiki: <a href="{WIKI_URL}/wiki/{wiki_page}">{wiki_page}</a>'
)
filename = (
f'{wiki_page}_v{printouts["Version"][0]} - {printouts["Approval Date"][0]}.pdf'
)
html = weasyprint.HTML(f"{WIKI_URL}/index.php?title={wiki_page}")
stylesheet = staticfiles.finders.find("paperwork/certification-print.css")
pdf = html.write_pdf(stylesheets=[stylesheet])
return HttpResponse(
pdf,
headers={
"Content-Type": "application/pdf",
"Content-Disposition": f'inline; filename="{filename}"',
},
)
class WarnEmptyColumn(tables.Column):
attrs = {
"td": {
"class": lambda value, bound_column: "table-danger"
if value == bound_column.default
else ""
}
}
class WaiverReportTable(tables.Table):
emergency_contact_name = WarnEmptyColumn()
emergency_contact_number = WarnEmptyColumn()
class Meta:
model = Waiver
fields = [
"name",
"date",
"emergency_contact_name",
"emergency_contact_number",
"waiver_version",
"guardian_name",
"guardian_relation",
"guardian_date",
]
class WaiverReport(ExportMixin, SingleTableMixin, PermissionRequiredMixin, ListView):
permission_required = "paperwork.view_waiver"
template_name = "paperwork/waiver_report.dj.html"
queryset = Waiver.objects.order_by("name").all()
table_class = WaiverReportTable
table_pagination = False
class InstructorOrVendorTable(tables.Table):
instructor_agreement_date = WarnEmptyColumn(
"Instructor Agreement Date(s)", default="Missing"
)
w9_date = WarnEmptyColumn(default="Missing")
class Meta:
model = InstructorOrVendor
fields = [
"name",
"instructor_agreement_date",
"w9_date",
"phone",
"email_address",
]
class InstructorOrVendorReport(
ExportMixin,
SingleTableMixin,
PermissionRequiredMixin,
ListView,
):
permission_required = "paperwork.view_instructororvendor"
template_name = "paperwork/instructor_or_vendor_report.dj.html"
queryset = InstructorOrVendor.objects.order_by("name").all()
table_class = InstructorOrVendorTable
export_formats = ("csv", "xlsx", "ods")
def get_table_data(self):
return (
super()
.get_table_data()
.values("name")
.annotate(
instructor_agreement_date=GroupConcat(
"instructor_agreement_date", distinct=True, ordering="asc"
),
w9_date=GroupConcat("w9_date", distinct=True, ordering="asc"),
phone=GroupConcat("phone", distinct=True, ordering="asc"),
email_address=GroupConcat(
"email_address", distinct=True, ordering="asc"
),
)
)