Skip to content

Commit

Permalink
ProvideOutputFile contextmamager and linter satiyfication
Browse files Browse the repository at this point in the history
  • Loading branch information
MitchiLaser committed Sep 4, 2023
1 parent cf51699 commit beb4247
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 106 deletions.
25 changes: 3 additions & 22 deletions src/timeforge/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ def main():
import tempfile
from . import helpers
from . import config
from . import core

#########################################

Expand Down Expand Up @@ -142,30 +143,10 @@ def main():

#########################################

with tempfile.TemporaryFile() as temp:

# download online form and store it in a temp file
try:
r: requests.Response = requests.get(config.MILOG_FORM_URL, allow_redirects=True)
except Exception as e:
print(f"Exception when downloading PSE-Hiwi Formular -> {e}\n")
sys.exit(os.EX_UNAVAILABLE)

temp.write(r.content)
temp.seek(0) # move cursor back to the beginning of the file

pdf_reader = PdfReader(temp)
pdf_writer = PdfWriter(clone_from=pdf_reader) # to copy everything else pdf_writer= PdfWriter();pdf_writer.append(pdf_reader)

fields = pdf_reader.get_form_text_fields() # get the field names from the form in the pdf
with core.ProvideOutputFile(args.output) as (WriteInPDF, fields):
for field in fields: # fill out all the fields in the form
if field in form_data:
pdf_writer.update_page_form_field_values(pdf_writer.pages[0], {field: form_data[field]})

#########################################

with open(args.output, 'wb') as output_file: # write file
pdf_writer.write(output_file)
WriteInPDF.update_page_form_field_values(WriteInPDF.pages[0], {field: form_data[field]})


if __name__ == "__main__":
Expand Down
37 changes: 37 additions & 0 deletions src/timeforge/core.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-

from contextlib import contextmanager
import os
from pypdf import PdfReader, PdfWriter
import requests
import sys
import tempfile
from . import config


@contextmanager
def ProvideOutputFile(output_file: str):
# store the online PDF in a temporary file which will automatically be deleted when this contextmanager will be left
with tempfile.TemporaryFile() as temp:

# download online form and store it in a temp file
try:
r: requests.Response = requests.get(config.MILOG_FORM_URL, allow_redirects=True)
except Exception as e:
print(f"Exception when downloading PSE-Hiwi Formular -> {e}\n")
sys.exit(os.EX_UNAVAILABLE)

temp.write(r.content)
temp.seek(0) # move cursor back to the beginning of the file

pdf_reader = PdfReader(temp)
pdf_writer = PdfWriter(clone_from=pdf_reader) # to copy everything else pdf_writer= PdfWriter();pdf_writer.append(pdf_reader)

fields = pdf_reader.get_form_text_fields() # get the field names from the form in the pdf

try:
yield pdf_writer, fields
finally:
with open(output_file, 'wb') as output_file: # write file
pdf_writer.write(output_file)
24 changes: 3 additions & 21 deletions src/timeforge/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from . import text_input
from . import helpers
from . import config
from . import core


class tui:
Expand All @@ -47,7 +48,6 @@ def __init__(self):
self.validate_content()
self.create_pdf_content()
# TODO: Create the dialog for the storage location
self.write_file()
# TODO: Add further function calls here
except curses.error as e:
self.reverse()
Expand Down Expand Up @@ -367,28 +367,10 @@ def create_pdf_content(self):
self.form_data["hhmmRow" + str(table_row) + "_4"] = day.work_hours.strftime("%H:%M")
table_row += 1

def write_file(self):

with tempfile.TemporaryFile() as temp:
# download online form and store it in a temp file
try:
r: requests.Response = requests.get(config.MILOG_FORM_URL, allow_redirects=True)
except Exception as e:
raise Exception(f"Exception when downloading PSE-Hiwi Formular -> {e}\n")

temp.write(r.content)
temp.seek(0) # move cursor back to the beginning of the file

pdf_reader = PdfReader(temp)
pdf_writer = PdfWriter(clone_from=pdf_reader) # to copy everything else pdf_writer= PdfWriter();pdf_writer.append(pdf_reader)

fields = pdf_reader.get_form_text_fields() # get the field names from the form in the pdf
with core.ProvideOutputFile(str(os.path.expanduser('~')) + "/out.pdf") as (WriteInPDF, fields):
for field in fields: # fill out all the fields in the form
if field in self.form_data:
pdf_writer.update_page_form_field_values(pdf_writer.pages[0], {field: self.form_data[field]})

with open(str(os.path.expanduser('~')) + "/out.pdf", 'wb') as output_file: # write file
pdf_writer.write(output_file)
WriteInPDF.update_page_form_field_values(WriteInPDF.pages[0], {field: self.form_data[field]})


