Skip to content
Snippets Groups Projects
Commit 4edb2660 authored by Jonathan Weth's avatar Jonathan Weth :keyboard:
Browse files

Show hints in PDF (first version)

parent bc5eec62
No related branches found
No related tags found
No related merge requests found
Showing with 183 additions and 84 deletions
from django.contrib import admin
# Register your models here.
from timetable.models import Hint, HintClass
from timetable.models import Hint
admin.site.register(Hint)
admin.site.register(HintClass)
def refresh_cache(modeladmin, request, queryset):
for obj in queryset.all():
obj.save()
refresh_cache.short_description = "Cache aktualisieren"
class HintAdmin(admin.ModelAdmin):
exclude = ("text_as_latex", "classes_formatted")
actions = [refresh_cache]
admin.site.register(Hint, HintAdmin)
......@@ -54,3 +54,4 @@ def get_all_hints_by_time_period(from_date, to_date):
def filter_date(date):
hints = Hint.objects.filter(from_date__lte=date, to_date__gte=date).order_by("from_date", "classes")
return hints
import os
import subprocess
from schoolapps.settings import BASE_DIR
def convert_markdown_2_latex(s):
try:
# Write markdown file
md_file = open(os.path.join(BASE_DIR, "latex", "m2l.md"), "w", encoding="utf8")
md_file.write(s)
md_file.close()
# Execute pandoc to convert markdown to latex
bash_command = "pandoc --from markdown --to latex --output {} {}".format(
os.path.join(BASE_DIR, "latex", "m2l.tex"),
os.path.join(BASE_DIR, "latex", "m2l.md"))
process = subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
print("[MD TO LATEX]", output)
# Read converted latex from file
tex_file = open(os.path.join(BASE_DIR, "latex", "m2l.tex"), "r", encoding="utf8")
r = tex_file.read()
tex_file.close()
# Replace some things
r = r.replace("\subparagraph", "\subsubsection")
r = r.replace("\paragraph", "\subsubsection")
r = r.replace("section", "section*")
# Return latex
return r
except Exception as e:
# Print error
print("[MD TO LATEX]", e)
return ""
# Generated by Django 2.2.1 on 2019-05-02 15:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timetable', '0005_auto_20190413_1413'),
]
operations = [
migrations.AddField(
model_name='hint',
name='text_as_latex',
field=models.TextField(blank=True, verbose_name='LaTeX (automatisch)'),
),
]
# Generated by Django 2.2.1 on 2019-05-02 15:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timetable', '0006_hint_text_as_latex'),
]
operations = [
migrations.AddField(
model_name='hintclass',
name='class_name',
field=models.CharField(default='', max_length=100),
),
]
# Generated by Django 2.2.1 on 2019-05-02 15:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('timetable', '0007_hintclass_class_name'),
]
operations = [
migrations.RenameField(
model_name='hintclass',
old_name='class_name',
new_name='name',
),
]
# Generated by Django 2.2.1 on 2019-05-02 15:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timetable', '0008_auto_20190502_1722'),
]
operations = [
migrations.AddField(
model_name='hint',
name='classes_formatted',
field=models.CharField(blank=True, max_length=200),
),
]
from datetime import date
from django.db import models
from django.db.models import ManyToManyField
from martor.models import MartorField
from untisconnect.api import get_class_by_id, get_all_classes
from timetable.m2l import convert_markdown_2_latex
from untisconnect.api import get_all_classes, format_classes
from untisconnect.models import Class
classes = get_all_classes()
......@@ -12,18 +12,19 @@ class_choices = [(x.id, x.name) for x in classes]
class HintClass(models.Model):
"""Maps a UNTIS class to a usable format for Django models"""
class_id = models.IntegerField(choices=class_choices)
name = models.CharField(max_length=100, default="")
def __str__(self):
try:
_class = get_class_by_id(self.class_id)
return _class.name
except Exception:
return "Unbekannte Klasse"
return self.name
# Map all classes from UNTIS to HintClass objects
for x in classes:
HintClass.objects.get_or_create(class_id=x.id)
obj, _ = HintClass.objects.get_or_create(class_id=x.id)
obj.name = x.name
obj.save()
class Hint(models.Model):
......@@ -38,18 +39,37 @@ class Hint(models.Model):
classes = models.ManyToManyField(HintClass, related_name="hints", verbose_name="Klassen", blank=True)
teachers = models.BooleanField(verbose_name="Lehrer?", default=False, blank=True)
# Caching
text_as_latex = models.TextField(verbose_name="LaTeX (automatisch)", blank=True)
classes_formatted = models.CharField(max_length=200, blank=True)
class Meta:
verbose_name = "Hinweis"
verbose_name_plural = "Hinweise"
def __init__(self, *args, **kwargs):
super(Hint, self).__init__(*args, **kwargs)
def __str__(self):
classes_list = [str(x) for x in self.classes.all()]
if self.teachers:
classes_list.append("Lehrkräfte")
targets = ", ".join(classes_list)
targets = self.classes_formatted
if self.teachers and targets != "":
targets += ", Lehrkräfte"
elif self.teachers:
targets = "Lehrkräfte"
return "[{}]: {}–{}".format(targets, self.from_date, self.to_date)
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
# Convert LaTeX already when saving as cache because then is no need to do it later > performance savings
self.text_as_latex = convert_markdown_2_latex(self.text)
# Format classes already > cache, too
self.classes_formatted = format_classes(self.classes.all())
super(Hint, self).save(force_insert=force_insert, force_update=force_update, using=using,
update_fields=update_fields)
class Timetable(models.Model):
class Meta:
......
......@@ -114,8 +114,8 @@ def generate_pdf(tex, filename):
tex_file.close()
# Execute pdflatex to generate the PDF
bash_command = "pdflatex -output-directory {} {}.tex".format(os.path.join(BASE_DIR, "latex"),
os.path.join(BASE_DIR, "latex", filename))
bash_command = "pdflatex -halt-on-error -output-directory {} {}.tex".format(os.path.join(BASE_DIR, "latex"),
os.path.join(BASE_DIR, "latex", filename))
print(bash_command)
process = subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
......@@ -139,73 +139,14 @@ def tex_replacer(s):
return s
def generate_class_tex(subs, date, header_info):
def generate_class_tex(subs, date, header_info, hints=None):
"""Generate LaTeX for a PDF by a substitution table"""
tex_body = ""
# Format dates
# status_date = formats.date_format(date, format="j. F Y, \\K\\W W ")
# current_date = formats.date_format(timezone.datetime.now(), format="j. F Y H:i")
# head_date = formats.date_format(date, format="l, j. F Y")
# Generate header with dates
# tex_body += TEX_HEADER_CLASS % (status_date, current_date, head_date)
# if header_info.is_box_needed():
# tex_body += TEX_HEADER_BOX_START
# for row in header_info.rows:
# tex_body += TEX_HEADER_BOX_ROW_A % row[0]
# tex_body += TEX_HEADER_BOX_MIDDLE
# for row in header_info.rows:
# tex_body += TEX_HEADER_BOX_ROW_B % row[1]
# tex_body += TEX_HEADER_BOX_END
# Begin table
# tex_body += TEX_TABLE_HEADER_CLASS
# color_background = True
# last_classes = ""
for sub in subs:
# Color groups of classes in grey/white
# if last_classes != sub.classes:
# color_background = not color_background
#
# last_classes = sub.classes
# if color_background:
# tex_body += '\\rowcolor{grey}'
# Get color tag for row
# color = "\color{%s}" % sub.color
# Print classes
# print(sub.classes)
# tex_body += color
# tex_body += '\\textbf{' + sub.classes + '} & '
# Print lesson number, teacher, subject and room
for i in [sub.lesson, sub.teacher, sub.subject, sub.room]:
# tex_body += color
tex_body += tex_replacer(i) + ' & '
# Print badge (Cancellation)
# if sub.badge is not None:
# tex_body += """\\large\\badge{%s}""" % sub.badge
# Print notice and new line
# tex_body += color
# tex_body += "\\Large\\textit{%s}\\\\\n" % (sub.text or "")
# End table
# tex_body += '\\end{longtable}'
# Connect header, body and footer
# tex_content = TEX_HEADER + tex_body + TEX_FOOTER
# return tex_content
context = {
"subs": subs,
"date": date,
"header_info": header_info,
"LOGO_FILENAME": LOGO_FILENAME
"LOGO_FILENAME": LOGO_FILENAME,
"hints": hints
}
return render_to_string("timetable/latex/substitutions.tex", context)
{% load martortags %}
{% if hints %}
\subsection*{Hinweise}
\vspace{-0.7em}
\begin{itemize}
\setlength\itemsep{0.1em}
{% for hint in hints %}
\normalsize
\item \small
{{ hint.classes_formatted }}{% if hint.teachers and hint.classes.all %}, {% endif %}{% if hint.teachers %}Lehrkräfte{% endif %}:
\normalsize
{{ hint.text_as_latex|safe }}
{% endfor %}
\end{itemize}
\vspace{-1em}
{% endif %}
\ No newline at end of file
......@@ -12,6 +12,7 @@
\usepackage{longtable}
\usepackage{multirow}
\usepackage{color, colortbl}
\usepackage[colorlinks, linkcolor = black, citecolor = black, filecolor = black, urlcolor = black]{hyperref}
\usepackage{ulem, xpatch}
\xpatchcmd{\sout}
......@@ -57,14 +58,14 @@ Stand: {% now "j. F Y H:i" %}\\
{# \vspace{10pt}#}
\section*{\Huge Vertretungen {{ date|date:"l, j. F Y"}}}
{% include "timetable/latex/hints.tex" %}
{% if header_info.is_box_needed %}
\fbox{
\begin{tabular}{@{}ll@{}}
{% for row in header_info.rows %}
\textbf{ {{ row.0 }} } & {{ row.1 }} \\
{% endfor %}
\end{tabular}
}
{% endif %}
% Init table
......
......@@ -6,12 +6,11 @@ from django.contrib.auth.decorators import login_required, permission_required
from django.http import Http404, FileResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.utils import timezone
from material import Fieldset, Row
from schoolapps.settings import SHORT_WEEK_DAYS, LONG_WEEK_DAYS
from timetable.filters import HintFilter
from timetable.forms import HintForm
from timetable.hints import get_all_hints_by_date, get_all_hints_by_time_period, get_all_hints_by_class_and_time_period, \
from timetable.hints import get_all_hints_by_time_period, get_all_hints_by_class_and_time_period, \
get_all_hints_for_teachers_by_time_period, get_all_hints_not_for_teachers_by_time_period
from timetable.pdf import generate_class_tex, generate_pdf
......@@ -239,9 +238,12 @@ def sub_pdf(request):
subs = get_substitutions_by_date(date)
sub_table = generate_sub_table(subs)
header_info = get_header_information(subs, date)
hints = list(get_all_hints_by_time_period(date, date))
# latex = convert_markdown_2_latex(hints[0].text)
# print(latex)
# Generate LaTeX
tex = generate_class_tex(sub_table, date, header_info)
tex = generate_class_tex(sub_table, date, header_info, hints)
# Generate PDF
generate_pdf(tex, "class{}".format(i))
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment