Digitale bierlijst

model.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. """
  2. Provides access to the models stored in the database, via the server.
  3. """
  4. from __future__ import annotations
  5. import datetime
  6. import enum
  7. import logging
  8. from dataclasses import dataclass
  9. from typing import Any, Dict, List, NamedTuple, Optional, Sequence, Tuple, Union
  10. from urllib.parse import urljoin
  11. import requests
  12. LOG = logging.getLogger(__name__)
  13. SERVER_URL = "http://127.0.0.1:5000"
  14. DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
  15. class NetworkError(enum.Enum):
  16. """Represents errors that might occur when communicating with the server."""
  17. HttpFailure = "http_failure"
  18. """Returned when the server returns a non-successful status code."""
  19. ConnectionFailure = "connection_failure"
  20. """Returned when we can't connect to the server at all."""
  21. InvalidData = "invalid_data"
  22. class ServerStatus:
  23. """ Provides helper classes to check whether the server is up. """
  24. @classmethod
  25. def is_server_running(cls) -> Union[bool, NetworkError]:
  26. try:
  27. req = requests.get(urljoin(SERVER_URL, "ping"))
  28. req.raise_for_status()
  29. except requests.ConnectionError as ex:
  30. LOG.exception(ex)
  31. return NetworkError.ConnectionFailure
  32. except requests.HTTPError as ex:
  33. LOG.exception(ex)
  34. return NetworkError.HttpFailure
  35. return True
  36. @dataclass(frozen=True)
  37. class OpenConsumptions:
  38. amount: int
  39. first_timestamp: Optional[datetime.datetime]
  40. last_timestamp: Optional[datetime.datetime]
  41. @classmethod
  42. def unsettled_consumptions(cls) -> Union[OpenConsumptions, NetworkError]:
  43. try:
  44. req = requests.get(urljoin(SERVER_URL, "status"))
  45. req.raise_for_status()
  46. data = req.json()
  47. except requests.ConnectionError as e:
  48. LOG.exception(e)
  49. return NetworkError.ConnectionFailure
  50. except requests.HTTPError as e:
  51. LOG.exception(e)
  52. return NetworkError.HttpFailure
  53. except ValueError as e:
  54. LOG.exception(e)
  55. return NetworkError.InvalidData
  56. amount: int = data["unsettled"]["amount"]
  57. if amount == 0:
  58. return cls.OpenConsumptions(
  59. amount=0, first_timestamp=None, last_timestamp=None
  60. )
  61. first = datetime.datetime.fromisoformat(data["unsettled"]["first"])
  62. last = datetime.datetime.fromisoformat(data["unsettled"]["last"])
  63. return cls.OpenConsumptions(
  64. amount=amount, first_timestamp=first, last_timestamp=last
  65. )
  66. class Person(NamedTuple):
  67. """ Represents a Person, as retrieved from the database. """
  68. full_name: str
  69. display_name: Optional[str]
  70. active: bool = True
  71. person_id: Optional[int] = None
  72. consumptions: dict = {}
  73. @property
  74. def name(self) -> str:
  75. return self.display_name or self.full_name
  76. def add_consumption(self, type_id: str) -> Optional[Consumption]:
  77. """ Register a consumption for this Person. """
  78. req = requests.post(
  79. urljoin(SERVER_URL, f"people/{self.person_id}/add_consumption/{type_id}")
  80. )
  81. try:
  82. data = req.json()
  83. if "error" in data:
  84. LOG.error(
  85. "Could not add consumption for %s (%s): %s",
  86. self.person_id,
  87. req.status_code,
  88. data,
  89. )
  90. return None
  91. self.consumptions.update(data["person"]["consumptions"])
  92. return Consumption.from_dict(data["consumption"])
  93. except ValueError:
  94. LOG.error(
  95. "Did not get JSON on adding Consumption (%s): %s",
  96. req.status_code,
  97. req.content,
  98. )
  99. return None
  100. def create(self) -> Union[Person, NetworkError]:
  101. """ Create a new Person from the current attributes. As tuples are
  102. immutable, a new Person with the correct id is returned. """
  103. try:
  104. req = requests.post(
  105. urljoin(SERVER_URL, "people"),
  106. json={
  107. "person": {
  108. "full_name": self.full_name,
  109. "display_name": self.display_name,
  110. "active": True,
  111. }
  112. },
  113. )
  114. req.raise_for_status()
  115. data = req.json()
  116. return Person.from_dict(data["person"])
  117. except requests.ConnectionError as e:
  118. LOG.exception(e)
  119. return NetworkError.ConnectionFailure
  120. except requests.HTTPError as e:
  121. LOG.exception(e)
  122. return NetworkError.HttpFailure
  123. except ValueError as e:
  124. LOG.exception(e)
  125. return NetworkError.InvalidData
  126. def set_active(self, new_state=True) -> Optional[Person]:
  127. req = requests.patch(
  128. urljoin(SERVER_URL, f"people/{self.person_id}"),
  129. json={"person": {"active": new_state}},
  130. )
  131. try:
  132. data = req.json()
  133. except ValueError:
  134. LOG.error(
  135. "Did not get JSON on updating Person (%s): %s",
  136. req.status_code,
  137. req.content,
  138. )
  139. return None
  140. if "error" in data or req.status_code != 200:
  141. LOG.error("Could not update Person (%s): %s", req.status_code, data)
  142. return None
  143. return Person.from_dict(data["person"])
  144. @classmethod
  145. def get(cls, person_id: int) -> Optional[Person]:
  146. """ Retrieve a Person by id. """
  147. req = requests.get(urljoin(SERVER_URL, f"/people/{person_id}"))
  148. try:
  149. data = req.json()
  150. if "error" in data:
  151. LOG.warning(
  152. "Could not get person %s (%s): %s", person_id, req.status_code, data
  153. )
  154. return None
  155. return Person.from_dict(data["person"])
  156. except ValueError:
  157. LOG.error(
  158. "Did not get JSON from server on getting Person (%s): %s",
  159. req.status_code,
  160. req.content,
  161. )
  162. return None
  163. @classmethod
  164. def get_all(cls, active=None) -> Union[List[Person], NetworkError]:
  165. """ Get all active People. """
  166. params = {}
  167. if active is not None:
  168. params["active"] = int(active)
  169. try:
  170. req = requests.get(urljoin(SERVER_URL, "/people"), params=params)
  171. req.raise_for_status()
  172. data = req.json()
  173. return [Person.from_dict(item) for item in data["people"]]
  174. except requests.ConnectionError as e:
  175. LOG.exception(e)
  176. return NetworkError.ConnectionFailure
  177. except requests.HTTPError as e:
  178. LOG.exception(e)
  179. return NetworkError.HttpFailure
  180. except ValueError as e:
  181. return NetworkError.InvalidData
  182. @classmethod
  183. def from_dict(cls, data: dict) -> "Person":
  184. """ Reconstruct a Person object from a dict. """
  185. return Person(
  186. full_name=data["full_name"],
  187. display_name=data["display_name"],
  188. active=data["active"],
  189. person_id=data["person_id"],
  190. consumptions=data["consumptions"],
  191. )
  192. class Export(NamedTuple):
  193. created_at: datetime.datetime
  194. settlement_ids: Sequence[int]
  195. export_id: int
  196. settlements: Sequence["Settlement"] = []
  197. @classmethod
  198. def from_dict(cls, data: dict) -> "Export":
  199. """ Reconstruct an Export from a dict. """
  200. return cls(
  201. export_id=data["export_id"],
  202. created_at=datetime.datetime.strptime(data["created_at"], DATETIME_FORMAT),
  203. settlement_ids=data["settlement_ids"],
  204. settlements=data.get("settlements", []),
  205. )
  206. @classmethod
  207. def get_all(cls) -> Optional[List[Export]]:
  208. """ Get a list of all existing Exports. """
  209. req = requests.get(urljoin(SERVER_URL, "exports"))
  210. try:
  211. data = req.json()
  212. except ValueError:
  213. LOG.error(
  214. "Did not get JSON on listing Exports (%s): %s",
  215. req.status_code,
  216. req.content,
  217. )
  218. return None
  219. if "error" in data or req.status_code != 200:
  220. LOG.error("Could not list Exports (%s): %s", req.status_code, data)
  221. return None
  222. return [cls.from_dict(e) for e in data["exports"]]
  223. @classmethod
  224. def get(cls, export_id: int) -> Optional[Export]:
  225. """ Retrieve one Export. """
  226. req = requests.get(urljoin(SERVER_URL, f"exports/{export_id}"))
  227. try:
  228. data = req.json()
  229. except ValueError:
  230. LOG.error(
  231. "Did not get JSON on getting Export (%s): %s",
  232. req.status_code,
  233. req.content,
  234. )
  235. return None
  236. if "error" in data or req.status_code != 200:
  237. LOG.error("Could not get Export (%s): %s", req.status_code, data)
  238. return None
  239. data["export"]["settlements"] = data["settlements"]
  240. return cls.from_dict(data["export"])
  241. @classmethod
  242. def create(cls) -> Optional[Export]:
  243. """ Create a new Export, containing all un-exported Settlements. """
  244. req = requests.post(urljoin(SERVER_URL, "exports"))
  245. try:
  246. data = req.json()
  247. except ValueError:
  248. LOG.error(
  249. "Did not get JSON on adding Export (%s): %s",
  250. req.status_code,
  251. req.content,
  252. )
  253. return None
  254. if "error" in data or req.status_code != 201:
  255. LOG.error("Could not create Export (%s): %s", req.status_code, data)
  256. return None
  257. data["export"]["settlements"] = data["settlements"]
  258. return cls.from_dict(data["export"])
  259. class ConsumptionType(NamedTuple):
  260. """ Represents a stored ConsumptionType. """
  261. name: str
  262. consumption_type_id: Optional[int] = None
  263. icon: Optional[str] = None
  264. active: bool = True
  265. def create(self) -> Union[ConsumptionType, NetworkError]:
  266. """ Create a new ConsumptionType from the current attributes. As tuples
  267. are immutable, a new ConsumptionType with the correct id is returned.
  268. """
  269. try:
  270. req = requests.post(
  271. urljoin(SERVER_URL, "consumption_types"),
  272. json={"consumption_type": {"name": self.name, "icon": self.icon}},
  273. )
  274. req.raise_for_status()
  275. data = req.json()
  276. return ConsumptionType.from_dict(data["consumption_type"])
  277. except requests.ConnectionError as e:
  278. LOG.exception(e)
  279. return NetworkError.ConnectionFailure
  280. except requests.HTTPError as e:
  281. LOG.exception(e)
  282. return NetworkError.HttpFailure
  283. except ValueError as e:
  284. LOG.exception(e)
  285. return NetworkError.InvalidData
  286. @classmethod
  287. def get(cls, consumption_type_id: int) -> Union[ConsumptionType, NetworkError]:
  288. """ Retrieve a ConsumptionType by id. """
  289. try:
  290. req = requests.get(
  291. urljoin(SERVER_URL, f"/consumption_types/{consumption_type_id}")
  292. )
  293. req.raise_for_status()
  294. data = req.json()
  295. except requests.ConnectionError as e:
  296. LOG.exception(e)
  297. return NetworkError.ConnectionFailure
  298. except requests.HTTPError as e:
  299. LOG.exception(e)
  300. return NetworkError.HttpFailure
  301. except ValueError as e:
  302. LOG.exception(e)
  303. return NetworkError.InvalidData
  304. return cls.from_dict(data["consumption_type"])
  305. @classmethod
  306. def get_all(cls, active: bool = True) -> Union[List[ConsumptionType], NetworkError]:
  307. """ Get the list of ConsumptionTypes. """
  308. try:
  309. req = requests.get(
  310. urljoin(SERVER_URL, "/consumption_types"),
  311. params={"active": int(active)},
  312. )
  313. req.raise_for_status()
  314. data = req.json()
  315. except requests.ConnectionError as e:
  316. LOG.exception(e)
  317. return NetworkError.ConnectionFailure
  318. except requests.HTTPError as e:
  319. LOG.exception(e)
  320. return NetworkError.HttpFailure
  321. except ValueError as e:
  322. LOG.exception(e)
  323. return NetworkError.InvalidData
  324. return [cls.from_dict(x) for x in data["consumption_types"]]
  325. @classmethod
  326. def from_dict(cls, data: dict) -> "ConsumptionType":
  327. """ Reconstruct a ConsumptionType from a dict. """
  328. return cls(
  329. name=data["name"],
  330. consumption_type_id=data["consumption_type_id"],
  331. icon=data.get("icon"),
  332. active=data["active"],
  333. )
  334. def set_active(self, active: bool) -> Union[ConsumptionType, NetworkError]:
  335. """Update the 'active' attribute."""
  336. try:
  337. req = requests.patch(
  338. urljoin(SERVER_URL, f"/consumption_types/{self.consumption_type_id}"),
  339. json={"consumption_type": {"active": active}},
  340. )
  341. req.raise_for_status()
  342. data = req.json()
  343. except requests.ConnectionError as e:
  344. LOG.exception(e)
  345. return NetworkError.ConnectionFailure
  346. except requests.HTTPError as e:
  347. LOG.exception(e)
  348. return NetworkError.HttpFailure
  349. except ValueError as e:
  350. LOG.exception(e)
  351. return NetworkError.InvalidData
  352. return self.from_dict(data["consumption_type"])
  353. class Consumption(NamedTuple):
  354. """ Represents a stored Consumption. """
  355. consumption_id: int
  356. person_id: int
  357. consumption_type_id: int
  358. created_at: datetime.datetime
  359. reversed: bool = False
  360. settlement_id: Optional[int] = None
  361. @classmethod
  362. def from_dict(cls, data: dict) -> "Consumption":
  363. """ Reconstruct a Consumption from a dict. """
  364. return cls(
  365. consumption_id=data["consumption_id"],
  366. person_id=data["person_id"],
  367. consumption_type_id=data["consumption_type_id"],
  368. settlement_id=data["settlement_id"],
  369. created_at=datetime.datetime.strptime(data["created_at"], DATETIME_FORMAT),
  370. reversed=data["reversed"],
  371. )
  372. def reverse(self) -> Optional[Consumption]:
  373. """ Reverse this consumption. """
  374. req = requests.delete(
  375. urljoin(SERVER_URL, f"/consumptions/{self.consumption_id}")
  376. )
  377. try:
  378. data = req.json()
  379. if "error" in data:
  380. LOG.error(
  381. "Could not reverse consumption %s (%s): %s",
  382. self.consumption_id,
  383. req.status_code,
  384. data,
  385. )
  386. return None
  387. return Consumption.from_dict(data["consumption"])
  388. except ValueError:
  389. LOG.error(
  390. "Did not get JSON on reversing Consumption (%s): %s",
  391. req.status_code,
  392. req.content,
  393. )
  394. return None
  395. class Settlement(NamedTuple):
  396. """ Represents a stored Settlement. """
  397. settlement_id: int
  398. name: str
  399. consumption_summary: Dict[str, Any]
  400. count_info: Dict[str, Any] = {}
  401. per_person_counts: Dict[str, Any] = {}
  402. @classmethod
  403. def from_dict(cls, data: dict) -> "Settlement":
  404. return Settlement(
  405. settlement_id=data["settlement_id"],
  406. name=data["name"],
  407. consumption_summary=data["consumption_summary"],
  408. count_info=data["count_info"],
  409. per_person_counts=data["per_person_counts"],
  410. )
  411. @classmethod
  412. def create(cls, name: str) -> "Settlement":
  413. req = requests.post(
  414. urljoin(SERVER_URL, "/settlements"), json={"settlement": {"name": name}}
  415. )
  416. return cls.from_dict(req.json()["settlement"])
  417. @classmethod
  418. def get(cls, settlement_id: int) -> Union[Settlement, NetworkError]:
  419. try:
  420. req = requests.get(urljoin(SERVER_URL, f"/settlements/{settlement_id}"))
  421. req.raise_for_status()
  422. data = req.json()
  423. except ValueError as e:
  424. LOG.exception(e)
  425. return NetworkError.InvalidData
  426. except requests.ConnectionError as e:
  427. LOG.exception(e)
  428. return NetworkError.ConnectionFailure
  429. except requests.HTTPError as e:
  430. LOG.exception(e)
  431. return NetworkError.HttpFailure
  432. data["settlement"]["count_info"] = data["count_info"]
  433. return cls.from_dict(data["settlement"])