def main():
Expand Down
64 changes: 32 additions & 32 deletions src/timeforge/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,78 +14,79 @@
# a class to store every row in the table (=every single working day) in an internal data structure
class Day:
def __init__(self, job, date, start_time, end_time, pause, work_hours):
self.job = job # Job description
self.date = date # the date of the day
self.start_time = self.time_from_h(start_time) # working start time
self.end_time = self.time_from_h(end_time) # working end time
self.work_hours = self.time_from_h(work_hours) # total working hours per day
self.pause = self.time_from_h(pause) # total pause hours per day
self.job = job # Job description
self.date = date # the date of the day
self.start_time = self.time_from_h(start_time) # working start time
self.end_time = self.time_from_h(end_time) # working end time
self.work_hours = self.time_from_h(work_hours) # total working hours per day
self.pause = self.time_from_h(pause) # total pause hours per day

def __lt__(self, other):
return self.date < other.date

def time_from_h(self, hours):
return time(hour= int(hours), minute= int(hours * 60 % 60))
return time(hour=int(hours), minute=int(hours * 60 % 60))

# a class to store the whole content of the table (=a month) internally


class Month_Dataset:
def __init__(self, year, month, total_work_hours, job, feiertage):
# values which define the working times
self.min_timeblock = 2 # the minimal amount of working time per day
self.max_timeblock = 4 # the maximum of working time at once (there might be longer blocks but then they have brakes in between
self.min_pause = 2 # minimal amount of pause time if the working time is greater than self.max_timeblock
self.max_pause = 3 # maximal amount of pause per day
self.min_timeblock = 2 # the minimal amount of working time per day
self.max_timeblock = 4 # the maximum of working time at once (there might be longer blocks but then they have brakes in between
self.min_pause = 2 # minimal amount of pause time if the working time is greater than self.max_timeblock
self.max_pause = 3 # maximal amount of pause per day
self.min_start_time = 8 # earliest time to start the day
self.max_start_time = 23 - 2 * self.max_timeblock - self.max_pause # latest time to end the day # TODO: Comment why this is calculated that way

self.feiertage = feiertage

self.month = month
self.year = year
self.total_work_hours = total_work_hours
self.days = []
self.timeblocks = self.make_timeblocks(self.total_work_hours) # TODO: put this function call return value directly into the function call one line below
# TODO: put this function call return value directly into the function call one line below
self.timeblocks = self.make_timeblocks(self.total_work_hours)
self.generate_content(job) # fill the table with content


def make_timeblocks(self, work_hours_left):
# Create an array with random time blocks which in sum fill the whole working time for a month
timeblock_array = []
while work_hours_left > 0:
timeblock_length = random.randint(self.min_timeblock, self.max_timeblock) # TODO: Check weather the call of the random function is done properly
# TODO: Check weather the call of the random function is done properly
timeblock_length = random.randint(self.min_timeblock, self.max_timeblock)
if work_hours_left - timeblock_length < 0:
timeblock_length = work_hours_left

timeblock_array.append(timeblock_length)
work_hours_left -= timeblock_length
return timeblock_array


def add_work(self, job, date, start_time, end_time, pause, work_hours):
self.days.append(Day(job, date, start_time, end_time, pause, work_hours))


def year_is_leap_year(year) -> bool:
if ((year%4 == 0 and year % 100 != 0) or year%400==0):
if ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):
return True
return False
def days_of_month(self,month:int,year:int) -> int:

def days_of_month(self, month: int, year: int) -> int:
if month == 2 and self.year_is_leap_year(year):
return 29
number_of_days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
number_of_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return number_of_days_in_month[month-1]

def generate_content(self, job):

def suggest_day_of_month():
while True:
day = random.randint(1,self.days_of_month(self.month,self.year)) # random day from the 1st to the last day of the month
day = random.randint(1, self.days_of_month(self.month, self.year)) # random day from the 1st to the last day of the month
d = date(self.year, self.month, day)
if d.weekday() <= 4 and not d in self.feiertage:
return d

#brakes will be added randomly. At 20h of total working time per day two hours of work have to be done to fit everything into the table
# brakes will be added randomly. At 20h of total working time per day two hours of work have to be done to fit everything into the table
if self.total_work_hours < 20:
p_2blocks = 0.3
else:
Expand All @@ -99,16 +100,15 @@ def suggest_day_of_month():
if not d in dates:
dates.append(d)
timeblocks_left -= 1
work_time = self.timeblocks.pop() # get latest entry of timeblock list
start_time = random.randint( self.min_start_time, self.max_start_time ) # generate random time to start the day
work_time = self.timeblocks.pop() # get latest entry of timeblock list
start_time = random.randint(self.min_start_time, self.max_start_time) # generate random time to start the day
pause = 0

# add a random break and a second working block
if p_2blocks >= random.uniform(0,1) and timeblocks_left > 0:
if p_2blocks >= random.uniform(0, 1) and timeblocks_left > 0:
timeblocks_left -= 1
pause = random.randint( self.min_pause, self.max_pause )
pause = random.randint(self.min_pause, self.max_pause)
work_time += self.timeblocks.pop()

end_time = start_time + work_time + pause
self.add_work(job, d, start_time, end_time, pause, work_time)

Loading

0 comments on commit beb4247

Please sign in to comment.