2022-11-17 18:39:45 +01:00
|
|
|
import copy
|
2022-12-15 22:32:01 +01:00
|
|
|
import json
|
2022-06-13 00:16:07 +02:00
|
|
|
from collections import defaultdict
|
2022-11-17 20:33:20 +01:00
|
|
|
from datetime import datetime, timedelta
|
2022-11-02 23:21:08 +01:00
|
|
|
from io import BytesIO
|
2023-01-04 22:51:58 +01:00
|
|
|
from typing import Generator, Union, Any, List, Tuple, TextIO
|
2022-11-17 20:33:20 +01:00
|
|
|
from pathlib import Path
|
2022-05-17 22:16:45 +02:00
|
|
|
|
|
|
|
import pandas as pd
|
2022-12-15 22:32:01 +01:00
|
|
|
from flask import current_app
|
2022-11-02 23:21:08 +01:00
|
|
|
from reportlab.lib import colors
|
|
|
|
from reportlab.lib.enums import TA_CENTER
|
|
|
|
from reportlab.lib.styles import getSampleStyleSheet
|
|
|
|
from reportlab.lib.units import mm, inch
|
|
|
|
from reportlab.platypus import SimpleDocTemplate, Paragraph, PageBreak, Table
|
2022-11-17 20:33:20 +01:00
|
|
|
from reportlab.pdfbase import pdfmetrics
|
|
|
|
from reportlab.pdfbase.ttfonts import TTFont
|
2022-11-17 14:56:19 +01:00
|
|
|
from werkzeug.datastructures import FileStorage
|
2022-05-17 22:16:45 +02:00
|
|
|
|
|
|
|
from .exceptions import InvalidNameOrTypeHeaderException
|
2022-12-15 22:32:01 +01:00
|
|
|
from ..students.models import Student, Group, ProjectGradeSheet
|
2022-11-17 20:33:20 +01:00
|
|
|
from ..examination_schedule.models import TermOfDefence
|
2022-05-17 22:16:45 +02:00
|
|
|
|
|
|
|
|
2022-05-19 18:15:11 +02:00
|
|
|
def check_columns(df: pd.DataFrame) -> bool:
|
|
|
|
headers = set(df.keys().values)
|
2022-06-12 22:20:10 +02:00
|
|
|
columns = ['NAZWISKO', 'IMIE', 'INDEKS', 'PESEL', 'EMAIL']
|
2022-06-12 21:20:11 +02:00
|
|
|
|
2022-05-19 18:15:11 +02:00
|
|
|
if len(headers - set(columns)) != 0:
|
|
|
|
return False
|
|
|
|
|
2022-05-17 22:16:45 +02:00
|
|
|
flag = True
|
2023-01-04 22:51:58 +01:00
|
|
|
col_types = ['object', 'object', 'int', 'int64', 'object']
|
2022-05-19 18:15:11 +02:00
|
|
|
|
2022-05-17 22:16:45 +02:00
|
|
|
for name, col_type in zip(columns, col_types):
|
2022-05-19 18:15:11 +02:00
|
|
|
if not str(df.dtypes[name]).startswith(col_type):
|
2022-05-17 22:16:45 +02:00
|
|
|
flag = False
|
|
|
|
break
|
|
|
|
|
|
|
|
return flag
|
|
|
|
|
|
|
|
|
2023-01-04 22:51:58 +01:00
|
|
|
def parse_csv(file: Union[FileStorage, TextIO]) -> Generator[Student, Any, None]:
|
2022-06-12 22:20:10 +02:00
|
|
|
df = pd.read_csv(file)
|
2023-01-04 22:51:58 +01:00
|
|
|
# raise Exception(df.to_string())
|
2022-06-13 00:16:07 +02:00
|
|
|
if not check_columns(df):
|
|
|
|
raise InvalidNameOrTypeHeaderException
|
2022-05-17 22:16:45 +02:00
|
|
|
|
2022-06-12 22:20:10 +02:00
|
|
|
students = (Student(last_name=dict(item.items())['NAZWISKO'],
|
|
|
|
first_name=dict(item.items())['IMIE'],
|
|
|
|
index=dict(item.items())['INDEKS'],
|
2022-06-13 00:16:07 +02:00
|
|
|
pesel=str(int(dict(item.items())['PESEL'])) if not pd.isna(
|
|
|
|
dict(item.items())['PESEL']) else None,
|
2022-11-17 14:56:19 +01:00
|
|
|
email=dict(item.items())['EMAIL'])
|
2022-05-19 18:15:11 +02:00
|
|
|
for _, item in df.iterrows())
|
2022-06-12 22:20:10 +02:00
|
|
|
|
2022-05-17 22:16:45 +02:00
|
|
|
return students
|
2022-06-13 00:16:07 +02:00
|
|
|
|
|
|
|
|
2022-11-17 14:56:19 +01:00
|
|
|
def generate_csv(students_and_groups: List[Tuple[Student, Group]]) -> str:
|
2022-06-13 00:16:07 +02:00
|
|
|
headers = ['PESEL', 'INDEKS', 'IMIE', 'NAZWISKO', 'EMAIL', 'CDYD_KOD', 'PRZ_KOD', 'TZAJ_KOD', 'GR_NR', 'PRG_KOD']
|
|
|
|
data = [(student.pesel, student.index, student.first_name, student.last_name, student.email,
|
2022-11-17 14:56:19 +01:00
|
|
|
group.cdyd_kod, group.prz_kod, group.tzaj_kod, group.project_supervisor_id,
|
|
|
|
None) for student, group in students_and_groups]
|
2022-06-13 00:16:07 +02:00
|
|
|
dataframe = defaultdict(list)
|
|
|
|
for row in data:
|
|
|
|
for idx, item in enumerate(row):
|
|
|
|
dataframe[headers[idx]].append(item)
|
|
|
|
|
|
|
|
df = pd.DataFrame(dataframe)
|
|
|
|
return df.to_csv(index=False)
|
2022-11-02 23:21:08 +01:00
|
|
|
|
|
|
|
|
2022-11-17 18:39:45 +01:00
|
|
|
def generate_range_dates(start_date: datetime, end_date: datetime, step_in_minutes: int) -> \
|
|
|
|
Generator[Union[datetime, timedelta], Any, None]:
|
|
|
|
current_date = copy.copy(start_date)
|
|
|
|
while True:
|
|
|
|
next_date = current_date + timedelta(minutes=step_in_minutes)
|
|
|
|
|
|
|
|
if next_date > end_date:
|
|
|
|
break
|
|
|
|
yield current_date
|
|
|
|
current_date = copy.copy(next_date)
|
|
|
|
|
|
|
|
|
2022-11-17 20:33:20 +01:00
|
|
|
def generate_examination_schedule_pdf_file(title: str, nested_term_of_defences: List[List[TermOfDefence]],
|
|
|
|
base_dir: Path) -> bytes:
|
2022-11-02 23:21:08 +01:00
|
|
|
pagesize = (297 * mm, 210 * mm)
|
2022-12-16 01:01:52 +01:00
|
|
|
headers = ["lp.", "Godzina", "Nazwa projektu", "Opiekun", "Zespol", "Komisja", "Uwagi"]
|
2022-11-02 23:21:08 +01:00
|
|
|
pdf_buffer = BytesIO()
|
|
|
|
my_doc = SimpleDocTemplate(
|
|
|
|
pdf_buffer,
|
|
|
|
pagesize=pagesize,
|
|
|
|
topMargin=1 * inch,
|
|
|
|
leftMargin=1 * inch,
|
|
|
|
rightMargin=1 * inch,
|
|
|
|
bottomMargin=1 * inch,
|
|
|
|
title=title
|
|
|
|
)
|
|
|
|
|
2022-11-17 20:33:20 +01:00
|
|
|
pdfmetrics.registerFont(TTFont('Lato', base_dir / 'fonts' / 'Lato.ttf'))
|
2022-11-02 23:21:08 +01:00
|
|
|
style = getSampleStyleSheet()
|
|
|
|
bodyText = style['BodyText']
|
2022-11-17 20:33:20 +01:00
|
|
|
bodyText.fontName = 'Lato'
|
2022-11-02 23:21:08 +01:00
|
|
|
normal = style["Heading1"]
|
|
|
|
normal.alignment = TA_CENTER
|
|
|
|
flowables = []
|
|
|
|
|
|
|
|
# print(nested_enrollments)
|
2022-11-17 20:33:20 +01:00
|
|
|
for term_of_defences in nested_term_of_defences:
|
|
|
|
if len(term_of_defences) == 0:
|
2022-11-02 23:21:08 +01:00
|
|
|
continue
|
2022-11-17 20:33:20 +01:00
|
|
|
date = datetime.strftime(term_of_defences[0].start_date.date(), '%d.%m.%Y')
|
2022-11-02 23:21:08 +01:00
|
|
|
paragraph_1 = Paragraph(f"{title} ~ {date}", normal)
|
|
|
|
flowables.append(paragraph_1)
|
|
|
|
data = [headers]
|
|
|
|
|
2022-11-17 20:33:20 +01:00
|
|
|
for idx, td in enumerate(term_of_defences, start=1):
|
|
|
|
new_date = td.start_date + timedelta(hours=2)
|
|
|
|
group_name = td.group.name if td.group is not None else ""
|
2022-11-02 23:21:08 +01:00
|
|
|
if group_name != '':
|
2022-11-17 20:33:20 +01:00
|
|
|
ps = td.group.project_supervisor
|
2022-11-02 23:21:08 +01:00
|
|
|
project_supervisor_fullname = f"{ps.first_name[0]}. {ps.last_name}"
|
2022-11-17 20:33:20 +01:00
|
|
|
students = td.group.students
|
2022-11-02 23:21:08 +01:00
|
|
|
# print(students)
|
|
|
|
team = ", ".join([f"{s.first_name} {s.last_name}" for s in students])
|
|
|
|
else:
|
|
|
|
project_supervisor_fullname = ""
|
|
|
|
team = ""
|
|
|
|
|
2022-11-17 20:33:20 +01:00
|
|
|
members = td.members_of_committee
|
2022-11-02 23:21:08 +01:00
|
|
|
# print(members)
|
|
|
|
if len(members) == 0:
|
|
|
|
committee = ''
|
|
|
|
else:
|
|
|
|
members_iter = (f"{m.first_name[0]} {m.last_name}" for m in members)
|
|
|
|
committee = ", ".join(members_iter)
|
|
|
|
|
|
|
|
data.append([str(idx), new_date.strftime("%H:%M"),
|
|
|
|
Paragraph(group_name, bodyText),
|
|
|
|
Paragraph(project_supervisor_fullname, bodyText),
|
|
|
|
Paragraph(team, bodyText),
|
|
|
|
Paragraph(committee, bodyText),
|
|
|
|
])
|
|
|
|
# print(data)
|
|
|
|
|
|
|
|
table = Table(data=data,
|
|
|
|
style=[
|
|
|
|
('GRID', (0, 0), (-1, -1), 0.5, colors.black),
|
|
|
|
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor("#A6F1A6")),
|
|
|
|
('BACKGROUND', (0, 0), (1, -1), colors.HexColor("#A6F1A6"))
|
|
|
|
],
|
2022-12-16 01:01:52 +01:00
|
|
|
colWidths=[0.25 * inch, 0.7 * inch, 1.6 * inch, 1.5 * inch, 2.5 * inch, 2.2 * inch, 2 * inch]
|
2022-11-02 23:21:08 +01:00
|
|
|
)
|
|
|
|
flowables.append(table)
|
|
|
|
flowables.append(PageBreak())
|
|
|
|
|
|
|
|
my_doc.build(flowables)
|
|
|
|
pdf_value = pdf_buffer.getvalue()
|
|
|
|
pdf_buffer.close()
|
|
|
|
return pdf_value
|
2022-12-15 22:32:01 +01:00
|
|
|
|
|
|
|
|
|
|
|
def load_weight_for_project_grade_sheet() -> Union[dict, None]:
|
|
|
|
base_dir = current_app.config.get('BASE_DIR')
|
|
|
|
config_dir = base_dir / "config"
|
|
|
|
|
|
|
|
with open(config_dir / "weights_project_grade_sheet.json") as f:
|
|
|
|
data = json.load(f)
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
|
|
def calculate_points_for_one_term(weights: dict, project_grade_sheets: List[ProjectGradeSheet]) -> list:
|
|
|
|
terms = []
|
|
|
|
for pgs in project_grade_sheets:
|
|
|
|
if pgs is None:
|
|
|
|
terms.append((0, 0))
|
|
|
|
continue
|
|
|
|
|
|
|
|
first_term_points = {
|
|
|
|
'nominator': 0,
|
|
|
|
'denominator': 0,
|
|
|
|
}
|
|
|
|
second_term_points = {
|
|
|
|
'nominator': 0,
|
|
|
|
'denominator': 0,
|
|
|
|
}
|
|
|
|
for weight_key, weight_value in weights.items():
|
|
|
|
points = first_term_points if weight_key.endswith('1') else second_term_points
|
|
|
|
try:
|
|
|
|
attribute_value = getattr(pgs, weight_key)
|
|
|
|
except AttributeError:
|
|
|
|
attribute_value = 0
|
|
|
|
points['nominator'] += attribute_value * weight_value * 1 / 4
|
|
|
|
points['denominator'] += weight_value
|
|
|
|
|
|
|
|
try:
|
|
|
|
fp = first_term_points['nominator'] / first_term_points['denominator']
|
|
|
|
except ZeroDivisionError:
|
|
|
|
fp = 0
|
|
|
|
try:
|
|
|
|
sp = second_term_points['nominator'] / second_term_points['denominator']
|
|
|
|
except ZeroDivisionError:
|
|
|
|
sp = 0
|
|
|
|
|
2023-01-04 22:51:58 +01:00
|
|
|
terms.append((round(fp, 2) * 100, round(sp, 2) * 100))
|
2022-12-15 22:32:01 +01:00
|
|
|
|
|
|
|
return terms
|