Stilforbedringer+

This commit is contained in:
Trygve 2022-06-27 14:26:32 +02:00
parent d3c6b6977a
commit 38cc7c7672

281
otime.py
View File

@ -10,49 +10,19 @@ from fpdf import FPDF
# The event object stores all the event data.
# A .otime file is more or less just a json dump of the Event object.
class Event:
def __init__(self, eventid, name, **kwargs):
def __init__(self, eventid, name, start_time=None, end_time=None,
organiser=None, courses=[], o_classes=[], runners=[],
card_dumps=[], fees=[]):
self.id = eventid
self.name = name
try:
self.start_time = kwargs['start_time']
except KeyError:
self.start_time = None
try:
self.end_time = kwargs['end_time']
except KeyError:
self.end_time = None
try:
self.organiser = kwargs['organiser']
except KeyError:
self.organiser = None
try:
self.courses = kwargs['courses']
except KeyError:
self.courses = []
try:
self.o_classes = kwargs['o_classes']
except KeyError:
self.o_classes = []
try:
self.runners = kwargs['runners']
except KeyError:
self.runners = []
try:
self.card_dumps = kwargs['card_dumps']
except KeyError:
self.card_dumps = []
try:
self.fees = kwargs['fees']
except KeyError:
self.fees = []
self.start_time = start_time
self.end_time = end_time
self.organiser = organiser
self.courses = courses
self.o_classes = o_classes
self.runners = runners
self.card_dumps = card_dumps
self.fees = fees
def add_course(self, *args):
for n in args:
@ -78,17 +48,18 @@ class Event:
tree = ET.parse(xml_file)
root = tree.getroot()
event_el = root.find('./{http://www.orienteering.org/datastandard/3.0}Event')
event_id = int(event_el.find('./{http://www.orienteering.org/datastandard/3.0}Id').text)
name = event_el.find('./{http://www.orienteering.org/datastandard/3.0}Name').text
organiser = event_el.find('./{http://www.orienteering.org/datastandard/3.0}Organiser/{http://www.orienteering.org/datastandard/3.0}Name').text
url = '{http://www.orienteering.org/datastandard/3.0}'
event_el = root.find(f'./{url}Event')
event_id = int(event_el.find(f'./{url}Id').text)
name = event_el.find(f'./{url}Name').text
organiser = event_el.find(f'./{url}Organiser/{url}Name').text
start_ds = event_el.find('./{http://www.orienteering.org/datastandard/3.0}StartTime/{http://www.orienteering.org/datastandard/3.0}Date').text
start_ts = event_el.find('./{http://www.orienteering.org/datastandard/3.0}StartTime/{http://www.orienteering.org/datastandard/3.0}Time').text[:-1]
start_ds = event_el.find(f'./{url}StartTime/{url}Date').text
start_ts = event_el.find(f'./{url}StartTime/{url}Time').text[:-1]
start_time = datetime.datetime.fromisoformat(f'{start_ds}T{start_ts}')
end_ds = event_el.find('./{http://www.orienteering.org/datastandard/3.0}EndTime/{http://www.orienteering.org/datastandard/3.0}Date').text
end_ts = event_el.find('./{http://www.orienteering.org/datastandard/3.0}EndTime/{http://www.orienteering.org/datastandard/3.0}Time').text[:-1]
end_ds = event_el.find(f'./{url}EndTime/{url}Date').text
end_ts = event_el.find(f'./{url}EndTime/{url}Time').text[:-1]
end_time = datetime.datetime.fromisoformat(f'{end_ds}T{end_ts}')
runners = runners_from_xml_entries(xml_file)
@ -119,6 +90,7 @@ class Event:
for d in self.card_dumps:
if r.card == d.card:
r.card_r = d
def match_runners_o_classes(self):
for r in self.runners:
for c in self.o_classes:
@ -136,6 +108,7 @@ class Event:
for f in self.fees:
if r.fee_id == f.id:
r.fee = f
def match_all(self):
self.match_runners_cards()
self.match_runners_o_classes()
@ -214,13 +187,10 @@ class Event:
# </SplitTime>
elif n.status() == 'Disqualified':
xml_child(result, 'Status', n.status())
controls = copy(n.card_r.controls)
splits = copy(n.card_r.splits)
for code, split in zip(n.res_codes(), n.res_splits()):
st = ET.SubElement(result, 'SplitTime')
xml_child(st, 'ControlCode', code)
if split != None:
if split is not None:
xml_child(st, 'Time', split)
else:
xml_child(result, 'Status', n.status())
@ -256,6 +226,9 @@ class Event:
json_data = {
'id': self.id,
'name': self.name,
'orginser': self.organiser,
'start_time': self.start_time.isoformat(),
'end_time': self.end_time.isoformat(),
'runners': rdicts,
'courses': cdicts,
'o_classes': ocdicts,
@ -269,11 +242,15 @@ class Event:
data = json.load(f)
runners = []
for r in data['runners']:
runners.append(Runner(r['id'], r['first'], r['last'], club_id=r['club_id'], club=r['club'], country=r['country'], card=r['card'], o_class_str=r['o_class_str'], fork=r['fork'],start_time=r['start_time']))
runners.append(Runner(r['id'], r['first'], r['last'], club_id=r['club_id'],
club=r['club'], country=r['country'], card=r['card'],
o_class_str=r['o_class_str'], fork=r['fork'],
start_time=r['start_time'], fee_id=int(r['fee_id'])))
courses = []
for c in data['courses']:
courses.append(Course(c['name'], c['codes'], forked=c['forked'], variations=c['variations']))
courses.append(Course(c['name'], c['codes'], forked=c['forked'],
variations=c['variations']))
o_classes = []
for c in data['o_classes']:
@ -281,13 +258,22 @@ class Event:
card_dumps = []
for d in data['card_dumps']:
card_dumps.append(CardDump(d['card'], d['controls'], d['splits'], datetime.datetime.fromisoformat(d['read_time']), datetime.datetime.fromisoformat(d['s_time']), datetime.datetime.fromisoformat(d['f_time'])))
card_dumps.append(CardDump(d['card'], d['controls'], d['splits'],
datetime.datetime.fromisoformat(d['read_time']),
datetime.datetime.fromisoformat(d['s_time']),
datetime.datetime.fromisoformat(d['f_time'])))
fees = []
for f in data['fees']:
fees.append(Fee(f['id'], f['name'], f['currency'], f['amount'], from_birth_date=f['from_birth_date'], to_birth_date=f['to_birth_date']))
fees.append(Fee(f['id'], f['name'], f['currency'], f['amount'],
from_birth_date=f['from_birth_date'],
to_birth_date=f['to_birth_date']))
return Event(data['id'], data['name'], runners=runners, courses=courses, o_classes=o_classes, card_dumps=card_dumps)
return Event(data['id'], data['name'], organiser=data['orginiser'],
start_time=datetime.datetime.fromisoformat(data['start_time']),
end_time=datetime.datetime.fromisoformat(data['end_time']),
runners=runners, courses=courses, o_classes=o_classes,
card_dumps=card_dumps, fees=fees)
def create_start_list_pdf(self, file_name):
pdf = FPDF()
@ -300,7 +286,7 @@ class Event:
pdf.multi_cell(col_width, line_height, runner.fullname(), border=1, ln=3, max_line_height=pdf.font_size, align='L')
pdf.multi_cell(col_width, line_height, runner.o_class_str, border=1, ln=3, max_line_height=pdf.font_size)
pdf.multi_cell(col_width, line_height, str(runner.card), border=1, ln=3, max_line_height=pdf.font_size)
if runner.start_time != None:
if runner.start_time is not None:
pdf.multi_cell(col_width, line_height, str(runner.start_time), border=1, ln=3, max_line_height=pdf.font_size)
else:
pdf.multi_cell(col_width, line_height, '', border=1, ln=3, max_line_height=pdf.font_size)
@ -308,7 +294,7 @@ class Event:
pdf.output(file_name)
def create_all_invoices(self, filename_prefix):
clubs = [x.club for x in self.runners if x.club != self.runners[self.runners.index(x)-1].club]
clubs = [x.club for x in self.runners if x.club != self.runners[self.runners.index(x)-1].club and x.club is not None]
for club in clubs:
self.create_club_invoice(club, filename_prefix + club + '.pdf')
@ -318,7 +304,6 @@ class Event:
payments = [x.fee.amount for x in runners_ic]
subtotal = sum(payments)
# Dict of runners in each fee
fee_dict = {}
for fee in self.fees:
@ -333,7 +318,6 @@ class Event:
pdf.set_creator('oTime 0.0.1')
pdf.set_creation_date()
pdf.add_page()
pdf.add_font("LiberationSans", fname="data/fonts/LiberationSans-Regular.ttf")
pdf.add_font("LiberationSans-Bold", fname="data/fonts/LiberationSans-Bold.ttf")
@ -396,7 +380,7 @@ class Event:
pdf.set_font("LiberationSans", size=10)
# Tabell
line_height = pdf.font_size * 2
col_width = pdf.epw / 9 # distribute content evenly
col_width = pdf.epw / 8 # distribute content evenly
# Top row
pdf.set_fill_color(191, 191, 191)
pdf.set_draw_color(191, 191, 191)
@ -405,7 +389,7 @@ class Event:
pdf.multi_cell(col_width*2, line_height, 'Navn', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Klasse', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Brikke', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Starttid', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True)
# pdf.multi_cell(col_width, line_height, 'Starttid', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Resultat', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Plass', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
pdf.multi_cell(col_width, line_height, 'Kontigent', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
@ -423,10 +407,10 @@ class Event:
pdf.multi_cell(col_width, line_height, runner.o_class_str, ln=3, max_line_height=pdf.font_size, align='L') # Class
pdf.multi_cell(col_width, line_height, str(runner.card), ln=3, max_line_height=pdf.font_size) # card
# Starttime:
if runner.start_time != None:
pdf.multi_cell(col_width, line_height, str(runner.start_time), ln=3, max_line_height=pdf.font_size)
else:
pdf.multi_cell(col_width, line_height, 'Fristart', ln=3, max_line_height=pdf.font_size)
#if runner.start_time != None:
# pdf.multi_cell(col_width, line_height, str(runner.start_time), ln=3, max_line_height=pdf.font_size)
#else:
# pdf.multi_cell(col_width, line_height, 'Fristart', ln=3, max_line_height=pdf.font_size)
# Time used:
if runner.status() == 'OK':
pdf.multi_cell(col_width, line_height, str(datetime.timedelta(seconds=runner.totaltime())), ln=3, max_line_height=pdf.font_size)
@ -450,7 +434,7 @@ class Event:
# sum
pdf.set_font("LiberationSans-Bold", size=10)
pdf.set_x(col_width*8)
pdf.multi_cell(0, line_height, 'Sum ' + str(subtotal), border='TB', ln=3, max_line_height=pdf.font_size, align='R')
pdf.cell(0, line_height, 'Sum ' + str(subtotal), border='TB', align='R')
pdf.set_font("LiberationSans", size=10)
line_height = pdf.font_size * 1.5
@ -486,63 +470,22 @@ class PDF(FPDF):
# The runner object stores all the data specific to a runner.
class Runner:
def __init__(self, runner_id, first, last, **kwargs):
def __init__(self, runner_id, first, last, club=None, club_id=None,
country=None, card=None, o_class_str=None, o_class=None,
fork=0, start_time=None, fee_id=None, fee=None):
self.id = runner_id
self.first = first
self.last = last
try:
self.club = kwargs['club']
except KeyError:
self.club = None
try:
self.club_id = kwargs['club_id']
except KeyError:
self.club_id = None
try:
self.country = kwargs['country']
except KeyError:
self.country = None
try:
self.card = kwargs['card']
except KeyError:
self.card = 0
try:
self.o_class_str = kwargs['o_class_str']
except KeyError:
self.o_class = None
try:
self.o_class = kwargs['o_class']
except KeyError:
self.o_class = None
try:
self.fork = kwargs['fork']
except KeyError:
self.fork = 0
try:
self.start_time = kwargs['start_time']
except KeyError:
self.start_time = None
try:
self.fee_id = kwargs['fee_id']
except KeyError:
self.fee_id = None
try:
self.fee = kwargs['fee']
self.fee_id = kwargs['fee'].id
except KeyError:
self.fee = None
#self.o_class = o_class
#self.start_time = start_time
self.club = club
self.club_id = club_id
self.country = country
self.card = card
self.o_class_str = o_class_str
self.o_class = o_class
self.fork = fork
self.start_time = start_time
self.fee_id = fee_id
self.fee = fee
def from_string(tt_line, o_classes):
#https://web.archive.org/web/20191229124046/http://wiki.ttime.no/index.php/Developer
@ -605,11 +548,11 @@ class Runner:
return 0
def status(self):
if hasattr(self, 'card_r') == False or self.o_class == None:
if hasattr(self, 'card_r') is False or self.o_class is None:
return 'Active'
elif self.check_codes():
return 'OK'
elif self.check_codes() == False:
elif self.check_codes() is False:
return 'Disqualified'
# TODO: må forbedres
@ -621,7 +564,7 @@ class Runner:
return None
def res_codes(self):
if self.o_class.course.forked == False:
if self.o_class.course.forked is False:
return self.o_class.course.codes
else:
return self.o_class.course.variations[self.fork]
@ -672,6 +615,7 @@ class Runner:
'fee_id': self.fee_id
}
class CardDump:
def __init__(self, card, controls, splits, read_time, s_time, f_time):
self.card = card
@ -780,19 +724,11 @@ class CardDump:
# Stored in Event.courses
class Course:
def __init__(self, name, codes, **kwargs):
def __init__(self, name, codes, forked=False, variations=None):
self.name = name
self.codes = codes
try:
self.forked = kwargs['forked']
except KeyError:
self.forked = False
try:
self.variations = kwargs['variations']
except KeyError:
self.variations = None
self.forked = forked
self.variations = variations
def __repr__(self):
return f'name({self.name})'
@ -822,21 +758,14 @@ class OClass:
}
class Fee:
def __init__(self, fee_id, name, currency, amount, **kwargs):
def __init__(self, fee_id, name, currency, amount, from_birth_date=None,
to_birth_date=None):
self.id = fee_id
self.name = name
self.currency = currency
self.amount = amount
try:
self.from_birth_date = kwargs['from_birth_date']
except KeyError:
self.from_birth_date = None
try:
self.to_birth_date = kwargs['to_birth_date']
except KeyError:
self.to_birth_date = None
self.from_birth_date = from_birth_date
self.to_birth_date = to_birth_date
def asdict(self):
return {
@ -880,34 +809,35 @@ def classes_from_ttime_conf(ttime_file, courses):
def runners_from_xml_entries(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
runners = []
person_entries = root.findall('./{http://www.orienteering.org/datastandard/3.0}PersonEntry')
url = '{http://www.orienteering.org/datastandard/3.0}'
runners = []
person_entries = root.findall(f'./{url}PersonEntry')
for p_entry in person_entries:
rid = p_entry[1][0].text
person = p_entry.find('./{http://www.orienteering.org/datastandard/3.0}Person')
name = person.find('./{http://www.orienteering.org/datastandard/3.0}Name')
first = name.find('./{http://www.orienteering.org/datastandard/3.0}Given').text
last = name.find('./{http://www.orienteering.org/datastandard/3.0}Family').text
person = p_entry.find(f'./{url}Person')
name = person.find(f'./{url}Name')
first = name.find(f'./{url}Given').text
last = name.find(f'./{url}Family').text
organisation = p_entry.find('./{http://www.orienteering.org/datastandard/3.0}Organisation')
organisation = p_entry.find(f'./{url}Organisation')
if organisation is not None:
club_id = organisation.find('./{http://www.orienteering.org/datastandard/3.0}Id').text
club_name = organisation.find('./{http://www.orienteering.org/datastandard/3.0}Name').text
club_name_short = organisation.find('./{http://www.orienteering.org/datastandard/3.0}ShortName').text
country = organisation.find('./{http://www.orienteering.org/datastandard/3.0}Country').attrib['code']
club_id = organisation.find(f'./{url}Id').text
club_name = organisation.find(f'./{url}Name').text
club_name_short = organisation.find(f'./{url}ShortName').text
country = organisation.find(f'./{url}Country').attrib['code']
else:
club_id = club_name = club_name_short = country = None
class_el = p_entry.find('./{http://www.orienteering.org/datastandard/3.0}Class')
class_str = class_el.find('./{http://www.orienteering.org/datastandard/3.0}Name').text
class_el = p_entry.find(f'./{url}Class')
class_str = class_el.find(f'./{url}Name').text
fee_id = int(p_entry.find('./{http://www.orienteering.org/datastandard/3.0}AssignedFee/{http://www.orienteering.org/datastandard/3.0}Fee/{http://www.orienteering.org/datastandard/3.0}Id').text)
fee_id = int(p_entry.find(f'./{url}AssignedFee/{url}Fee/{url}Id').text)
try:
card = int(p_entry.find('./{http://www.orienteering.org/datastandard/3.0}ControlCard').text)
card = int(p_entry.find(f'./{url}ControlCard').text)
except AttributeError:
card = None
@ -917,34 +847,38 @@ def runners_from_xml_entries(xml_file):
start_time=start_time, fee_id=fee_id))
return runners
def fees_from_xml_entries(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
allfees = root.findall('.//{http://www.orienteering.org/datastandard/3.0}Fee')
url = '{http://www.orienteering.org/datastandard/3.0}'
allfees = root.findall(f'.//{url}Fee')
added_ids = []
fee_objs = []
for fee in allfees:
f_id = int(fee.find('./{http://www.orienteering.org/datastandard/3.0}Id').text)
f_id = int(fee.find(f'./{url}Id').text)
if f_id not in added_ids:
added_ids.append(f_id)
fee_id = f_id
name = fee.find('./{http://www.orienteering.org/datastandard/3.0}Name').text
currency = fee.find('./{http://www.orienteering.org/datastandard/3.0}Amount').attrib['currency']
amount = int(fee.find('./{http://www.orienteering.org/datastandard/3.0}Amount').text)
name = fee.find(f'./{url}Name').text
currency = fee.find(f'./{url}Amount').attrib['currency']
amount = int(fee.find(f'./{url}Amount').text)
try:
from_birth_date = fee.find('./{http://www.orienteering.org/datastandard/3.0}FromDateOfBirth').text
from_birth_date = fee.find(f'./{url}FromDateOfBirth').text
except AttributeError:
from_birth_date = None
try:
to_birth_date = fee.find('./{http://www.orienteering.org/datastandard/3.0}ToDateOfBirth').text
to_birth_date = fee.find(f'./{url}ToDateOfBirth').text
except AttributeError:
to_birth_date = None
fee_objs.append(Fee(fee_id, name, currency, amount, from_birth_date=from_birth_date, to_birth_date=to_birth_date))
fee_objs.append(Fee(fee_id, name, currency, amount,
from_birth_date=from_birth_date, to_birth_date=to_birth_date))
return fee_objs
# Checks if small list is in big list
def contains(small, big):
valid = True
@ -963,15 +897,16 @@ def contains(small, big):
else:
return False
def get_runners_in_class(runners, o_class):
# Filters out runner objects that dont have the correct o_class
list_filtrd = []
for i in runners:
marker = 0
if i.o_class == o_class:
list_filtrd.append(i)
return list_filtrd
def rank_runners(allrunners, o_class):
runners = get_runners_in_class(allrunners, o_class)
runners_ranked = []
@ -981,8 +916,8 @@ def rank_runners(allrunners, o_class):
runners_ranked.sort(key=lambda x: x.totaltime())
return runners_ranked
# Used to make creating xml files easier
def xml_child(parent, tag, content):
e = ET.SubElement(parent, tag)
e.text = str(content)