2022-12-18 16:40:39 +00:00
|
|
|
from dataclasses import dataclass
|
2024-01-21 23:35:44 +00:00
|
|
|
from sanic import Request, exceptions, Sanic
|
2022-12-18 16:40:39 +00:00
|
|
|
import httpx
|
|
|
|
import re
|
2023-12-30 10:27:42 +00:00
|
|
|
from utils import *
|
2022-12-18 16:40:39 +00:00
|
|
|
from config import *
|
2022-12-18 16:48:29 +00:00
|
|
|
from os.path import join
|
2023-01-08 20:23:39 +00:00
|
|
|
import json
|
2024-01-21 23:35:44 +00:00
|
|
|
from sanic.log import logger
|
2023-01-17 21:25:35 +00:00
|
|
|
from time import time
|
2024-02-14 19:22:56 +00:00
|
|
|
from metrics import *
|
2024-01-21 23:35:44 +00:00
|
|
|
import asyncio
|
2024-02-22 18:15:33 +00:00
|
|
|
from threading import Lock
|
|
|
|
import pretixClient
|
|
|
|
import traceback
|
2022-12-18 16:40:39 +00:00
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class Order:
|
|
|
|
def __init__(self, data):
|
2023-01-17 21:25:35 +00:00
|
|
|
|
2023-01-17 21:49:39 +00:00
|
|
|
self.time = time()
|
2022-12-18 16:40:39 +00:00
|
|
|
self.data = data
|
2024-05-13 08:25:45 +00:00
|
|
|
if(len(self.data['positions']) == 0):
|
|
|
|
for fee in data['fees']:
|
|
|
|
if(fee['fee_type'] == "cancellation"):
|
|
|
|
self.data['status'] = 'c'
|
2022-12-18 16:40:39 +00:00
|
|
|
self.status = {'n': 'pending', 'p': 'paid', 'e': 'expired', 'c': 'canceled'}[self.data['status']]
|
2024-01-13 15:59:24 +00:00
|
|
|
self.secret = data['secret']
|
|
|
|
|
2023-02-02 21:47:06 +00:00
|
|
|
if not len(self.data['positions']):
|
|
|
|
self.status = 'canceled'
|
|
|
|
|
2022-12-18 16:40:39 +00:00
|
|
|
self.code = data['code']
|
2023-01-17 21:25:35 +00:00
|
|
|
self.pending_update = False
|
|
|
|
|
2023-05-11 22:18:49 +00:00
|
|
|
self.email = data['email']
|
|
|
|
|
2023-01-08 20:23:39 +00:00
|
|
|
self.has_card = False
|
|
|
|
self.sponsorship = None
|
2023-01-17 21:25:35 +00:00
|
|
|
self.has_early = False
|
|
|
|
self.has_late = False
|
2024-03-12 20:35:52 +00:00
|
|
|
self.first_name = "None"
|
|
|
|
self.last_name = "None"
|
2023-08-06 10:46:09 +00:00
|
|
|
self.country = 'xx'
|
2023-05-25 22:58:44 +00:00
|
|
|
self.address = None
|
2023-07-04 21:07:39 +00:00
|
|
|
self.checked_in = False
|
2023-12-30 10:27:42 +00:00
|
|
|
self.room_type = None
|
|
|
|
self.daily = False
|
|
|
|
self.dailyDays = []
|
2024-03-12 20:35:52 +00:00
|
|
|
self.bed_in_room = -1
|
2024-03-20 16:28:35 +00:00
|
|
|
self.room_person_no = -1
|
2023-12-30 10:27:42 +00:00
|
|
|
self.answers = []
|
2024-03-12 20:35:52 +00:00
|
|
|
self.position_id = -1
|
|
|
|
self.position_positionid = -1
|
|
|
|
self.position_positiontypeid = -1
|
|
|
|
self.barcode = "None"
|
2022-12-18 16:40:39 +00:00
|
|
|
|
2023-08-06 10:46:09 +00:00
|
|
|
idata = data['invoice_address']
|
|
|
|
if idata:
|
2024-05-13 11:30:21 +00:00
|
|
|
self.address = f"{idata['street'].strip()} - {idata['zipcode'].strip()} {idata['city'].strip()} - {idata['country'].strip()}".replace("\n", "").replace("\r", "")
|
2023-08-06 10:46:09 +00:00
|
|
|
self.country = idata['country']
|
|
|
|
|
2022-12-18 16:40:39 +00:00
|
|
|
for p in self.data['positions']:
|
2024-01-08 21:02:27 +00:00
|
|
|
if p['item'] in CATEGORIES_LIST_MAP['tickets']:
|
2023-01-08 20:23:39 +00:00
|
|
|
self.position_id = p['id']
|
|
|
|
self.position_positionid = p['positionid']
|
2023-09-20 18:15:48 +00:00
|
|
|
self.position_positiontypeid = p['item']
|
2023-01-08 20:23:39 +00:00
|
|
|
self.answers = p['answers']
|
2023-12-30 10:27:42 +00:00
|
|
|
for i, ans in enumerate(self.answers):
|
|
|
|
if(TYPE_OF_QUESTIONS[self.answers[i]['question']] == QUESTION_TYPES['file_upload']):
|
|
|
|
self.answers[i]['answer'] = "file:keep"
|
2023-01-08 20:23:39 +00:00
|
|
|
self.barcode = p['secret']
|
2023-07-04 21:07:39 +00:00
|
|
|
self.checked_in = bool(p['checkins'])
|
2023-12-30 10:27:42 +00:00
|
|
|
|
2024-01-08 21:02:27 +00:00
|
|
|
if p['item'] in CATEGORIES_LIST_MAP['dailys']:
|
2023-12-30 10:27:42 +00:00
|
|
|
self.daily = True
|
2024-01-08 21:02:27 +00:00
|
|
|
self.dailyDays.append(CATEGORIES_LIST_MAP['dailys'].index(p['item']))
|
2022-12-18 16:40:39 +00:00
|
|
|
|
2024-01-08 21:02:27 +00:00
|
|
|
if p['item'] in CATEGORIES_LIST_MAP['memberships']:
|
2023-01-08 20:23:39 +00:00
|
|
|
self.has_card = True
|
|
|
|
|
2024-01-08 21:02:27 +00:00
|
|
|
if p['item'] == ITEMS_ID_MAP['sponsorship_item']:
|
2024-01-18 17:03:32 +00:00
|
|
|
sponsorshipType = key_from_value(ITEM_VARIATIONS_MAP['sponsorship_item'], p['variation'])
|
2024-01-08 21:02:27 +00:00
|
|
|
self.sponsorship = sponsorshipType[0].replace ('sponsorship_item_', '') if len(sponsorshipType) > 0 else None
|
2023-01-08 20:23:39 +00:00
|
|
|
|
2023-01-17 21:25:35 +00:00
|
|
|
if p['attendee_name']:
|
|
|
|
self.first_name = p['attendee_name_parts']['given_name']
|
|
|
|
self.last_name = p['attendee_name_parts']['family_name']
|
|
|
|
|
2024-01-08 21:02:27 +00:00
|
|
|
if p['item'] == ITEMS_ID_MAP['early_arrival_admission']:
|
2023-01-17 21:25:35 +00:00
|
|
|
self.has_early = True
|
|
|
|
|
2024-01-08 21:02:27 +00:00
|
|
|
if p['item'] == ITEMS_ID_MAP['late_departure_admission']:
|
2023-01-17 21:25:35 +00:00
|
|
|
self.has_late = True
|
2023-12-30 10:27:42 +00:00
|
|
|
|
2024-01-08 21:02:27 +00:00
|
|
|
if p['item'] == ITEMS_ID_MAP['bed_in_room']:
|
2024-01-18 17:03:32 +00:00
|
|
|
roomTypeLst = key_from_value(ITEM_VARIATIONS_MAP['bed_in_room'], p['variation'])
|
2024-01-08 21:02:27 +00:00
|
|
|
roomTypeId = roomTypeLst[0] if len(roomTypeLst) > 0 else None
|
2023-12-30 10:27:42 +00:00
|
|
|
self.bed_in_room = p['variation']
|
2024-03-20 16:28:35 +00:00
|
|
|
self.room_person_no = ROOM_CAPACITY_MAP[roomTypeId] if roomTypeId in ROOM_CAPACITY_MAP else self.room_person_no
|
2023-01-17 21:25:35 +00:00
|
|
|
|
|
|
|
self.total = float(data['total'])
|
|
|
|
self.fees = 0
|
2023-05-08 21:42:44 +00:00
|
|
|
self.refunds = 0
|
2023-01-17 21:25:35 +00:00
|
|
|
for fee in data['fees']:
|
|
|
|
self.fees += float(fee['value'])
|
2023-05-08 21:42:44 +00:00
|
|
|
|
|
|
|
for ref in data['refunds']:
|
|
|
|
self.refunds += float(ref['amount'])
|
2023-01-17 21:25:35 +00:00
|
|
|
|
|
|
|
answers = ['payment_provider', 'shirt_size', 'birth_date', 'fursona_name', 'room_confirmed', 'room_id']
|
|
|
|
|
|
|
|
self.payment_provider = data['payment_provider']
|
2023-05-23 19:02:02 +00:00
|
|
|
self.comment = data['comment']
|
2023-05-25 22:58:44 +00:00
|
|
|
self.phone = data['phone']
|
2024-01-19 17:03:54 +00:00
|
|
|
self.room_errors = []
|
2024-01-08 21:02:27 +00:00
|
|
|
self.loadAns()
|
2024-03-12 20:35:52 +00:00
|
|
|
|
2024-04-14 09:35:41 +00:00
|
|
|
if(self.bed_in_room < 0 and not self.daily):
|
2024-03-12 20:35:52 +00:00
|
|
|
self.status = "canceled" # Must refer to the previous status assignment
|
2024-01-08 21:02:27 +00:00
|
|
|
def loadAns(self):
|
2023-01-08 20:23:39 +00:00
|
|
|
self.shirt_size = self.ans('shirt_size')
|
|
|
|
self.is_artist = True if self.ans('is_artist') != 'No' else False
|
|
|
|
self.is_fursuiter = True if self.ans('is_fursuiter') != 'No' else False
|
|
|
|
self.is_allergic = True if self.ans('is_allergic') != 'No' else False
|
2023-07-04 21:07:39 +00:00
|
|
|
self.notes = self.ans('notes')
|
|
|
|
self.badge_id = int(self.ans('badge_id')) if self.ans('badge_id') else None
|
2023-01-19 16:03:38 +00:00
|
|
|
self.propic_locked = self.ans('propic_locked')
|
2023-05-23 20:15:01 +00:00
|
|
|
self.propic_fursuiter = self.ans('propic_fursuiter')
|
|
|
|
self.propic = self.ans('propic')
|
2023-05-08 20:22:07 +00:00
|
|
|
self.carpooling_message = json.loads(self.ans('carpooling_message')) if self.ans('carpooling_message') else {}
|
2023-05-23 19:02:02 +00:00
|
|
|
self.karaoke_songs = json.loads(self.ans('karaoke_songs')) if self.ans('karaoke_songs') else {}
|
2023-01-08 20:23:39 +00:00
|
|
|
self.birth_date = self.ans('birth_date')
|
2023-05-25 22:58:44 +00:00
|
|
|
self.birth_location = self.ans('birth_location')
|
2022-12-18 16:40:39 +00:00
|
|
|
self.name = self.ans('fursona_name')
|
|
|
|
self.room_id = self.ans('room_id')
|
|
|
|
self.room_confirmed = self.ans('room_confirmed')
|
2023-01-08 20:23:39 +00:00
|
|
|
self.room_name = self.ans('room_name')
|
2022-12-18 16:40:39 +00:00
|
|
|
self.pending_room = self.ans('pending_room')
|
|
|
|
self.pending_roommates = self.ans('pending_roommates').split(',') if self.ans('pending_roommates') else []
|
|
|
|
self.room_members = self.ans('room_members').split(',') if self.ans('room_members') else []
|
2024-01-13 13:58:06 +00:00
|
|
|
self.room_owner = (self.code is not None and self.room_id is not None and self.code.strip() == self.room_id.strip())
|
2022-12-18 16:40:39 +00:00
|
|
|
self.room_secret = self.ans('room_secret')
|
2023-05-11 22:18:49 +00:00
|
|
|
self.app_token = self.ans('app_token')
|
2023-05-23 19:02:02 +00:00
|
|
|
self.nfc_id = self.ans('nfc_id')
|
|
|
|
self.can_scan_nfc = True if self.ans('can_scan_nfc') != 'No' else False
|
2023-07-04 21:07:39 +00:00
|
|
|
self.actual_room = self.ans('actual_room')
|
2024-01-08 21:02:27 +00:00
|
|
|
self.staff_role = self.ans('staff_role')
|
2023-05-25 22:58:44 +00:00
|
|
|
self.telegram_username = self.ans('telegram_username').strip('@') if self.ans('telegram_username') else None
|
2024-01-29 23:35:56 +00:00
|
|
|
self.shuttle_bus = self.ans('shuttle_bus')
|
2022-12-18 16:40:39 +00:00
|
|
|
def __getitem__(self, var):
|
|
|
|
return self.data[var]
|
2024-01-19 00:15:20 +00:00
|
|
|
|
|
|
|
def set_room_errors (self, to_set):
|
2024-02-19 06:55:23 +00:00
|
|
|
self.room_errors = to_set
|
2022-12-18 16:40:39 +00:00
|
|
|
|
|
|
|
def ans(self, name):
|
2023-01-08 20:23:39 +00:00
|
|
|
for p in self.data['positions']:
|
|
|
|
for a in p['answers']:
|
2023-07-04 21:07:39 +00:00
|
|
|
if a.get('question_identifier', None) == name:
|
2023-01-08 20:23:39 +00:00
|
|
|
if a['answer'] in ['True', 'False']:
|
|
|
|
return bool(a['answer'] == 'True')
|
|
|
|
return a['answer']
|
2022-12-18 16:40:39 +00:00
|
|
|
return None
|
2024-01-08 21:02:27 +00:00
|
|
|
|
|
|
|
def isBadgeValid (self):
|
|
|
|
return self.ans('propic') and (not self.is_fursuiter or self.ans('propic_fursuiter'))
|
|
|
|
|
|
|
|
def isAdmin (self):
|
|
|
|
return self.code in ADMINS or self.staff_role in ADMINS_PRETIX_ROLE_NAMES
|
2022-12-18 16:40:39 +00:00
|
|
|
|
2023-12-30 10:27:42 +00:00
|
|
|
async def edit_answer_fileUpload(self, name, fileName, mimeType, data : bytes):
|
|
|
|
if(mimeType != None and data != None):
|
2024-02-22 18:15:33 +00:00
|
|
|
localHeaders = dict(headers)
|
|
|
|
localHeaders['Content-Type'] = mimeType
|
|
|
|
localHeaders['Content-Disposition'] = f'attachment; filename="{fileName}"'
|
2024-03-02 12:44:49 +00:00
|
|
|
res = await pretixClient.post("upload", baseUrl=base_url, headers=localHeaders, content=data, expectedStatusCodes=[201])
|
2024-02-22 18:15:33 +00:00
|
|
|
res = res.json()
|
|
|
|
await self.edit_answer(name, res['id'])
|
2023-12-30 10:27:42 +00:00
|
|
|
else:
|
|
|
|
await self.edit_answer(name, None)
|
2024-01-08 21:02:27 +00:00
|
|
|
self.loadAns()
|
2023-12-30 10:27:42 +00:00
|
|
|
|
2022-12-18 16:40:39 +00:00
|
|
|
async def edit_answer(self, name, new_answer):
|
|
|
|
found = False
|
2023-01-17 21:25:35 +00:00
|
|
|
self.pending_update = True
|
2022-12-18 16:40:39 +00:00
|
|
|
for key in range(len(self.answers)):
|
2023-07-04 21:07:39 +00:00
|
|
|
if self.answers[key].get('question_identifier', None) == name:
|
2022-12-18 16:40:39 +00:00
|
|
|
if new_answer != None:
|
2024-01-21 23:35:44 +00:00
|
|
|
if DEV_MODE and EXTRA_PRINTS: logger.debug('[ANSWER EDIT] EXISTING ANSWER UPDATE %s => %s', name, new_answer)
|
2022-12-18 16:40:39 +00:00
|
|
|
self.answers[key]['answer'] = new_answer
|
|
|
|
found = True
|
|
|
|
else:
|
2024-01-21 23:35:44 +00:00
|
|
|
if DEV_MODE and EXTRA_PRINTS: logger.debug('[ANSWER EDIT] DEL ANSWER %s => %s', name, new_answer)
|
2022-12-18 16:40:39 +00:00
|
|
|
del self.answers[key]
|
|
|
|
|
|
|
|
break
|
|
|
|
|
|
|
|
if (not found) and (new_answer is not None):
|
2024-02-22 18:15:33 +00:00
|
|
|
res = await pretixClient.get("questions/")
|
|
|
|
res = res.json()
|
2022-12-18 16:40:39 +00:00
|
|
|
for r in res['results']:
|
|
|
|
if r['identifier'] != name: continue
|
|
|
|
|
2024-01-21 23:35:44 +00:00
|
|
|
if DEV_MODE and EXTRA_PRINTS: logger.debug(f'[ANSWER EDIT] %s => %s', name, new_answer)
|
2022-12-18 16:40:39 +00:00
|
|
|
self.answers.append({
|
|
|
|
'question': r['id'],
|
|
|
|
'answer': new_answer,
|
|
|
|
'options': r['options']
|
|
|
|
})
|
2024-01-08 21:02:27 +00:00
|
|
|
self.loadAns()
|
2022-12-18 16:40:39 +00:00
|
|
|
|
|
|
|
async def send_answers(self):
|
2024-02-22 18:15:33 +00:00
|
|
|
if DEV_MODE and EXTRA_PRINTS: logger.debug("[ANSWER POST] POSITION ID IS %s", self.position_id)
|
|
|
|
|
|
|
|
for i, ans in enumerate(self.answers):
|
|
|
|
if TYPE_OF_QUESTIONS[ans['question']] == QUESTION_TYPES["multiple_choice_from_list"]: # if multiple choice
|
|
|
|
identifier = ans['question_identifier']
|
|
|
|
if self.ans(identifier) == "": #if empty answer
|
|
|
|
await self.edit_answer(identifier, None)
|
|
|
|
# Fix for karaoke fields
|
|
|
|
#if ans['question'] == 40:
|
|
|
|
# del self.answers[i]['options']
|
|
|
|
# del self.answers[i]['option_identifiers']
|
2024-05-13 08:25:45 +00:00
|
|
|
|
|
|
|
ans = [] if self.status == "canceled" else self.answers
|
|
|
|
res = await pretixClient.patch(f'orderpositions/{self.position_id}/', json={'answers': ans}, expectedStatusCodes=None)
|
2024-02-22 18:15:33 +00:00
|
|
|
|
|
|
|
if res.status_code != 200:
|
2024-05-10 19:51:14 +00:00
|
|
|
e = res.json()
|
|
|
|
if "answers" in e:
|
|
|
|
for ans, err in zip(self.answers, res.json()['answers']):
|
|
|
|
if err:
|
|
|
|
logger.error ('[ANSWERS SENDING] ERROR ON %s %s', ans, err)
|
|
|
|
else:
|
|
|
|
logger.error("[ANSWERS SENDING] GENERIC ERROR. Response: '%s'", str(e))
|
2023-05-23 19:02:02 +00:00
|
|
|
|
2024-02-22 18:15:33 +00:00
|
|
|
raise exceptions.ServerError('There has been an error while updating this answers.')
|
|
|
|
|
|
|
|
for i, ans in enumerate(self.answers):
|
|
|
|
if(TYPE_OF_QUESTIONS[self.answers[i]['question']] == QUESTION_TYPES['file_upload']):
|
|
|
|
self.answers[i]['answer'] = "file:keep"
|
2023-12-30 10:27:42 +00:00
|
|
|
|
2023-01-17 21:25:35 +00:00
|
|
|
self.pending_update = False
|
2023-01-19 16:03:38 +00:00
|
|
|
self.time = -1
|
2024-01-08 21:02:27 +00:00
|
|
|
self.loadAns()
|
2024-01-29 23:35:56 +00:00
|
|
|
|
|
|
|
def get_language(self):
|
|
|
|
return self.country.lower() if self.country.lower() in AVAILABLE_LOCALES else 'en'
|
2024-05-19 09:03:48 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
to_return = f"{'Room' if self.room_owner else 'Order'} {self.code}"
|
|
|
|
if self.room_owner == True:
|
|
|
|
to_return = f"{to_return} [ members = {self.room_members} ]"
|
|
|
|
return to_return
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
to_return = f"{'Room' if self.room_owner == True else 'Order'} {self.code}"
|
|
|
|
if self.room_owner == True:
|
|
|
|
to_return = f"{to_return} [ members = {self.room_members} ]"
|
|
|
|
return to_return
|
2022-12-18 16:40:39 +00:00
|
|
|
|
2024-05-19 19:07:31 +00:00
|
|
|
@dataclass
|
|
|
|
class Quota:
|
|
|
|
def __init__(self, data):
|
|
|
|
self.items = data['items'] if 'items' in data else []
|
|
|
|
self.variations = data['variations'] if 'variations' in data else []
|
|
|
|
self.available = data['available'] if 'available' in data else False
|
|
|
|
self.size = data['size'] if 'size' in data else 0
|
|
|
|
self.available_number = data['available_number'] if 'available_number' in data else 0
|
|
|
|
|
|
|
|
def has_item (self, id: int=-1, variation: int=None):
|
|
|
|
return id in self.items if not variation else (id in self.items and variation in self.variations)
|
|
|
|
|
|
|
|
def get_left (self):
|
|
|
|
return self.available_number
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return f'Quota [items={self.items}, variations={self.variations}] [{self.available_number}/{self.size}]'
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return f'Quota [items={self.items}, variations={self.variations}] [{self.available_number}/{self.size}]'
|
|
|
|
|
|
|
|
def get_quota(item: int, variation: int = None) -> Quota:
|
2024-05-20 13:44:21 +00:00
|
|
|
ret : Quota = None
|
2024-05-19 19:07:31 +00:00
|
|
|
for q in QUOTA_LIST:
|
2024-05-20 13:44:21 +00:00
|
|
|
if (q.has_item(item, variation)):
|
|
|
|
if(ret == None or (q.size != None and q.size < ret.size)):
|
|
|
|
ret = q
|
|
|
|
return ret
|
2024-05-19 19:07:31 +00:00
|
|
|
|
2022-12-18 16:40:39 +00:00
|
|
|
@dataclass
|
|
|
|
class Quotas:
|
|
|
|
def __init__(self, data):
|
|
|
|
self.data = data
|
|
|
|
|
|
|
|
def get_left(self, capacity):
|
|
|
|
for quota in self.data['results']:
|
2023-09-20 18:15:48 +00:00
|
|
|
if quota['id'] == ROOM_QUOTA_ID[capacity]:
|
2023-08-06 12:25:50 +00:00
|
|
|
return quota['available_number']
|
|
|
|
return 0
|
2022-12-18 16:40:39 +00:00
|
|
|
|
|
|
|
async def get_quotas(request: Request=None):
|
2024-02-22 18:15:33 +00:00
|
|
|
res = await pretixClient.get('quotas/?order=id&with_availability=true')
|
|
|
|
res = res.json()
|
|
|
|
|
|
|
|
return Quotas(res)
|
2022-12-18 16:40:39 +00:00
|
|
|
|
2024-05-19 19:07:31 +00:00
|
|
|
async def load_item_quotas() -> bool:
|
|
|
|
global QUOTA_LIST
|
|
|
|
QUOTA_LIST = []
|
|
|
|
logger.info ('[QUOTAS] Loading quotas...')
|
|
|
|
success = True
|
|
|
|
try:
|
|
|
|
res = await pretixClient.get('quotas/?order=id&with_availability=true')
|
|
|
|
res = res.json()
|
|
|
|
for quota_data in res['results']:
|
|
|
|
QUOTA_LIST.append (Quota(quota_data))
|
|
|
|
except Exception:
|
|
|
|
logger.warning(f"[QUOTAS] Error while loading quotas.\n{traceback.format_exc()}")
|
|
|
|
success = False
|
|
|
|
return success
|
|
|
|
|
2023-01-17 21:25:35 +00:00
|
|
|
async def get_order(request: Request=None):
|
|
|
|
await request.receive_body()
|
|
|
|
return await request.app.ctx.om.get_order(request=request)
|
2023-01-08 20:23:39 +00:00
|
|
|
|
2023-01-17 21:25:35 +00:00
|
|
|
class OrderManager:
|
|
|
|
def __init__(self):
|
2023-12-30 10:27:42 +00:00
|
|
|
self.lastCacheUpdate = 0
|
2024-02-22 18:15:33 +00:00
|
|
|
self.updating : Lock = Lock()
|
2023-12-30 10:27:42 +00:00
|
|
|
self.empty()
|
|
|
|
|
|
|
|
def empty(self):
|
2023-01-17 21:25:35 +00:00
|
|
|
self.cache = {}
|
|
|
|
self.order_list = []
|
|
|
|
|
2024-01-21 23:35:44 +00:00
|
|
|
# Will fill cache once the last cache update is greater than cache expire time
|
2024-02-22 18:15:33 +00:00
|
|
|
async def update_cache(self, check_itemsQuestions=False):
|
2023-12-30 10:27:42 +00:00
|
|
|
t = time()
|
2024-01-21 23:35:44 +00:00
|
|
|
to_return = False
|
2024-02-22 18:15:33 +00:00
|
|
|
success = True
|
|
|
|
if(t - self.lastCacheUpdate > CACHE_EXPIRE_TIME and not self.updating.locked()):
|
2024-01-21 23:35:44 +00:00
|
|
|
to_return = True
|
2024-02-22 18:15:33 +00:00
|
|
|
success = await self.fill_cache(check_itemsQuestions=check_itemsQuestions)
|
|
|
|
return (to_return, success)
|
|
|
|
|
|
|
|
def add_cache(self, order, cache=None, orderList=None):
|
|
|
|
# Extra params for dry runs
|
|
|
|
if(cache is None):
|
|
|
|
cache = self.cache
|
|
|
|
if(orderList is None):
|
|
|
|
orderList = self.order_list
|
|
|
|
|
|
|
|
cache[order.code] = order
|
|
|
|
if not order.code in orderList:
|
|
|
|
orderList.append(order.code)
|
2023-12-30 10:27:42 +00:00
|
|
|
|
2024-02-22 18:15:33 +00:00
|
|
|
def remove_cache(self, code, cache=None, orderList=None):
|
|
|
|
# Extra params for dry runs
|
|
|
|
if(cache is None):
|
|
|
|
cache = self.cache
|
|
|
|
if(orderList is None):
|
|
|
|
orderList = self.order_list
|
2023-01-17 21:25:35 +00:00
|
|
|
|
2024-02-22 18:15:33 +00:00
|
|
|
if code in cache:
|
|
|
|
del cache[code]
|
|
|
|
orderList.remove(code)
|
2023-01-17 21:25:35 +00:00
|
|
|
|
2024-05-31 15:00:27 +00:00
|
|
|
|
2024-02-22 18:15:33 +00:00
|
|
|
async def fill_cache(self, check_itemsQuestions=False) -> bool:
|
2024-01-21 23:35:44 +00:00
|
|
|
# Check cache lock
|
2024-05-31 15:00:27 +00:00
|
|
|
logger.info(f"[CACHE] Lock status: {self.updating.locked()}")
|
2024-02-22 18:15:33 +00:00
|
|
|
self.updating.acquire()
|
2024-05-31 15:00:27 +00:00
|
|
|
ret = False
|
|
|
|
exp = None
|
|
|
|
try:
|
|
|
|
ret = await self.fill_cache_INTERNAL(check_itemsQuestions=check_itemsQuestions)
|
|
|
|
except Exception as e:
|
|
|
|
exp = e
|
|
|
|
self.updating.release()
|
|
|
|
logger.info(f"[CACHE] Ret status: {ret}. Exp: {exp}")
|
|
|
|
if(exp != None):
|
|
|
|
raise exp
|
|
|
|
return ret
|
|
|
|
|
|
|
|
async def fill_cache_INTERNAL(self, check_itemsQuestions=False) -> bool:
|
2024-01-21 23:35:44 +00:00
|
|
|
start_time = time()
|
|
|
|
logger.info("[CACHE] Filling cache...")
|
|
|
|
# Index item's ids
|
2024-02-22 18:15:33 +00:00
|
|
|
r = await load_items()
|
|
|
|
if(not r and check_itemsQuestions):
|
|
|
|
logger.error("[CACHE] Items were not loading correctly. Aborting filling cache...")
|
|
|
|
return False
|
2024-01-21 23:35:44 +00:00
|
|
|
|
|
|
|
# Index questions' types
|
2024-02-22 18:15:33 +00:00
|
|
|
r = await load_questions()
|
|
|
|
if(not r and check_itemsQuestions):
|
|
|
|
logger.error("[CACHE] Questions were not loading correctly. Aborting filling cache...")
|
|
|
|
return False
|
2024-01-21 23:35:44 +00:00
|
|
|
|
2024-05-19 19:07:31 +00:00
|
|
|
# Load quotas
|
|
|
|
r = await load_item_quotas()
|
|
|
|
if(not r and check_itemsQuestions):
|
|
|
|
logger.error("[CACHE] Quotas were not loading correctly. Aborting filling cache...")
|
|
|
|
return False
|
|
|
|
|
2024-02-22 18:15:33 +00:00
|
|
|
cache = {}
|
|
|
|
orderList = []
|
|
|
|
success = True
|
2023-07-04 21:07:39 +00:00
|
|
|
p = 0
|
2024-01-21 23:35:44 +00:00
|
|
|
try:
|
2024-02-22 18:15:33 +00:00
|
|
|
while 1:
|
|
|
|
p += 1
|
|
|
|
res = await pretixClient.get(f"orders/?page={p}", expectedStatusCodes=[200, 404])
|
|
|
|
if res.status_code == 404: break
|
|
|
|
# Parse order data
|
|
|
|
data = res.json()
|
|
|
|
for o in data['results']:
|
|
|
|
o = Order(o)
|
|
|
|
if o.status in ['canceled', 'expired']:
|
|
|
|
self.remove_cache(o.code, cache=cache, orderList=orderList)
|
|
|
|
else:
|
|
|
|
self.add_cache(Order(o), cache=cache, orderList=orderList)
|
|
|
|
self.lastCacheUpdate = time()
|
|
|
|
logger.info(f"[CACHE] Cache filled in {self.lastCacheUpdate - start_time}s.")
|
|
|
|
except Exception:
|
|
|
|
logger.error(f"[CACHE] Error while refreshing cache.\n{traceback.format_exc()}")
|
|
|
|
success = False
|
|
|
|
|
|
|
|
# Apply new cache if there were no errors
|
|
|
|
if(success):
|
|
|
|
self.cache = cache
|
|
|
|
self.order_list = orderList
|
|
|
|
|
2024-01-21 23:35:44 +00:00
|
|
|
# Validating rooms
|
|
|
|
rooms = list(filter(lambda o: (o.code == o.room_id), self.cache.values()))
|
|
|
|
asyncio.create_task(validate_rooms(None, rooms, self))
|
2024-02-22 18:15:33 +00:00
|
|
|
|
|
|
|
return success
|
2024-05-19 19:07:31 +00:00
|
|
|
|
2023-07-04 21:07:39 +00:00
|
|
|
async def get_order(self, request=None, code=None, secret=None, nfc_id=None, cached=False):
|
2023-01-17 21:25:35 +00:00
|
|
|
|
2023-07-04 21:07:39 +00:00
|
|
|
# if it's a nfc id, just retorn it
|
|
|
|
if nfc_id:
|
|
|
|
for order in self.cache.values():
|
|
|
|
if order.nfc_id == nfc_id:
|
|
|
|
return order
|
|
|
|
|
2024-01-21 23:35:44 +00:00
|
|
|
await self.update_cache()
|
2023-01-17 21:25:35 +00:00
|
|
|
# If a cached order is needed, just get it if available
|
2023-01-19 16:03:38 +00:00
|
|
|
if code and cached and code in self.cache and time()-self.cache[code].time < 3600:
|
2023-01-17 21:25:35 +00:00
|
|
|
return self.cache[code]
|
|
|
|
|
|
|
|
# If it's a request, ignore all the other parameters and just get the order of the requestor
|
|
|
|
if request:
|
|
|
|
code = request.cookies.get("foxo_code")
|
|
|
|
secret = request.cookies.get("foxo_secret")
|
2022-12-18 16:40:39 +00:00
|
|
|
|
2023-01-17 21:25:35 +00:00
|
|
|
if re.match('^[A-Z0-9]{5}$', code or '') and (secret is None or re.match('^[a-z0-9]{16,}$', secret)):
|
2024-01-21 23:35:44 +00:00
|
|
|
if DEV_MODE and EXTRA_PRINTS: logger.debug(f'Fetching {code} with secret {secret}')
|
2023-01-17 21:25:35 +00:00
|
|
|
|
2024-02-22 18:15:33 +00:00
|
|
|
res = await pretixClient.get(f"orders/{code}/", expectedStatusCodes=None)
|
|
|
|
if res.status_code != 200:
|
|
|
|
if request:
|
|
|
|
raise exceptions.Forbidden("Your session has expired due to order deletion or change! Please check your E-Mail for more info.")
|
2023-05-08 20:22:07 +00:00
|
|
|
else:
|
2024-02-22 18:15:33 +00:00
|
|
|
self.remove_cache(code)
|
|
|
|
return None
|
|
|
|
|
|
|
|
res = res.json()
|
|
|
|
|
|
|
|
order = Order(res)
|
|
|
|
if order.status in ['canceled', 'expired']:
|
|
|
|
self.remove_cache(order.code)
|
|
|
|
if request:
|
|
|
|
raise exceptions.Forbidden(f"Your order has been deleted. Contact support with your order identifier ({res['code']}) for further info.")
|
|
|
|
else:
|
|
|
|
self.add_cache(order)
|
|
|
|
|
|
|
|
if request and secret != res['secret']:
|
|
|
|
raise exceptions.Forbidden("Your session has expired due to a token change. Please check your E-Mail for an updated link!")
|
2024-05-19 19:07:31 +00:00
|
|
|
return order
|