otime/otime.py

939 lines
36 KiB
Python
Raw Normal View History

2022-05-30 14:25:49 +00:00
from copy import copy
2022-02-06 00:12:32 +00:00
import datetime
import csv
import re
import json
import io
2022-02-06 00:12:32 +00:00
import xml.etree.ElementTree as ET
# from fpdf import FPDF
2022-05-11 13:07:33 +00:00
# The event object stores all the event data.
# A .otime file is more or less just a json dump of the Event object.
2022-05-11 13:07:33 +00:00
class Event:
2022-06-27 12:26:32 +00:00
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
2022-06-27 12:26:32 +00:00
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:
self.courses.append(n)
def add_o_class(self, *args):
for n in args:
self.o_classes.append(n)
def add_runners(self, *args):
for n in args:
self.runners.append(n)
2022-05-11 13:07:33 +00:00
def add_fees(self, *args):
for n in args:
self.fees.append(n)
def import_xml_entries(self, xml_file):
self.add_runners(*runners_from_xml_entries(xml_file))
self.add_fees(*fees_from_xml_entries(xml_file))
2022-06-01 21:28:22 +00:00
def from_xml_entries(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
2022-06-27 12:26:32 +00:00
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
2022-06-01 21:28:22 +00:00
2022-06-27 12:26:32 +00:00
start_ds = event_el.find(f'./{url}StartTime/{url}Date').text
start_ts = event_el.find(f'./{url}StartTime/{url}Time').text[:-1]
2022-06-01 21:28:22 +00:00
start_time = datetime.datetime.fromisoformat(f'{start_ds}T{start_ts}')
2022-06-27 12:26:32 +00:00
end_ds = event_el.find(f'./{url}EndTime/{url}Date').text
end_ts = event_el.find(f'./{url}EndTime/{url}Time').text[:-1]
2022-06-01 21:28:22 +00:00
end_time = datetime.datetime.fromisoformat(f'{end_ds}T{end_ts}')
runners = runners_from_xml_entries(xml_file)
fees = fees_from_xml_entries(xml_file)
return Event(event_id, name, organiser=organiser, runners=runners,
2022-06-27 12:26:32 +00:00
fees=fees, start_time=start_time, end_time=end_time)
2022-06-01 21:28:22 +00:00
def import_ttime_cnf(self, ttime_file):
self.add_course(*courses_from_ttime_conf(ttime_file))
if isinstance(ttime_file, io.TextIOBase):
ttime_file.seek(0)
self.add_o_class(*classes_from_ttime_conf(ttime_file, self.courses))
def import_ttime_db(self, ttime_file):
if type(ttime_file) == str:
f_list = ttime_file.splitlines()
elif isinstance(ttime_file, io.TextIOBase):
csvreader = csv.reader(ttime_file, delimiter=';',)
2022-03-11 14:31:20 +00:00
runnerarray = []
for row in f_list:
if len(row) == 0 or row[1] == '':
2022-03-11 14:31:20 +00:00
continue
2022-05-11 13:07:33 +00:00
runnerarray.append(Runner.from_string(row, self.o_classes))
2022-03-11 14:31:20 +00:00
self.runners = runnerarray
2022-05-11 13:07:33 +00:00
def import_mtr_file(self, mtr_file):
2022-05-21 14:25:50 +00:00
self.card_dumps = CardDump.list_from_mtr_f(mtr_file)
2022-05-11 13:07:33 +00:00
2022-03-03 14:39:59 +00:00
def match_runners_cards(self):
for r in self.runners:
for d in self.card_dumps:
if r.card == d.card:
r.card_r = d
2022-06-27 12:26:32 +00:00
def match_runners_o_classes(self):
for r in self.runners:
for c in self.o_classes:
if r.o_class_str == c.name:
r.o_class = c
def match_o_classes_courses(self):
for oc in self.o_classes:
for c in self.courses:
if oc.course_str == c.name:
oc.course = c
2022-06-01 15:42:55 +00:00
def match_runners_fees(self):
for r in self.runners:
for f in self.fees:
if r.fee_id == f.id:
r.fee = f
2022-06-27 12:26:32 +00:00
def match_all(self):
self.match_runners_cards()
self.match_runners_o_classes()
self.match_o_classes_courses()
2022-06-01 15:42:55 +00:00
self.match_runners_fees()
def get_xml_res(self):
root = ET.Element('ResultList')
root.set('xmlns', 'http://www.orienteering.org/datastandard/3.0')
root.set('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
root.set('iofVersion', '3.0')
root.set('createTime', datetime.datetime.now().isoformat(timespec='seconds'))
root.set('creator', 'oTime')
root.set('status', 'Complete')
tree = ET.ElementTree(root)
event = ET.SubElement(root, 'Event')
xml_child(event, 'Id', self.id)
xml_child(event, 'Name', self.name)
for i in self.o_classes:
print('Hmmmmmm')
2022-05-11 13:07:33 +00:00
# <ClassResult>
class_result = ET.SubElement(root, 'ClassResult')
2022-05-11 13:07:33 +00:00
# <Class>
t = ET.SubElement(class_result, 'Class')
xml_child(t, 'Name', i.name)
2022-05-11 13:07:33 +00:00
# <PersonResult>
runners_same_c = get_runners_in_class(self.runners, i)
runners_ranked = rank_runners(runners_same_c, i)
# Put the OK runners first and Active last
runners_sorted = [i for i in runners_same_c if i not in runners_ranked]
runners_ranked.extend(runners_sorted)
for n in runners_ranked:
2022-05-30 14:25:49 +00:00
if n.status() == 'Active':
continue
person_result = ET.SubElement(class_result, 'PersonResult')
2022-05-11 13:07:33 +00:00
# <Person>
person = ET.SubElement(person_result, 'Person')
xml_child(person, 'Id', n.id)
2022-05-11 13:07:33 +00:00
# <Name>
name = ET.SubElement(person, 'Name')
xml_child(name, 'Family', n.last)
xml_child(name, 'Given', n.first)
2022-05-11 13:07:33 +00:00
# </Name>
# </Person>
# <Organisation>
org = ET.SubElement(person_result, 'Organisation')
2022-05-21 14:25:50 +00:00
xml_child(org, 'Id', n.club_id)
xml_child(org, 'Name', n.club)
country = ET.SubElement(org, 'Country')
# TODO: hent land fra løperobjektet
country.text = 'Norway'
country.set('code', 'NOR')
2022-05-11 13:07:33 +00:00
# </Organisation>
# <Result>
result = ET.SubElement(person_result, 'Result')
# TODO: Dette bør skrives om til å bruke Runner metoder så mye som mulig.
2022-05-11 13:07:33 +00:00
if hasattr(n, 'card_r') and len(n.card_r.splits) > 2:
xml_child(result, 'StartTime', n.card_r.s_time.isoformat())
xml_child(result, 'FinishTime', n.card_r.f_time.isoformat())
xml_child(result, 'Time', n.totaltime())
if n.status() == 'OK':
2022-05-11 13:07:33 +00:00
# <TimeBehind>
xml_child(result, 'TimeBehind', n.totaltime() - runners_ranked[0].totaltime())
2022-05-11 13:07:33 +00:00
# </TimeBehind>
xml_child(result, 'Position', n.rank(self.runners))
xml_child(result, 'Status', n.status())
2022-05-11 13:07:33 +00:00
# <SplitTime>
# TODO: ta utgangspunkt i løypa, ikke det brikka har stempla
for code, split in zip(n.card_r.controls, n.card_r.splits):
st = ET.SubElement(result, 'SplitTime')
xml_child(st, 'ControlCode', code)
xml_child(st, 'Time', split)
2022-05-30 14:25:49 +00:00
if code == n.res_codes()[-1]:
break
2022-05-11 13:07:33 +00:00
# </SplitTime>
elif n.status() == 'Disqualified':
xml_child(result, 'Status', n.status())
for code, split in zip(n.res_codes(), n.res_splits()):
st = ET.SubElement(result, 'SplitTime')
xml_child(st, 'ControlCode', code)
2022-06-27 12:26:32 +00:00
if split is not None:
xml_child(st, 'Time', split)
else:
xml_child(result, 'Status', n.status())
else:
xml_child(result, 'Status', n.status())
2022-05-11 13:07:33 +00:00
# </Result>
# </PersonResult>
# </Class>
ET.indent(root, space=' ', level=0)
return tree
2022-04-01 18:13:27 +00:00
def create_json_file(self):
rdicts = []
for runner in self.runners:
rdicts.append(runner.asdict())
cdicts = []
for course in self.courses:
cdicts.append(course.asdict())
ocdicts = []
for o_class in self.o_classes:
ocdicts.append(o_class.asdict())
ddicts = []
for dump in self.card_dumps:
ddicts.append(dump.asdict())
fdicts = []
for fee in self.fees:
fdicts.append(fee.asdict())
json_data = {
'id': self.id,
'name': self.name,
2022-06-27 12:26:32 +00:00
'orginser': self.organiser,
'start_time': self.start_time.isoformat(),
'end_time': self.end_time.isoformat(),
'runners': rdicts,
'courses': cdicts,
'o_classes': ocdicts,
'card_dumps': ddicts,
'fees': fdicts
}
return json.dumps(json_data, sort_keys=True, indent=4)
# Get event object from .otime json file
def from_json(f):
data = json.load(f)
runners = []
for r in data['runners']:
2022-06-27 12:26:32 +00:00
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']:
2022-06-27 12:26:32 +00:00
courses.append(Course(c['name'], c['codes'], forked=c['forked'],
variations=c['variations']))
o_classes = []
for c in data['o_classes']:
o_classes.append(OClass(c['name'], c['course_str'], None))
card_dumps = []
for d in data['card_dumps']:
2022-06-27 12:26:32 +00:00
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']:
2022-06-27 12:26:32 +00:00
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']))
2022-06-27 12:26:32 +00:00
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)
2022-04-01 18:13:27 +00:00
def create_start_list_pdf(self, file_name):
pdf = FPDF()
pdf.add_page()
2022-06-01 15:42:55 +00:00
pdf.add_font("LiberationSans", fname="data/fonts/LiberationSans-Regular.ttf")
pdf.set_font("LiberationSans", size=10)
2022-04-01 18:13:27 +00:00
line_height = pdf.font_size * 2
col_width = pdf.epw / 4 # distribute content evenly
for runner in self.runners:
pdf.multi_cell(col_width, line_height, runner.fullname(), border=1, ln=3, max_line_height=pdf.font_size, align='L')
2022-06-01 15:42:55 +00:00
pdf.multi_cell(col_width, line_height, runner.o_class_str, border=1, ln=3, max_line_height=pdf.font_size)
2022-04-01 18:13:27 +00:00
pdf.multi_cell(col_width, line_height, str(runner.card), border=1, ln=3, max_line_height=pdf.font_size)
2022-06-27 12:26:32 +00:00
if runner.start_time is not None:
2022-04-01 18:13:27 +00:00
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)
pdf.ln(line_height)
pdf.output(file_name)
2022-06-02 20:10:13 +00:00
def create_all_invoices(self, filename_prefix):
2022-06-27 12:26:32 +00:00
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]
2022-06-02 20:10:13 +00:00
for club in clubs:
self.create_club_invoice(club, filename_prefix + club + '.pdf')
2022-06-01 21:28:22 +00:00
def create_club_invoice(self, club, file_name):
# Get only runners in specified club
runners_ic = [x for x in self.runners if x.club == club]
2022-06-02 20:10:13 +00:00
payments = [x.fee.amount for x in runners_ic]
subtotal = sum(payments)
# Dict of runners in each fee
2022-06-01 21:28:22 +00:00
fee_dict = {}
for fee in self.fees:
fee_dict.update({fee.name: [x for x in runners_ic if x.fee.name == fee.name]})
2022-06-02 20:10:13 +00:00
if len(fee_dict[fee.name]) == 0:
fee_dict.pop(fee.name)
pdf = PDF()
pdf.set_title(f'Faktura {self.name} {club}')
pdf.set_producer('oTime 0.0.1')
pdf.set_creator('oTime 0.0.1')
pdf.set_creation_date()
2022-06-01 15:42:55 +00:00
pdf.add_page()
pdf.add_font("LiberationSans", fname="data/fonts/LiberationSans-Regular.ttf")
2022-06-01 21:28:22 +00:00
pdf.add_font("LiberationSans-Bold", fname="data/fonts/LiberationSans-Bold.ttf")
pdf.set_font("LiberationSans", size=10)
line_height = pdf.font_size * 1.5
# Topp venstre:
pdf.set_font("LiberationSans-Bold", size=10)
pdf.multi_cell(pdf.epw / 2, line_height, self.name, align='L')
2022-06-02 20:10:13 +00:00
pdf.ln(0.2)
2022-06-01 21:28:22 +00:00
pdf.set_font("LiberationSans", size=10)
2022-06-02 20:10:13 +00:00
pdf.multi_cell(pdf.epw / 2, line_height, self.organiser, align='L')
pdf.ln(14)
pdf.multi_cell(pdf.epw / 2, line_height, club, align='L')
2022-06-01 21:28:22 +00:00
pdf.ln()
# Topp høyre:
pdf.set_xy(-pdf.epw / 3, 10)
pdf.set_font("LiberationSans-Bold", size=20)
pdf.multi_cell(pdf.epw, line_height, 'Faktura', align='L')
pdf.set_xy(-pdf.epw / 3, 20)
# Dato
pdf.set_font("LiberationSans-Bold", size=10)
pdf.multi_cell(0, line_height, 'Dato:', align='L')
pdf.set_xy(-pdf.epw / 3, 20)
pdf.set_font("LiberationSans", size=10)
pdf.multi_cell(0, line_height, datetime.date.today().strftime('%d.%m.%Y'), align='R')
# Nummer
pdf.set_xy(-pdf.epw / 3, 20 + line_height)
pdf.set_font("LiberationSans-Bold", size=10)
pdf.multi_cell(0, line_height, 'Nummer:', align='L')
pdf.set_xy(-pdf.epw / 3, 20 + line_height)
pdf.multi_cell(0, line_height, '1', align='R')
# Kundeid
pdf.set_xy(-pdf.epw / 3, 20 + line_height*2)
pdf.set_font("LiberationSans-Bold", size=10)
pdf.multi_cell(0, line_height, 'Kundeid:', align='L')
pdf.set_xy(-pdf.epw / 3, 20 + line_height*2)
2022-06-01 15:42:55 +00:00
pdf.set_font("LiberationSans", size=10)
2022-06-01 21:28:22 +00:00
pdf.multi_cell(0, line_height, '123', align='R')
# Forfall
pdf.set_xy(-pdf.epw / 3, 20 + line_height*3)
pdf.set_font("LiberationSans-Bold", size=10)
pdf.multi_cell(0, line_height, 'Forfall:', align='L')
pdf.set_xy(-pdf.epw / 3, 20 + line_height*3)
pdf.set_font("LiberationSans", size=10)
pdf.multi_cell(0, line_height, datetime.date.today().strftime('%d.08.%Y'), align='R')
pdf.set_xy(-pdf.epw, 20 + line_height*5)
pdf.set_font("LiberationSans-Bold", size=10)
date = self.start_time.strftime('%d.%m.%Y')
pdf.multi_cell(0, line_height, f'Kontingentliste {self.name} dato: {date}', align='R')
pdf.ln()
pdf.set_font("LiberationSans", size=10)
# Tabell
2022-06-01 15:42:55 +00:00
line_height = pdf.font_size * 2
2022-06-27 12:26:32 +00:00
col_width = pdf.epw / 8 # distribute content evenly
# Top row
2022-06-01 21:28:22 +00:00
pdf.set_fill_color(191, 191, 191)
pdf.set_draw_color(191, 191, 191)
pdf.set_font("LiberationSans-Bold", size=10)
2022-06-27 12:26:32 +00:00
pdf.multi_cell(col_width, line_height, 'Startnr', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True)
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, '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)
2022-06-01 21:28:22 +00:00
pdf.ln()
2022-06-02 20:10:13 +00:00
pdf.set_draw_color(0, 0, 0)
2022-06-01 21:28:22 +00:00
for runners in fee_dict.values():
2022-06-02 20:10:13 +00:00
pdf.set_font("LiberationSans-Bold", size=11)
pdf.multi_cell(len(runners[0].fee.name)*2.3, pdf.font_size * 1.1, runners[0].fee.name, border='B', align='L')
pdf.set_font("LiberationSans", size=8)
line_height = pdf.font_size * 1.6
2022-06-01 21:28:22 +00:00
pdf.ln()
for runner in runners:
2022-06-27 12:26:32 +00:00
pdf.multi_cell(col_width, line_height, runner.id, ln=3, max_line_height=pdf.font_size, align='L') # Start Number
2022-06-02 20:10:13 +00:00
pdf.multi_cell(col_width*2, line_height, f'{runner.last}, {runner.first}', ln=3, max_line_height=pdf.font_size, align='L') # Name
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:
2022-06-27 12:26:32 +00:00
#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)
2022-06-02 20:10:13 +00:00
# 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)
elif runner.status() == 'Disqualified':
pdf.multi_cell(col_width, line_height, 'DSQ', ln=3, max_line_height=pdf.font_size)
elif runner.status() == 'Active':
pdf.multi_cell(col_width, line_height, 'DNS', ln=3, max_line_height=pdf.font_size)
else:
pdf.multi_cell(col_width, line_height, runner.status(), ln=3, max_line_height=pdf.font_size)
# Rank:
if runner.status() == 'OK':
pdf.multi_cell(col_width, line_height, str(runner.rank(self.runners)) + '.', ln=3, max_line_height=pdf.font_size)
else:
pdf.multi_cell(col_width, line_height, '', ln=3, max_line_height=pdf.font_size)
pdf.multi_cell(col_width, line_height, str(runner.fee.amount), ln=3, max_line_height=pdf.font_size, align='R')
2022-06-01 21:28:22 +00:00
pdf.ln(line_height)
2022-06-02 20:10:13 +00:00
pdf.set_draw_color(0, 0, 0)
# sum
pdf.set_font("LiberationSans-Bold", size=10)
pdf.set_x(col_width*8)
2022-06-27 12:26:32 +00:00
pdf.cell(0, line_height, 'Sum ' + str(subtotal), border='TB', align='R')
2022-06-02 20:10:13 +00:00
pdf.set_font("LiberationSans", size=10)
line_height = pdf.font_size * 1.5
pdf.ln(20)
pdf.multi_cell(0, line_height, 'Antall løpere ' + str(len(runners_ic)), ln=3, max_line_height=pdf.font_size, align='L')
pdf.set_x(col_width*7)
pdf.multi_cell(col_width, line_height, 'Total sum', ln=3, max_line_height=pdf.font_size, align='L')
pdf.multi_cell(0, line_height, str(subtotal), ln=3, max_line_height=pdf.font_size, align='R')
pdf.ln()
pdf.set_x(col_width*7)
pdf.multi_cell(col_width, line_height, 'Betalt', ln=3, max_line_height=pdf.font_size, align='L')
pdf.multi_cell(0, line_height, '0', ln=3, max_line_height=pdf.font_size, align='R')
pdf.ln()
pdf.set_font("LiberationSans-Bold", size=10)
pdf.set_x(col_width*7)
pdf.multi_cell(col_width, line_height, 'Skyldig', border='B', ln=3, max_line_height=pdf.font_size, align='L')
pdf.multi_cell(0, line_height, str(subtotal), border='B',ln=3, max_line_height=pdf.font_size, align='R')
2022-06-01 15:42:55 +00:00
pdf.output(file_name)
"""
2022-06-02 20:10:13 +00:00
class PDF(FPDF):
def footer(self):
self.set_y(-15)
self.set_font("LiberationSans", size=10)
self.set_fill_color(191, 191, 191)
self.set_draw_color(191, 191, 191)
col_width = self.epw / 3
self.cell(col_width, 7, 'oTime', border=1, align='L', fill=True)
self.cell(col_width, 7, datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S'), border=1, align='C', fill=True)
self.cell(col_width, 7, f"Side {self.page_no()} av {{nb}}", border=1, align='R', fill=True)
"""
2022-05-11 13:07:33 +00:00
# The runner object stores all the data specific to a runner.
class Runner:
2022-06-27 12:26:32 +00:00
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):
2022-05-11 13:07:33 +00:00
self.id = runner_id
self.first = first
self.last = last
2022-06-27 12:26:32 +00:00
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
2022-05-11 13:07:33 +00:00
def from_string(tt_line, o_classes):
2022-05-11 13:07:33 +00:00
#https://web.archive.org/web/20191229124046/http://wiki.ttime.no/index.php/Developer
eventorid = tt_line[0]
country = ''
name = tt_line[2].split(',')
try:
first = name[1].strip()
except:
first = ''
last = name[0]
try:
club = tt_line[4]
except:
club = "None"
try:
card = int(tt_line[6])
except:
card = 0
runner_o_class = None
try:
raw_class_str = tt_line[3]
except:
# VELDIG MIDLERTIDIG
2022-03-26 21:18:05 +00:00
runner_o_class = None
2022-05-11 13:07:33 +00:00
else:
if raw_class_str != '':
for i in o_classes:
if i.name == raw_class_str:
runner_o_class = i
break
else:
2022-05-11 13:07:33 +00:00
runner_o_class = None
# TODO: Gjør sånn at den lager nye o klasser om den ikke finnes fra før
2022-05-21 14:25:50 +00:00
options = tt_line[5].split(',')
try:
club_id = options[options.index('A')+3]
except:
club_id = 0
2022-05-11 13:07:33 +00:00
try:
start_time = options[options.index('U')+1]
except:
start_time = None
return Runner(eventorid, first, last, club=club, club_id=club_id,
country=country, card=card, o_class_str=raw_class_str,
o_class=runner_o_class, start_time=start_time)
2022-02-14 06:41:31 +00:00
2022-02-06 00:12:32 +00:00
def fullname(self):
return '{} {}'.format(self.first, self.last)
2022-05-11 13:07:33 +00:00
def check_codes(self):
2022-05-30 14:25:49 +00:00
return contains(self.res_codes(), self.card_r.controls)
2022-05-11 13:07:33 +00:00
def totaltime(self):
2022-05-30 14:25:49 +00:00
f_control = self.res_codes()[-1]
2022-03-03 16:50:53 +00:00
try:
index = self.card_r.controls.index(f_control)
return self.card_r.splits[index]
2022-03-03 16:50:53 +00:00
except:
2022-04-10 18:25:33 +00:00
return 0
2022-02-10 19:42:01 +00:00
def status(self):
2022-06-27 12:26:32 +00:00
if hasattr(self, 'card_r') is False or self.o_class is None:
2022-02-10 19:42:01 +00:00
return 'Active'
elif self.check_codes():
return 'OK'
2022-06-27 12:26:32 +00:00
elif self.check_codes() is False:
2022-02-10 19:42:01 +00:00
return 'Disqualified'
2022-05-11 13:07:33 +00:00
2022-06-01 15:42:55 +00:00
# TODO: må forbedres
2022-02-14 06:41:31 +00:00
def rank(self, allrunners):
c_ranked = rank_runners(allrunners, self.o_class)
2022-06-01 15:42:55 +00:00
try:
return c_ranked.index(self) + 1
except ValueError:
return None
2022-05-11 13:07:33 +00:00
2022-05-30 14:25:49 +00:00
def res_codes(self):
2022-06-27 12:26:32 +00:00
if self.o_class.course.forked is False:
2022-05-30 14:25:49 +00:00
return self.o_class.course.codes
else:
return self.o_class.course.variations[self.fork]
# TODO: Mange bugs med løyper som har samme post flere ganger
2022-05-30 14:25:49 +00:00
# Used for making result files and tables
2022-02-14 18:03:13 +00:00
def res_splits(self):
if self.status() == 'OK':
splits_cpy = self.card_r.splits.copy()
for control in self.card_r.controls:
if control not in self.res_codes():
index = self.card_r.controls.index(control)
split = self.card_r.splits[index]
splits_cpy.remove(split)
return splits_cpy
2022-05-30 14:25:49 +00:00
else:
splits_cpy = self.card_r.splits.copy()
for control in self.card_r.controls:
if control not in self.res_codes():
index = self.card_r.controls.index(control)
split = self.card_r.splits[index]
splits_cpy.remove(split)
punches = self.card_r.controls.copy()
splits = []
for code in self.res_codes():
if punches[0] == code:
splits.append(splits_cpy[0])
splits_cpy.pop(0)
punches.pop(0)
continue
else:
splits.append(None)
return splits
2022-05-30 14:25:49 +00:00
def asdict(self):
return {
'id': self.id,
'first': self.first,
'last': self.last,
'club_id': self.club_id,
'club': self.club,
'country': self.country,
'card': self.card,
'o_class_str': self.o_class_str,
'fork' : self.fork,
2022-06-01 15:42:55 +00:00
'start_time': self.start_time,
'fee_id': self.fee_id
}
2022-03-03 16:50:53 +00:00
2022-06-27 12:26:32 +00:00
2022-05-11 13:07:33 +00:00
class CardDump:
def __init__(self, card, controls, splits, read_time, s_time, f_time):
self.card = card
self.controls = controls
self.splits = splits
self.read_time = read_time
self.s_time = s_time
self.f_time = f_time
2022-05-11 13:07:33 +00:00
def __repr__(self):
return f'card({self.card}) controls({self.controls}) splits({self.splits})'
def from_mtr_bytes(datamsg):
card = int.from_bytes(datamsg[20:23], 'little')
#Extract codes and splits:
controls = []
splits = []
splits_offset = 26
code_numbytes = 1
time_numbytes = 2
split_numbytes = code_numbytes + time_numbytes
for split_index in range(50):
code_offset = splits_offset + split_index * split_numbytes
time_offset = code_offset + code_numbytes
code = int.from_bytes(datamsg[code_offset:code_offset+code_numbytes], 'little')
time = int.from_bytes(datamsg[time_offset:time_offset+time_numbytes], 'little')
if code != 0:
controls.append(code)
splits.append(time)
# Extract start time:
year = int.from_bytes(datamsg[8:9], 'little')
month = int.from_bytes(datamsg[9:10], 'little')
day = int.from_bytes(datamsg[10:11], 'little')
hours = int.from_bytes(datamsg[11:12], 'little')
minutes = int.from_bytes(datamsg[12:13], 'little')
seconds = int.from_bytes(datamsg[13:14], 'little')
milliseconds = int.from_bytes(datamsg[14:16], 'little')
read_time = datetime.datetime(year, month, day, hours, minutes, seconds, milliseconds)
if len(controls) > 2:
2022-06-27 12:26:32 +00:00
s_time = read_time - datetime.timedelta(seconds=splits[-1])
2022-05-11 13:07:33 +00:00
f_time = read_time - (datetime.timedelta(seconds=splits[-1]) + datetime.timedelta(seconds=splits[-2]))
else:
s_time = read_time
f_time = read_time
2022-05-11 13:07:33 +00:00
return(CardDump(card, controls, splits, read_time, s_time, f_time))
def list_from_mtr_f(mtr_f):
if type(mtr_f) == str:
f_list = mtr_f.splitlines()
rows = []
cards = []
# hver rad er brikkenummer med tilhørende info
csvreader = csv.reader(f_list)
for row in csvreader:
if len(row) == 0:
continue
rows.append(row)
controls = []
splits = []
# postkodene kommer på oddetall fra og med den 11. De blir hevet inn i controls
for item in row[11::2]:
if item == '250':
controls.append(int(item))
break
elif item == '000':
break
else:
controls.append(int(item))
# strekktidene kommer på partall fra og med den 12. De blir hevet i splits.
for item in row[12::2]:
if item == '00000':
break
else:
splits.append(int(item))
# looper gjonnom løperobjektene og legger til poster og strekktider + start og sluttid
# usikker på om dette er riktig klokeslett
tl = row[5].split(' ')
tl[0] = tl[0].split('.')
tl[0][2] = '20' + tl[0][2]
tl[0] = list(map(int, tl[0]))
tl[1] = tl[1].split(':')
tl[1][2] = float(tl[1][2])
tl[1] = list(map(int, tl[1]))
read_time = datetime.datetime(tl[0][2], tl[0][1], tl[0][0], tl[1][0], tl[1][1], tl[1][2])
if len(controls) > 2 and len(splits) > 2:
2022-06-27 12:26:32 +00:00
s_time = read_time - datetime.timedelta(seconds=splits[-1])
f_time = read_time - (datetime.timedelta(seconds=splits[-1]) + datetime.timedelta(seconds=splits[-2]))
else:
s_time = read_time
f_time = read_time
2022-05-11 13:07:33 +00:00
cards.append(CardDump(int(row[6]), controls, splits, read_time, s_time, f_time))
return cards
2022-05-11 13:07:33 +00:00
def asdict(self):
return {
'card': self.card,
'controls': self.controls,
'splits': self.splits,
'read_time': self.read_time.isoformat(),
's_time': self.s_time.isoformat(),
'f_time': self.f_time.isoformat()
}
2022-05-11 13:07:33 +00:00
# Stored in Event.courses
class Course:
2022-06-27 12:26:32 +00:00
def __init__(self, name, codes, forked=False, variations=None):
2022-02-06 00:12:32 +00:00
self.name = name
self.codes = codes
2022-06-27 12:26:32 +00:00
self.forked = forked
self.variations = variations
def __repr__(self):
return f'name({self.name})'
2022-02-06 00:12:32 +00:00
def asdict(self):
return {
'name': self.name,
2022-05-30 14:25:49 +00:00
'codes': self.codes,
'forked': self.forked,
'variations': self.variations
}
2022-05-11 13:07:33 +00:00
# Stored in Event.o_classes
class OClass:
def __init__(self, name, course_str, course):
2022-02-06 00:12:32 +00:00
self.name = name
self.course_str = course_str
2022-02-06 00:12:32 +00:00
self.course = course
def __repr__(self):
return f'name({self.name})'
2022-02-06 00:12:32 +00:00
def asdict(self):
return {
'name': self.name,
'course_str': self.course_str
}
2022-05-31 19:14:50 +00:00
class Fee:
2022-06-27 12:26:32 +00:00
def __init__(self, fee_id, name, currency, amount, from_birth_date=None,
to_birth_date=None):
2022-05-31 19:14:50 +00:00
self.id = fee_id
self.name = name
2022-05-31 19:14:50 +00:00
self.currency = currency
self.amount = amount
2022-06-27 12:26:32 +00:00
self.from_birth_date = from_birth_date
self.to_birth_date = to_birth_date
def asdict(self):
return {
'id': self.id,
'name': self.name,
'currency': self.currency,
'amount': self.amount,
'from_birth_date': self.from_birth_date,
'to_birth_date': self.to_birth_date
}
2022-05-11 13:07:33 +00:00
# TODO: Take string instead of file.
def courses_from_ttime_conf(ttime_file):
if type(ttime_file) == str:
conf = ttime_file.splitlines()
elif isinstance(ttime_file, io.TextIOBase):
conf = ttime_file.readlines()
2022-02-06 00:12:32 +00:00
courses = []
for line in conf:
if '-codes' in line:
code_list = re.search(r'(?<=\")(.*?)(?=\")', line).group().split(';')
loops = 0
for n in code_list:
n = n.split(',')
loops += 1
n = list(map(int, n))
2022-05-11 13:07:33 +00:00
courses.append(Course('course_'+str(loops), n))
2022-02-06 00:12:32 +00:00
return courses
2022-05-11 13:07:33 +00:00
2022-02-06 00:12:32 +00:00
def classes_from_ttime_conf(ttime_file, courses):
if type(ttime_file) == str:
conf = ttime_file.splitlines()
elif isinstance(ttime_file, io.TextIOBase):
conf = ttime_file.readlines()
2022-02-06 00:12:32 +00:00
o_classes = []
for line in conf:
if '-courses' in line:
raw_courselist = re.search(r'(?<=\")(.*?)(?=\")', line).group().split(';')
loops = 0
for n in raw_courselist:
2022-03-26 21:18:05 +00:00
split = n.split(',')
for i in split:
o_classes.append(OClass(i, courses[loops].name, courses[loops]))
2022-02-06 00:12:32 +00:00
loops += 1
return o_classes
def runners_from_xml_entries(xml_file):
2022-05-21 14:25:50 +00:00
tree = ET.parse(xml_file)
root = tree.getroot()
2022-06-27 12:26:32 +00:00
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
2022-06-27 12:26:32 +00:00
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
2022-06-27 12:26:32 +00:00
organisation = p_entry.find(f'./{url}Organisation')
2022-06-01 15:42:55 +00:00
if organisation is not None:
2022-06-27 12:26:32 +00:00
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']
2022-06-01 15:42:55 +00:00
else:
club_id = club_name = club_name_short = country = None
2022-06-27 12:26:32 +00:00
class_el = p_entry.find(f'./{url}Class')
class_str = class_el.find(f'./{url}Name').text
2022-05-21 14:25:50 +00:00
2022-06-27 12:26:32 +00:00
fee_id = int(p_entry.find(f'./{url}AssignedFee/{url}Fee/{url}Id').text)
2022-06-01 15:42:55 +00:00
2022-05-21 14:25:50 +00:00
try:
2022-06-27 12:26:32 +00:00
card = int(p_entry.find(f'./{url}ControlCard').text)
except AttributeError:
card = None
2022-05-21 14:25:50 +00:00
start_time = None
runners.append(Runner(rid, first, last, club=club_name, club_id=club_id,
2022-06-27 12:26:32 +00:00
country=country,card=card, o_class_str=class_str,
start_time=start_time, fee_id=fee_id))
return runners
2022-06-27 12:26:32 +00:00
def fees_from_xml_entries(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
2022-05-21 14:25:50 +00:00
2022-06-27 12:26:32 +00:00
url = '{http://www.orienteering.org/datastandard/3.0}'
allfees = root.findall(f'.//{url}Fee')
added_ids = []
fee_objs = []
for fee in allfees:
2022-06-27 12:26:32 +00:00
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
2022-06-27 12:26:32 +00:00
name = fee.find(f'./{url}Name').text
currency = fee.find(f'./{url}Amount').attrib['currency']
amount = int(fee.find(f'./{url}Amount').text)
try:
2022-06-27 12:26:32 +00:00
from_birth_date = fee.find(f'./{url}FromDateOfBirth').text
except AttributeError:
from_birth_date = None
try:
2022-06-27 12:26:32 +00:00
to_birth_date = fee.find(f'./{url}ToDateOfBirth').text
except AttributeError:
to_birth_date = None
2022-06-27 12:26:32 +00:00
fee_objs.append(Fee(fee_id, name, currency, amount,
from_birth_date=from_birth_date, to_birth_date=to_birth_date))
return fee_objs
2022-05-21 14:25:50 +00:00
2022-06-27 12:26:32 +00:00
2022-05-11 13:07:33 +00:00
# Checks if small list is in big list
def contains(small, big):
valid = True
mark = 0
map_bl = []
for i in small:
2022-06-27 12:26:32 +00:00
for n, control in enumerate(big[mark:]):
if i == control:
mark += n
map_bl.append(mark)
break
else:
valid = False
if valid:
return map_bl
else:
return False
2022-06-27 12:26:32 +00:00
2022-02-14 06:41:31 +00:00
def get_runners_in_class(runners, o_class):
2022-03-11 14:31:20 +00:00
# Filters out runner objects that dont have the correct o_class
2022-02-10 19:42:01 +00:00
list_filtrd = []
for i in runners:
if i.o_class == o_class:
list_filtrd.append(i)
return list_filtrd
2022-06-27 12:26:32 +00:00
2022-02-14 06:41:31 +00:00
def rank_runners(allrunners, o_class):
runners = get_runners_in_class(allrunners, o_class)
runners_ranked = []
for i in runners:
if i.status() == 'OK':
runners_ranked.append(i)
runners_ranked.sort(key=lambda x: x.totaltime())
2022-02-14 06:41:31 +00:00
return runners_ranked
2022-06-27 12:26:32 +00:00
2022-05-11 13:07:33 +00:00
# Used to make creating xml files easier
2022-02-18 10:01:55 +00:00
def xml_child(parent, tag, content):
e = ET.SubElement(parent, tag)
e.text = str(content)