reimplemented openMensaFeedv2 and fixed linting

This commit is contained in:
Hadrian Burkhardt
2023-12-03 02:51:47 +01:00
committed by f4lco
parent 9e37940334
commit d637d71c8f
16 changed files with 632 additions and 598 deletions
+47 -83
View File
@@ -1,63 +1,43 @@
import logging
from datetime import datetime
from stw_potsdam.builder import Builder
from stw_potsdam.swp_webspeiseplan_api import SWP_Webspeiseplan_API
from datetime import datetime, date
from stw_potsdam.xml_types.canteen_xml import CanteenMeta, CanteenXML
from stw_potsdam.xml_types.times_xml import TimesXML
from stw_potsdam.xml_types.meal_xml import MealXML
class SWP_Webspeiseplan_Parser:
class SWPWebspeiseplanParser:
"""Class method to parse SWP_Webspeiseplan."""
def __init__(
self,
menu_data: list[dict],
meal_categories: list[dict],
outlet_data: dict,
url: str,
):
"""Initialize the parser .
Args:
menu_data (list[dict]): [description]
meal_categories (list[dict]): [description]
outlet_data (dict): [description]
url (str): [description]
"""
def __init__(self) -> None:
"""Init SWPWebspeiseplanParser object."""
logging.basicConfig()
self.logger = logging.getLogger(__name__)
self.menu_data = menu_data
self.meal_categories = meal_categories
self.outlet_data = outlet_data
self.url = url
self._builder = Builder()
self.__parse_canteen(outlet_data)
self.__parse_feed()
self.__parse_meals()
def __parse_canteen(self, outlet: dict):
def parse_canteen_meta_times(self, outlet: dict):
"""Parse the outlet data from outlet.
Args:
outlet (dict): [description]
"""
canteen = self._builder
canteen.name = outlet["name"]
canteen.address = (
outlet["addressInfo"]["street"],
outlet["addressInfo"]["postalCode"],
outlet["addressInfo"]["city"],
)
canteen.city = outlet["addressInfo"]["city"]
canteen.phone = outlet["contactInfo"][0]["phone"]
canteen.email = outlet["contactInfo"][0]["email"]
self.logger.debug("parse_canteen_meta_times(): %s", outlet["name"])
addr_info = outlet["addressInfo"]
meta = {
"name": outlet["name"],
"address": f'{addr_info["street"]}, {addr_info["postalCode"]} '
+ f'{addr_info["city"]}',
"city": addr_info["city"],
"phone": outlet["contactInfo"][0]["phone"],
"email": outlet["contactInfo"][0]["email"],
}
if outlet["positionInfo"]:
canteen.location = (
meta["location"] = (
outlet["positionInfo"]["longitude"],
outlet["positionInfo"]["latitude"],
)
canteen_meta = CanteenMeta(**meta)
# TODO: availability via locations isPublic
times = {
weekday_dict = {
"monday": f"{outlet['moZeit1']}, {outlet['moZeit2']}",
"tuesday": f"{outlet['diZeit1']}, {outlet['diZeit2']}",
"wednesday": f"{outlet['miZeit1']}, {outlet['miZeit2']}",
@@ -67,52 +47,36 @@ class SWP_Webspeiseplan_Parser:
"sunday": f"{outlet['soZeit1']}, {outlet['soZeit2']}",
}
times = {
weekday_dict = {
k: v.replace("None, None", "")
.replace("None,", "")
.replace(", None", "")
for k, v in times.items()
for k, v in weekday_dict.items()
}
canteen.times = times
canteen_times = TimesXML(weekday_dict)
canteen = CanteenXML(canteen_meta, canteen_times)
return canteen
def __parse_feed(self):
"""Parse feed and set feed."""
feed = {
"name": "full",
"priority": 0,
"hour": "8-14",
"retry": "30 1",
"url": self.url,
"source": SWP_Webspeiseplan_API.URL_BASE,
}
self._builder.feed = feed
def __parse_meals(self):
def parse_meals(
self, menu_data, meal_categories
) -> list[tuple[date, str, MealXML]]:
"""Parse the menu and adds it to the builder."""
for menu in self.menu_data:
for meal in menu["speiseplanGerichtData"]:
info = meal["speiseplanAdvancedGericht"]
date = datetime.fromisoformat(info["datum"]).date()
additional_info = meal["zusatzinformationen"]
self._builder.add_meal(
date=date,
category=self.meal_categories[info["gerichtkategorieID"]][
"name"
],
name=info["gerichtname"],
prices={
"student": additional_info["mitarbeiterpreisDecimal2"],
"employee": additional_info["price3Decimal2"],
"other": additional_info["gaestepreisDecimal2"],
},
meals = []
for menu in menu_data:
for meal_data in menu["speiseplanGerichtData"]:
info = meal_data["speiseplanAdvancedGericht"]
additional_info = meal_data["zusatzinformationen"]
price = {
"student": additional_info["mitarbeiterpreisDecimal2"],
"employee": additional_info["price3Decimal2"],
"other": additional_info["gaestepreisDecimal2"],
}
meal = MealXML(name=info["gerichtname"], price=price)
day = datetime.fromisoformat(info["datum"]).date()
category = meal_categories[info["gerichtkategorieID"]]["name"]
meals.append(
{"day": day, "category": category, "meal": meal}
)
@property
def xml_feed(self):
"""Return the XML string of the builder.
Returns:
[type]: [description]
"""
return self._builder.toXML()
self.logger.debug("parse_meals(): %s meals parsed", len(meals))
return meals