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. "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 = Consumption.\
  60. query.\
  61. 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. 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.\
  125. filter_by(settlement=None).\
  126. filter_by(reversed=False)
  127. unsettled = unsettled_q.count()
  128. first = None
  129. last = None
  130. if unsettled:
  131. last = unsettled_q.\
  132. order_by(Consumption.created_at.desc()).\
  133. first().\
  134. created_at.isoformat()
  135. first = unsettled_q.\
  136. order_by(Consumption.created_at.asc())\
  137. .first()\
  138. .created_at.isoformat()
  139. return jsonify({
  140. 'unsettled': {
  141. 'amount': unsettled,
  142. 'first': first,
  143. 'last': last,
  144. },
  145. })
  146. # Person
  147. @app.route("/people", methods=["GET"])
  148. def get_people():
  149. """ Return a list of currently known people. """
  150. people = Person.query.order_by(Person.name).all()
  151. q = Person.query.order_by(Person.name)
  152. if request.args.get("active"):
  153. active_status = request.args.get("active", type=int)
  154. q = q.filter_by(active=active_status)
  155. people = q.all()
  156. result = [person.as_dict for person in people]
  157. return jsonify(people=result)
  158. @app.route("/people/<int:person_id>", methods=["GET"])
  159. def get_person(person_id: int):
  160. person = Person.query.get_or_404(person_id)
  161. return jsonify(person=person.as_dict)
  162. @app.route("/people", methods=["POST"])
  163. def add_person():
  164. """
  165. Add a new person.
  166. Required parameters:
  167. - name (str)
  168. """
  169. json = request.get_json()
  170. if not json:
  171. return jsonify({"error": "Could not parse JSON."}), 400
  172. data = json.get("person") or {}
  173. person = Person(name=data.get("name"))
  174. try:
  175. db.session.add(person)
  176. db.session.commit()
  177. except SQLAlchemyError:
  178. return jsonify({"error": "Invalid arguments for Person."}), 400
  179. return jsonify(person=person.as_dict), 201
  180. @app.route("/people/<int:person_id>/add_consumption", methods=["POST"])
  181. def add_consumption(person_id: int):
  182. person = Person.query.get_or_404(person_id)
  183. consumption = Consumption(person=person, consumption_type_id=1)
  184. try:
  185. db.session.add(consumption)
  186. db.session.commit()
  187. except SQLAlchemyError:
  188. return (
  189. jsonify(
  190. {"error": "Invalid Consumption parameters.", "person": person.as_dict}
  191. ),
  192. 400,
  193. )
  194. return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201
  195. @app.route("/people/<int:person_id>", methods=["PATCH"])
  196. def update_person(person_id: int):
  197. person = Person.query.get_or_404(person_id)
  198. data = request.json["person"]
  199. if "active" in data:
  200. person.active = data["active"]
  201. db.session.add(person)
  202. db.session.commit()
  203. return jsonify(person=person.as_dict)
  204. @app.route("/people/<int:person_id>/add_consumption/<int:ct_id>", methods=["POST"])
  205. def add_consumption2(person_id: int, ct_id: int):
  206. person = Person.query.get_or_404(person_id)
  207. consumption = Consumption(person=person, consumption_type_id=ct_id)
  208. try:
  209. db.session.add(consumption)
  210. db.session.commit()
  211. except SQLAlchemyError:
  212. return (
  213. jsonify(
  214. {"error": "Invalid Consumption parameters.", "person": person.as_dict}
  215. ),
  216. 400,
  217. )
  218. return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201
  219. @app.route("/consumptions/<int:consumption_id>", methods=["DELETE"])
  220. def reverse_consumption(consumption_id: int):
  221. """ Reverse a consumption. """
  222. consumption = Consumption.query.get_or_404(consumption_id)
  223. if consumption.reversed:
  224. return (
  225. jsonify(
  226. {
  227. "error": "Consumption already reversed",
  228. "consumption": consumption.as_dict,
  229. }
  230. ),
  231. 409,
  232. )
  233. try:
  234. consumption.reversed = True
  235. db.session.add(consumption)
  236. db.session.commit()
  237. except SQLAlchemyError:
  238. return jsonify({"error": "Database error."}), 500
  239. return jsonify(consumption=consumption.as_dict), 200
  240. # ConsumptionType
  241. @app.route("/consumption_types", methods=["GET"])
  242. def get_consumption_types():
  243. """ Return a list of currently active consumption types. """
  244. ctypes = ConsumptionType.query.all()
  245. result = [ct.as_dict for ct in ctypes]
  246. return jsonify(consumption_types=result)
  247. @app.route("/consumption_types/<int:consumption_type_id>", methods=["GET"])
  248. def get_consumption_type(consumption_type_id: int):
  249. ct = ConsumptionType.query.get_or_404(consumption_type_id)
  250. return jsonify(consumption_type=ct.as_dict)
  251. @app.route("/consumption_types", methods=["POST"])
  252. def add_consumption_type():
  253. """ Add a new ConsumptionType. """
  254. json = request.get_json()
  255. if not json:
  256. return jsonify({"error": "Could not parse JSON."}), 400
  257. data = json.get("consumption_type") or {}
  258. ct = ConsumptionType(name=data.get("name"), icon=data.get("icon"))
  259. try:
  260. db.session.add(ct)
  261. db.session.commit()
  262. except SQLAlchemyError:
  263. return jsonify({"error": "Invalid arguments for ConsumptionType."}), 400
  264. return jsonify(consumption_type=ct.as_dict), 201
  265. # Settlement
  266. @app.route("/settlements", methods=["GET"])
  267. def get_settlements():
  268. """ Return a list of the active Settlements. """
  269. result = Settlement.query.all()
  270. return jsonify(settlements=[s.as_dict for s in result])
  271. @app.route("/settlements", methods=["POST"])
  272. def add_settlement():
  273. """ Create a Settlement, and link all un-settled Consumptions to it. """
  274. json = request.get_json()
  275. if not json:
  276. return jsonify({"error": "Could not parse JSON."}), 400
  277. data = json.get('settlement') or {}
  278. s = Settlement(name=data['name'])
  279. db.session.add(s)
  280. db.session.commit()
  281. Consumption.query.filter_by(settlement=None).update({'settlement_id':
  282. s.settlement_id})
  283. db.session.commit()
  284. return jsonify(settlement=s.as_dict)