Digitale bierlijst

model.py 10KB

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