Digitale bierlijst

model.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. """
  2. Provides access to the models stored in the database, via the server.
  3. """
  4. import datetime
  5. import logging
  6. from typing import NamedTuple
  7. from urllib.parse import urljoin
  8. import requests
  9. LOG = logging.getLogger(__name__)
  10. SERVER_URL = "http://127.0.0.1:5000"
  11. class ServerStatus:
  12. """ Provides helper classes to check whether the server is up. """
  13. @classmethod
  14. def is_server_running(cls) -> bool:
  15. try:
  16. req = requests.get(urljoin(SERVER_URL, "ping"))
  17. if req.status_code == 200:
  18. return True, req.content
  19. return False, req.content
  20. except requests.ConnectionError as ex:
  21. return False, ex
  22. datetime_format = "%Y-%m-%dT%H:%M:%S.%f"
  23. @classmethod
  24. def unsettled_consumptions(cls) -> dict:
  25. req = requests.get(urljoin(SERVER_URL, "status"))
  26. data = req.json()
  27. if data["unsettled"]["amount"]:
  28. data["unsettled"]["first"] = datetime.datetime.strptime(
  29. data["unsettled"]["first"], cls.datetime_format
  30. )
  31. data["unsettled"]["last"] = datetime.datetime.strptime(
  32. data["unsettled"]["last"], cls.datetime_format
  33. )
  34. return data
  35. class Person(NamedTuple):
  36. """ Represents a Person, as retrieved from the database. """
  37. name: str
  38. active: bool
  39. person_id: int = None
  40. consumptions: dict = {}
  41. def add_consumption(self, type_id: str) -> bool:
  42. """ Register a consumption for this Person. """
  43. req = requests.post(
  44. urljoin(SERVER_URL, f"people/{self.person_id}/add_consumption/{type_id}")
  45. )
  46. try:
  47. data = req.json()
  48. if "error" in data:
  49. LOG.error(
  50. "Could not add consumption for %s (%s): %s",
  51. self.person_id,
  52. req.status_code,
  53. data,
  54. )
  55. return False
  56. self.consumptions.update(data["person"]["consumptions"])
  57. return Consumption.from_dict(data["consumption"])
  58. except ValueError:
  59. LOG.error(
  60. "Did not get JSON on adding Consumption (%s): %s",
  61. req.status_code,
  62. req.content,
  63. )
  64. return False
  65. def create(self) -> "Person":
  66. """ Create a new Person from the current attributes. As tuples are
  67. immutable, a new Person with the correct id is returned. """
  68. req = requests.post(
  69. urljoin(SERVER_URL, "people"),
  70. json={"person": {"name": self.name, "active": True}},
  71. )
  72. try:
  73. data = req.json()
  74. except ValueError:
  75. LOG.error(
  76. "Did not get JSON on adding Person (%s): %s",
  77. req.status_code,
  78. req.content,
  79. )
  80. return None
  81. if "error" in data or req.status_code != 201:
  82. LOG.error("Could not create Person (%s): %s", req.status_code, data)
  83. return None
  84. return Person.from_dict(data["person"])
  85. def set_active(self, new_state=True) -> "Person":
  86. req = requests.patch(
  87. urljoin(SERVER_URL, f"people/{self.person_id}"),
  88. json={"person": {"active": new_state}},
  89. )
  90. try:
  91. data = req.json()
  92. except ValueError:
  93. LOG.error(
  94. "Did not get JSON on updating Person (%s): %s",
  95. req.status_code,
  96. req.content,
  97. )
  98. return None
  99. if "error" in data or req.status_code != 200:
  100. LOG.error("Could not update Person (%s): %s", req.status_code, data)
  101. return None
  102. return Person.from_dict(data["person"])
  103. @classmethod
  104. def get(cls, person_id: int) -> "Person":
  105. """ Retrieve a Person by id. """
  106. req = requests.get(urljoin(SERVER_URL, f"/people/{person_id}"))
  107. try:
  108. data = req.json()
  109. if "error" in data:
  110. LOG.warning(
  111. "Could not get person %s (%s): %s", person_id, req.status_code, data
  112. )
  113. return None
  114. return Person.from_dict(data["person"])
  115. except ValueError:
  116. LOG.error(
  117. "Did not get JSON from server on getting Person (%s): %s",
  118. req.status_code,
  119. req.content,
  120. )
  121. return None
  122. @classmethod
  123. def get_all(cls, active=None) -> ["Person"]:
  124. """ Get all active People. """
  125. params = {}
  126. if active is not None:
  127. params["active"] = int(active)
  128. req = requests.get(urljoin(SERVER_URL, "/people"), params=params)
  129. try:
  130. data = req.json()
  131. if "error" in data:
  132. LOG.warning("Could not get people (%s): %s", req.status_code, data)
  133. return [Person.from_dict(item) for item in data["people"]]
  134. except ValueError:
  135. LOG.error(
  136. "Did not get JSON from server on getting People (%s): %s",
  137. req.status_code,
  138. req.content,
  139. )
  140. return None
  141. @classmethod
  142. def from_dict(cls, data: dict) -> "Person":
  143. """ Reconstruct a Person object from a dict. """
  144. return Person(
  145. name=data["name"],
  146. active=data["active"],
  147. person_id=data["person_id"],
  148. consumptions=data["consumptions"],
  149. )
  150. class ConsumptionType(NamedTuple):
  151. """ Represents a stored ConsumptionType. """
  152. name: str
  153. consumption_type_id: int = None
  154. icon: str = None
  155. def create(self) -> "ConsumptionType":
  156. """ Create a new ConsumptionType from the current attributes. As tuples
  157. are immutable, a new ConsumptionType with the correct id is returned.
  158. """
  159. req = requests.post(
  160. urljoin(SERVER_URL, "consumption_types"),
  161. json={"consumption_type": {"name": self.name, "icon": self.icon}},
  162. )
  163. try:
  164. data = req.json()
  165. except ValueError:
  166. LOG.error(
  167. "Did not get JSON on adding ConsumptionType (%s): %s",
  168. req.status_code,
  169. req.content,
  170. )
  171. return None
  172. if "error" in data or req.status_code != 201:
  173. LOG.error(
  174. "Could not create ConsumptionType (%s): %s", req.status_code, data
  175. )
  176. return None
  177. return ConsumptionType.from_dict(data["consumption_type"])
  178. @classmethod
  179. def get(cls, consumption_type_id: int) -> "ConsumptionType":
  180. """ Retrieve a ConsumptionType by id. """
  181. req = requests.get(
  182. urljoin(SERVER_URL, f"/consumption_types/{consumption_type_id}")
  183. )
  184. try:
  185. data = req.json()
  186. if "error" in data:
  187. LOG.warning(
  188. "Could not get consumption type %s (%s): %s",
  189. consumption_type_id,
  190. req.status_code,
  191. data,
  192. )
  193. return None
  194. return cls.from_dict(data["consumption_type"])
  195. except ValueError:
  196. LOG.error(
  197. "Did not get JSON from server on getting consumption type (%s): %s",
  198. req.status_code,
  199. req.content,
  200. )
  201. return None
  202. @classmethod
  203. def get_all(cls) -> ["ConsumptionType"]:
  204. """ Get all active ConsumptionTypes. """
  205. req = requests.get(urljoin(SERVER_URL, "/consumption_types"))
  206. try:
  207. data = req.json()
  208. if "error" in data:
  209. LOG.warning(
  210. "Could not get consumption types (%s): %s", req.status_code, data
  211. )
  212. return [cls.from_dict(item) for item in data["consumption_types"]]
  213. except ValueError:
  214. LOG.error(
  215. "Did not get JSON from server on getting ConsumptionTypes (%s): %s",
  216. req.status_code,
  217. req.content,
  218. )
  219. return None
  220. @classmethod
  221. def from_dict(cls, data: dict) -> "ConsumptionType":
  222. """ Reconstruct a ConsumptionType from a dict. """
  223. return cls(
  224. name=data["name"],
  225. consumption_type_id=data["consumption_type_id"],
  226. icon=data.get("icon"),
  227. )
  228. class Consumption(NamedTuple):
  229. """ Represents a stored Consumption. """
  230. consumption_id: int
  231. person_id: int
  232. consumption_type_id: int
  233. created_at: datetime.datetime
  234. reversed: bool = False
  235. settlement_id: int = None
  236. @classmethod
  237. def from_dict(cls, data: dict) -> "Consumption":
  238. """ Reconstruct a Consumption from a dict. """
  239. datetime_format = "%Y-%m-%dT%H:%M:%S.%f"
  240. # 2018-08-31T17:30:47.871521
  241. return cls(
  242. consumption_id=data["consumption_id"],
  243. person_id=data["person_id"],
  244. consumption_type_id=data["consumption_type_id"],
  245. settlement_id=data["settlement_id"],
  246. created_at=datetime.datetime.strptime(data["created_at"], datetime_format),
  247. reversed=data["reversed"],
  248. )
  249. def reverse(self) -> "Consumption":
  250. """ Reverse this consumption. """
  251. req = requests.delete(
  252. urljoin(SERVER_URL, f"/consumptions/{self.consumption_id}")
  253. )
  254. try:
  255. data = req.json()
  256. if "error" in data:
  257. LOG.error(
  258. "Could not reverse consumption %s (%s): %s",
  259. self.consumption_id,
  260. req.status_code,
  261. data,
  262. )
  263. return False
  264. return Consumption.from_dict(data["consumption"])
  265. except ValueError:
  266. LOG.error(
  267. "Did not get JSON on reversing Consumption (%s): %s",
  268. req.status_code,
  269. req.content,
  270. )
  271. return False
  272. class Settlement(NamedTuple):
  273. """ Represents a stored Settlement. """
  274. settlement_id: int
  275. name: str
  276. consumption_summary: dict
  277. @classmethod
  278. def from_dict(cls, data: dict) -> "Settlement":
  279. return Settlement(
  280. settlement_id=data["settlement_id"],
  281. name=data["name"],
  282. consumption_summary=data["consumption_summary"],
  283. )
  284. @classmethod
  285. def create(cls, name: str) -> "Settlement":
  286. req = requests.post(
  287. urljoin(SERVER_URL, "/settlements"), json={"settlement": {"name": name}}
  288. )
  289. return cls.from_dict(req.json()["settlement"])