koma-pretix-parser/parse.py
2023-10-02 20:59:39 +02:00

83 lines
3.1 KiB
Python

import json
from pathlib import Path
from typing import Dict, Tuple, Union # I have just python3.8 here :(
def parse(filename: Union[str, Path]) -> Tuple[
Dict[int, str],
Dict[int, int],
Dict[int, str],
Dict[int, Dict[Tuple[int, str], int]]
]:
"""Parse a JSON export from pretix.
:param filename: filename of the JSON export to parse.
:returns: Four mappings:
* item_id to item name
* item_id to order count of this item
* question_id to question identifier
* question_id to stats for this question, which identifies an answer by its item_id and actual answer.
The stats map this identifier to number of occurrences
"""
with open(filename, 'r', encoding='utf8') as f:
data = json.load(f)['event']
items = {i['id']: i['name'] for i in data['items']}
count_items = {id_: 0 for id_ in items}
questions = {q['id']: q['identifier'] for q in data['questions']}
quest_answers = {id_: {} for id_ in questions}
for order in data['orders']:
for position in order['positions']:
item_id = position['item']
count_items[item_id] += 1
for answer in position['answers']:
quest_id = answer['question']
answer_key = (item_id, answer['answer'])
quest_answers[quest_id][answer_key] = (
quest_answers[quest_id].get(answer_key, 0) + 1
)
return items, count_items, questions, quest_answers
def wiki_stats(items: Dict[int, str], count_items: Dict[int, int], questions: Dict[int, str],
quest_answers: Dict[int, Dict[Tuple[int, str], int]]) -> str:
"""Generate stats for the Wiki page.
Input parameters are output of the parse() function.
"""
ret = ""
ret += ('== Anmeldezahlen ==\n'
'{|class="wikitable sortable"\n'
'! Posten !! Anzahl\n'
'|-\n')
for item_id, item_name in items.items():
ret += f"|| {item_name} || {count_items.get(item_id)}\n|-\n"
ret += "|}\n"
# ids of the questions which represent a size of a merch product
size_ids = (312, 313, 314, 316, 319, 320, 321, 322, 323)
ret += ('== Merch-Größenverteilung ==\n'
'{|class="wikitable sortable"\n'
'! Größe/Eigenschaft !! Wert !! Anzahl\n'
'|-\n')
for size_id in size_ids:
for size, count in quest_answers[size_id].items():
ret += f"|| {questions[size_id]}: || {size[1]} || {count}\n|-\n"
ret += "|}\n"
athene_id = 305 # ID of the question how the logo image is to be named
human_id = 147 # ticket for a human
mascot_id = 148 # ticket for a mascot
def prefix(id_):
return "Mensch sagt:" if id_ == human_id else "Maskottchen sagt:" if id_ == mascot_id else ""
ret += ('== Wie heißt das Ding? ==\n'
'{|class="wikitable sortable"\n'
'! Variante !! Stimmen\n'
'|-\n')
for variant, count in quest_answers[athene_id].items():
ret += f"|| {prefix(variant[0])} {variant[1]} || {count}\n|-\n"
ret += "|}\n"
return ret