Digitale bierlijst

__init__.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 Settlement(db.Model):
  44. """ Represents a settlement of the list. """
  45. __tablename__ = "settlements"
  46. settlement_id = db.Column(db.Integer, primary_key=True)
  47. name = db.Column(db.String, nullable=False)
  48. consumptions = db.relationship("Consumption", backref="settlement", lazy=True)
  49. def __repr__(self) -> str:
  50. return f"<Settlement {self.settlement_id}: {self.name}>"
  51. @property
  52. def as_dict(self) -> dict:
  53. return {
  54. "settlement_id": self.settlement_id,
  55. "name": self.name,
  56. "consumption_summary": self.consumption_summary,
  57. }
  58. @property
  59. def consumption_summary(self) -> dict:
  60. q = (
  61. Consumption.query.filter_by(settlement=self)
  62. .group_by(Consumption.consumption_type_id)
  63. .outerjoin(ConsumptionType)
  64. .with_entities(
  65. Consumption.consumption_type_id,
  66. ConsumptionType.name,
  67. func.count(Consumption.consumption_id),
  68. )
  69. .all()
  70. )
  71. return {r[0]: {"name": r[1], "count": r[2]} for r in q}
  72. class ConsumptionType(db.Model):
  73. """ Represents a type of consumption to be counted. """
  74. __tablename__ = "consumption_types"
  75. consumption_type_id = db.Column(db.Integer, primary_key=True)
  76. name = db.Column(db.String, nullable=False)
  77. icon = db.Column(db.String)
  78. consumptions = db.relationship("Consumption", backref="consumption_type", lazy=True)
  79. def __repr__(self) -> str:
  80. return f"<ConsumptionType: {self.name}>"
  81. @property
  82. def as_dict(self) -> dict:
  83. return {
  84. "consumption_type_id": self.consumption_type_id,
  85. "name": self.name,
  86. "icon": self.icon,
  87. }
  88. class Consumption(db.Model):
  89. """ Represent one consumption to be counted. """
  90. __tablename__ = "consumptions"
  91. consumption_id = db.Column(db.Integer, primary_key=True)
  92. person_id = db.Column(db.Integer, db.ForeignKey("people.person_id"), nullable=True)
  93. consumption_type_id = db.Column(
  94. db.Integer,
  95. db.ForeignKey("consumption_types.consumption_type_id"),
  96. nullable=False,
  97. )
  98. settlement_id = db.Column(
  99. db.Integer, db.ForeignKey("settlements.settlement_id"), nullable=True
  100. )
  101. created_at = db.Column(
  102. db.DateTime, default=datetime.datetime.utcnow, nullable=False
  103. )
  104. reversed = db.Column(db.Boolean, default=False, nullable=False)
  105. def __repr__(self) -> str:
  106. return f"<Consumption: {self.consumption_type.name} for {self.person.name}>"
  107. @property
  108. def as_dict(self) -> dict:
  109. return {
  110. "consumption_id": self.consumption_id,
  111. "person_id": self.person_id,
  112. "consumption_type_id": self.consumption_type_id,
  113. "settlement_id": self.settlement_id,
  114. "created_at": self.created_at.isoformat(),
  115. "reversed": self.reversed,
  116. }
  117. # ---------- Models ----------
  118. @app.route("/ping")
  119. def ping() -> None:
  120. """ Return a status ping. """
  121. return "Pong"
  122. @app.route("/status")
  123. def status() -> None:
  124. """ Return a status dict with info about the database. """
  125. unsettled_q = Consumption.query.filter_by(settlement=None).filter_by(reversed=False)
  126. unsettled = unsettled_q.count()
  127. first = None
  128. last = None
  129. if unsettled:
  130. last = (
  131. unsettled_q.order_by(Consumption.created_at.desc())
  132. .first()
  133. .created_at.isoformat()
  134. )
  135. first = (
  136. unsettled_q.order_by(Consumption.created_at.asc())
  137. .first()
  138. .created_at.isoformat()
  139. )
  140. return jsonify({"unsettled": {"amount": unsettled, "first": first, "last": last}})
  141. # Person
  142. @app.route("/people", methods=["GET"])
  143. def get_people():
  144. """ Return a list of currently known people. """
  145. people = Person.query.order_by(Person.name).all()
  146. q = Person.query.order_by(Person.name)
  147. if request.args.get("active"):
  148. active_status = request.args.get("active", type=int)
  149. q = q.filter_by(active=active_status)
  150. people = q.all()
  151. result = [person.as_dict for person in people]
  152. return jsonify(people=result)
  153. @app.route("/people/<int:person_id>", methods=["GET"])
  154. def get_person(person_id: int):
  155. person = Person.query.get_or_404(person_id)
  156. return jsonify(person=person.as_dict)
  157. @app.route("/people", methods=["POST"])
  158. def add_person():
  159. """
  160. Add a new person.
  161. Required parameters:
  162. - name (str)
  163. """
  164. json = request.get_json()
  165. if not json:
  166. return jsonify({"error": "Could not parse JSON."}), 400
  167. data = json.get("person") or {}
  168. person = Person(name=data.get("name"), active=data.get("active", False))
  169. try:
  170. db.session.add(person)
  171. db.session.commit()
  172. except SQLAlchemyError:
  173. return jsonify({"error": "Invalid arguments for Person."}), 400
  174. return jsonify(person=person.as_dict), 201
  175. @app.route("/people/<int:person_id>/add_consumption", methods=["POST"])
  176. def add_consumption(person_id: int):
  177. person = Person.query.get_or_404(person_id)
  178. consumption = Consumption(person=person, consumption_type_id=1)
  179. try:
  180. db.session.add(consumption)
  181. db.session.commit()
  182. except SQLAlchemyError:
  183. return (
  184. jsonify(
  185. {"error": "Invalid Consumption parameters.", "person": person.as_dict}
  186. ),
  187. 400,
  188. )
  189. return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201
  190. @app.route("/people/<int:person_id>", methods=["PATCH"])
  191. def update_person(person_id: int):
  192. person = Person.query.get_or_404(person_id)
  193. data = request.json["person"]
  194. if "active" in data:
  195. person.active = data["active"]
  196. db.session.add(person)
  197. db.session.commit()
  198. return jsonify(person=person.as_dict)
  199. @app.route("/people/<int:person_id>/add_consumption/<int:ct_id>", methods=["POST"])
  200. def add_consumption2(person_id: int, ct_id: int):
  201. person = Person.query.get_or_404(person_id)
  202. consumption = Consumption(person=person, consumption_type_id=ct_id)
  203. try:
  204. db.session.add(consumption)
  205. db.session.commit()
  206. except SQLAlchemyError:
  207. return (
  208. jsonify(
  209. {"error": "Invalid Consumption parameters.", "person": person.as_dict}
  210. ),
  211. 400,
  212. )
  213. return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201
  214. @app.route("/consumptions/<int:consumption_id>", methods=["DELETE"])
  215. def reverse_consumption(consumption_id: int):
  216. """ Reverse a consumption. """
  217. consumption = Consumption.query.get_or_404(consumption_id)
  218. if consumption.reversed:
  219. return (
  220. jsonify(
  221. {
  222. "error": "Consumption already reversed",
  223. "consumption": consumption.as_dict,
  224. }
  225. ),
  226. 409,
  227. )
  228. try:
  229. consumption.reversed = True
  230. db.session.add(consumption)
  231. db.session.commit()
  232. except SQLAlchemyError:
  233. return jsonify({"error": "Database error."}), 500
  234. return jsonify(consumption=consumption.as_dict), 200
  235. # ConsumptionType
  236. @app.route("/consumption_types", methods=["GET"])
  237. def get_consumption_types():
  238. """ Return a list of currently active consumption types. """
  239. ctypes = ConsumptionType.query.all()
  240. result = [ct.as_dict for ct in ctypes]
  241. return jsonify(consumption_types=result)
  242. @app.route("/consumption_types/<int:consumption_type_id>", methods=["GET"])
  243. def get_consumption_type(consumption_type_id: int):
  244. ct = ConsumptionType.query.get_or_404(consumption_type_id)
  245. return jsonify(consumption_type=ct.as_dict)
  246. @app.route("/consumption_types", methods=["POST"])
  247. def add_consumption_type():
  248. """ Add a new ConsumptionType. """
  249. json = request.get_json()
  250. if not json:
  251. return jsonify({"error": "Could not parse JSON."}), 400
  252. data = json.get("consumption_type") or {}
  253. ct = ConsumptionType(name=data.get("name"), icon=data.get("icon"))
  254. try:
  255. db.session.add(ct)
  256. db.session.commit()
  257. except SQLAlchemyError:
  258. return jsonify({"error": "Invalid arguments for ConsumptionType."}), 400
  259. return jsonify(consumption_type=ct.as_dict), 201
  260. # Settlement
  261. @app.route("/settlements", methods=["GET"])
  262. def get_settlements():
  263. """ Return a list of the active Settlements. """
  264. result = Settlement.query.all()
  265. return jsonify(settlements=[s.as_dict for s in result])
  266. @app.route("/settlements", methods=["POST"])
  267. def add_settlement():
  268. """ Create a Settlement, and link all un-settled Consumptions to it. """
  269. json = request.get_json()
  270. if not json:
  271. return jsonify({"error": "Could not parse JSON."}), 400
  272. data = json.get("settlement") or {}
  273. s = Settlement(name=data["name"])
  274. db.session.add(s)
  275. db.session.commit()
  276. Consumption.query.filter_by(settlement=None).update(
  277. {"settlement_id": s.settlement_id}
  278. )
  279. db.session.commit()
  280. return jsonify(settlement=s.as_dict)