Digitale bierlijst

__init__.py 11KB

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