Digitale bierlijst

__init__.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. """
  2. Piket server, handles events generated by the client.
  3. """
  4. import datetime
  5. import os
  6. from sqlalchemy.exc import SQLAlchemyError
  7. from sqlalchemy import func
  8. from flask import Flask, jsonify, abort, request
  9. from flask_sqlalchemy import SQLAlchemy
  10. DATA_HOME = os.environ.get("XDG_DATA_HOME", "~/.local/share")
  11. CONFIG_DIR = os.path.join(DATA_HOME, "piket_server")
  12. DB_PATH = os.path.expanduser(os.path.join(CONFIG_DIR, "database.sqlite3"))
  13. DB_URL = f"sqlite:///{DB_PATH}"
  14. app = Flask("piket_server")
  15. app.config["SQLALCHEMY_DATABASE_URI"] = DB_URL
  16. app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
  17. db = SQLAlchemy(app)
  18. # ---------- Models ----------
  19. class Person(db.Model):
  20. """ Represents a person to be shown on the lists. """
  21. __tablename__ = "people"
  22. person_id = db.Column(db.Integer, primary_key=True)
  23. name = db.Column(db.String, nullable=False)
  24. active = db.Column(db.Boolean, nullable=False, default=False)
  25. consumptions = db.relationship("Consumption", backref="person", lazy=True)
  26. def __repr__(self) -> str:
  27. return f"<Person {self.person_id}: {self.name}>"
  28. @property
  29. def as_dict(self) -> dict:
  30. return {
  31. "person_id": self.person_id,
  32. "active": self.active,
  33. "name": self.name,
  34. "consumptions": {
  35. ct.consumption_type_id: Consumption.query.filter_by(person=self)
  36. .filter_by(settlement=None)
  37. .filter_by(consumption_type=ct)
  38. .filter_by(reversed=False)
  39. .count()
  40. for ct in ConsumptionType.query.all()
  41. },
  42. }
  43. class Export(db.Model):
  44. """ Represents a set of exported Settlements. """
  45. __tablename__ = "exports"
  46. export_id = db.Column(db.Integer, primary_key=True)
  47. created_at = db.Column(
  48. db.DateTime, default=datetime.datetime.utcnow, nullable=False
  49. )
  50. settlements = db.relationship("Settlement", backref="export", lazy=True)
  51. @property
  52. def as_dict(self) -> dict:
  53. return {
  54. "export_id": self.export_id,
  55. "created_at": self.created_at.isoformat(),
  56. "settlement_ids": [s.settlement_id for s in self.settlements],
  57. }
  58. class Settlement(db.Model):
  59. """ Represents a settlement of the list. """
  60. __tablename__ = "settlements"
  61. settlement_id = db.Column(db.Integer, primary_key=True)
  62. name = db.Column(db.String, nullable=False)
  63. export_id = db.Column(db.Integer, db.ForeignKey("exports.export_id"), nullable=True)
  64. consumptions = db.relationship("Consumption", backref="settlement", lazy=True)
  65. def __repr__(self) -> str:
  66. return f"<Settlement {self.settlement_id}: {self.name}>"
  67. @property
  68. def as_dict(self) -> dict:
  69. return {
  70. "settlement_id": self.settlement_id,
  71. "name": self.name,
  72. "consumption_summary": self.consumption_summary,
  73. "unique_people": self.unique_people,
  74. }
  75. @property
  76. def unique_people(self) -> int:
  77. q = (
  78. Consumption.query.filter_by(settlement=self)
  79. .filter_by(reversed=False)
  80. .group_by(Consumption.person_id)
  81. .count()
  82. )
  83. return q
  84. @property
  85. def consumption_summary(self) -> dict:
  86. q = (
  87. Consumption.query.filter_by(settlement=self)
  88. .filter_by(reversed=False)
  89. .group_by(Consumption.consumption_type_id)
  90. .order_by(ConsumptionType.name)
  91. .outerjoin(ConsumptionType)
  92. .with_entities(
  93. Consumption.consumption_type_id,
  94. ConsumptionType.name,
  95. func.count(Consumption.consumption_id),
  96. )
  97. .all()
  98. )
  99. return {r[0]: {"name": r[1], "count": r[2]} for r in q}
  100. @property
  101. def per_person(self) -> dict:
  102. # Get keys of seen consumption_types
  103. c_types = self.consumption_summary.keys()
  104. result = {}
  105. for type in c_types:
  106. c_type = ConsumptionType.query.get(type)
  107. result[type] = {"consumption_type": c_type.as_dict, "counts": {}}
  108. q = (
  109. Consumption.query.filter_by(settlement=self)
  110. .filter_by(reversed=False)
  111. .filter_by(consumption_type=c_type)
  112. .group_by(Consumption.person_id)
  113. .order_by(Person.name)
  114. .outerjoin(Person)
  115. .with_entities(
  116. Person.person_id,
  117. Person.name,
  118. func.count(Consumption.consumption_id),
  119. )
  120. .all()
  121. )
  122. for row in q:
  123. result[type]["counts"][row[0]] = {"name": row[1], "count": row[2]}
  124. return result
  125. class ConsumptionType(db.Model):
  126. """ Represents a type of consumption to be counted. """
  127. __tablename__ = "consumption_types"
  128. consumption_type_id = db.Column(db.Integer, primary_key=True)
  129. name = db.Column(db.String, nullable=False)
  130. icon = db.Column(db.String)
  131. active = db.Column(db.Boolean, default=True)
  132. consumptions = db.relationship("Consumption", backref="consumption_type", lazy=True)
  133. def __repr__(self) -> str:
  134. return f"<ConsumptionType: {self.name}>"
  135. @property
  136. def as_dict(self) -> dict:
  137. return {
  138. "consumption_type_id": self.consumption_type_id,
  139. "name": self.name,
  140. "icon": self.icon,
  141. }
  142. class Consumption(db.Model):
  143. """ Represent one consumption to be counted. """
  144. __tablename__ = "consumptions"
  145. consumption_id = db.Column(db.Integer, primary_key=True)
  146. person_id = db.Column(db.Integer, db.ForeignKey("people.person_id"), nullable=True)
  147. consumption_type_id = db.Column(
  148. db.Integer,
  149. db.ForeignKey("consumption_types.consumption_type_id"),
  150. nullable=False,
  151. )
  152. settlement_id = db.Column(
  153. db.Integer, db.ForeignKey("settlements.settlement_id"), nullable=True
  154. )
  155. created_at = db.Column(
  156. db.DateTime, default=datetime.datetime.utcnow, nullable=False
  157. )
  158. reversed = db.Column(db.Boolean, default=False, nullable=False)
  159. def __repr__(self) -> str:
  160. return f"<Consumption: {self.consumption_type.name} for {self.person.name}>"
  161. @property
  162. def as_dict(self) -> dict:
  163. return {
  164. "consumption_id": self.consumption_id,
  165. "person_id": self.person_id,
  166. "consumption_type_id": self.consumption_type_id,
  167. "settlement_id": self.settlement_id,
  168. "created_at": self.created_at.isoformat(),
  169. "reversed": self.reversed,
  170. }
  171. # ---------- Models ----------
  172. @app.route("/ping")
  173. def ping() -> None:
  174. """ Return a status ping. """
  175. return "Pong"
  176. @app.route("/status")
  177. def status() -> None:
  178. """ Return a status dict with info about the database. """
  179. unsettled_q = Consumption.query.filter_by(settlement=None).filter_by(reversed=False)
  180. unsettled = unsettled_q.count()
  181. first = None
  182. last = None
  183. if unsettled:
  184. last = (
  185. unsettled_q.order_by(Consumption.created_at.desc())
  186. .first()
  187. .created_at.isoformat()
  188. )
  189. first = (
  190. unsettled_q.order_by(Consumption.created_at.asc())
  191. .first()
  192. .created_at.isoformat()
  193. )
  194. return jsonify({"unsettled": {"amount": unsettled, "first": first, "last": last}})
  195. # Person
  196. @app.route("/people", methods=["GET"])
  197. def get_people():
  198. """ Return a list of currently known people. """
  199. people = Person.query.order_by(Person.name).all()
  200. q = Person.query.order_by(Person.name)
  201. if request.args.get("active"):
  202. active_status = request.args.get("active", type=int)
  203. q = q.filter_by(active=active_status)
  204. people = q.all()
  205. result = [person.as_dict for person in people]
  206. return jsonify(people=result)
  207. @app.route("/people/<int:person_id>", methods=["GET"])
  208. def get_person(person_id: int):
  209. person = Person.query.get_or_404(person_id)
  210. return jsonify(person=person.as_dict)
  211. @app.route("/people", methods=["POST"])
  212. def add_person():
  213. """
  214. Add a new person.
  215. Required parameters:
  216. - name (str)
  217. """
  218. json = request.get_json()
  219. if not json:
  220. return jsonify({"error": "Could not parse JSON."}), 400
  221. data = json.get("person") or {}
  222. person = Person(name=data.get("name"), active=data.get("active", False))
  223. try:
  224. db.session.add(person)
  225. db.session.commit()
  226. except SQLAlchemyError:
  227. return jsonify({"error": "Invalid arguments for Person."}), 400
  228. return jsonify(person=person.as_dict), 201
  229. @app.route("/people/<int:person_id>/add_consumption", methods=["POST"])
  230. def add_consumption(person_id: int):
  231. person = Person.query.get_or_404(person_id)
  232. consumption = Consumption(person=person, consumption_type_id=1)
  233. try:
  234. db.session.add(consumption)
  235. db.session.commit()
  236. except SQLAlchemyError:
  237. return (
  238. jsonify(
  239. {"error": "Invalid Consumption parameters.", "person": person.as_dict}
  240. ),
  241. 400,
  242. )
  243. return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201
  244. @app.route("/people/<int:person_id>", methods=["PATCH"])
  245. def update_person(person_id: int):
  246. person = Person.query.get_or_404(person_id)
  247. data = request.json["person"]
  248. if "active" in data:
  249. person.active = data["active"]
  250. db.session.add(person)
  251. db.session.commit()
  252. return jsonify(person=person.as_dict)
  253. @app.route("/people/<int:person_id>/add_consumption/<int:ct_id>", methods=["POST"])
  254. def add_consumption2(person_id: int, ct_id: int):
  255. person = Person.query.get_or_404(person_id)
  256. consumption = Consumption(person=person, consumption_type_id=ct_id)
  257. try:
  258. db.session.add(consumption)
  259. db.session.commit()
  260. except SQLAlchemyError:
  261. return (
  262. jsonify(
  263. {"error": "Invalid Consumption parameters.", "person": person.as_dict}
  264. ),
  265. 400,
  266. )
  267. return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201
  268. @app.route("/consumptions/<int:consumption_id>", methods=["DELETE"])
  269. def reverse_consumption(consumption_id: int):
  270. """ Reverse a consumption. """
  271. consumption = Consumption.query.get_or_404(consumption_id)
  272. if consumption.reversed:
  273. return (
  274. jsonify(
  275. {
  276. "error": "Consumption already reversed",
  277. "consumption": consumption.as_dict,
  278. }
  279. ),
  280. 409,
  281. )
  282. try:
  283. consumption.reversed = True
  284. db.session.add(consumption)
  285. db.session.commit()
  286. except SQLAlchemyError:
  287. return jsonify({"error": "Database error."}), 500
  288. return jsonify(consumption=consumption.as_dict), 200
  289. # ConsumptionType
  290. @app.route("/consumption_types", methods=["GET"])
  291. def get_consumption_types():
  292. """ Return a list of currently active consumption types. """
  293. ctypes = ConsumptionType.query.filter_by(active=True).all()
  294. result = [ct.as_dict for ct in ctypes]
  295. return jsonify(consumption_types=result)
  296. @app.route("/consumption_types/<int:consumption_type_id>", methods=["GET"])
  297. def get_consumption_type(consumption_type_id: int):
  298. ct = ConsumptionType.query.get_or_404(consumption_type_id)
  299. return jsonify(consumption_type=ct.as_dict)
  300. @app.route("/consumption_types", methods=["POST"])
  301. def add_consumption_type():
  302. """ Add a new ConsumptionType. """
  303. json = request.get_json()
  304. if not json:
  305. return jsonify({"error": "Could not parse JSON."}), 400
  306. data = json.get("consumption_type") or {}
  307. ct = ConsumptionType(name=data.get("name"), icon=data.get("icon"))
  308. try:
  309. db.session.add(ct)
  310. db.session.commit()
  311. except SQLAlchemyError:
  312. return jsonify({"error": "Invalid arguments for ConsumptionType."}), 400
  313. return jsonify(consumption_type=ct.as_dict), 201
  314. # Settlement
  315. @app.route("/settlements", methods=["GET"])
  316. def get_settlements():
  317. """ Return a list of the active Settlements. """
  318. result = Settlement.query.all()
  319. return jsonify(settlements=[s.as_dict for s in result])
  320. @app.route("/settlements/<int:settlement_id>", methods=["GET"])
  321. def get_settlement(settlement_id: int):
  322. """ Show full details for a single Settlement. """
  323. s = Settlement.query.get_or_404(settlement_id)
  324. per_person = s.per_person
  325. return jsonify(settlement=s.as_dict, count_info=per_person)
  326. @app.route("/settlements", methods=["POST"])
  327. def add_settlement():
  328. """ Create a Settlement, and link all un-settled Consumptions to it. """
  329. json = request.get_json()
  330. if not json:
  331. return jsonify({"error": "Could not parse JSON."}), 400
  332. data = json.get("settlement") or {}
  333. s = Settlement(name=data["name"])
  334. db.session.add(s)
  335. db.session.commit()
  336. Consumption.query.filter_by(settlement=None).update(
  337. {"settlement_id": s.settlement_id}
  338. )
  339. db.session.commit()
  340. return jsonify(settlement=s.as_dict)
  341. # Export
  342. @app.route("/exports", methods=["GET"])
  343. def get_exports():
  344. """ Return a list of the created Exports. """
  345. result = Export.query.all()
  346. return jsonify(exports=[e.as_dict for e in result])
  347. @app.route("/exports/<int:export_id>", methods=["GET"])
  348. def get_export(export_id: int):
  349. """ Return an overview for the given Export. """
  350. e = Export.query.get_or_404(export_id)
  351. ss = [s.as_dict for s in e.settlements]
  352. return jsonify(export=e.as_dict, settlements=ss)
  353. @app.route("/exports", methods=["POST"])
  354. def add_export():
  355. """ Create an Export, and link all un-exported Settlements to it. """
  356. # Assert that there are Settlements to be exported.
  357. s_count = Settlement.query.filter_by(export=None).count()
  358. if s_count == 0:
  359. return jsonify(error="No un-exported Settlements."), 403
  360. e = Export()
  361. db.session.add(e)
  362. db.session.commit()
  363. Settlement.query.filter_by(export=None).update({"export_id": e.export_id})
  364. db.session.commit()
  365. ss = [s.as_dict for s in e.settlements]
  366. return jsonify(export=e.as_dict, settlements=ss), 201