Digitale bierlijst

__init__.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. consumptions = db.relationship("Consumption", backref="consumption_type", lazy=True)
  132. def __repr__(self) -> str:
  133. return f"<ConsumptionType: {self.name}>"
  134. @property
  135. def as_dict(self) -> dict:
  136. return {
  137. "consumption_type_id": self.consumption_type_id,
  138. "name": self.name,
  139. "icon": self.icon,
  140. }
  141. class Consumption(db.Model):
  142. """ Represent one consumption to be counted. """
  143. __tablename__ = "consumptions"
  144. consumption_id = db.Column(db.Integer, primary_key=True)
  145. person_id = db.Column(db.Integer, db.ForeignKey("people.person_id"), nullable=True)
  146. consumption_type_id = db.Column(
  147. db.Integer,
  148. db.ForeignKey("consumption_types.consumption_type_id"),
  149. nullable=False,
  150. )
  151. settlement_id = db.Column(
  152. db.Integer, db.ForeignKey("settlements.settlement_id"), nullable=True
  153. )
  154. created_at = db.Column(
  155. db.DateTime, default=datetime.datetime.utcnow, nullable=False
  156. )
  157. reversed = db.Column(db.Boolean, default=False, nullable=False)
  158. def __repr__(self) -> str:
  159. return f"<Consumption: {self.consumption_type.name} for {self.person.name}>"
  160. @property
  161. def as_dict(self) -> dict:
  162. return {
  163. "consumption_id": self.consumption_id,
  164. "person_id": self.person_id,
  165. "consumption_type_id": self.consumption_type_id,
  166. "settlement_id": self.settlement_id,
  167. "created_at": self.created_at.isoformat(),
  168. "reversed": self.reversed,
  169. }
  170. # ---------- Models ----------
  171. @app.route("/ping")
  172. def ping() -> None:
  173. """ Return a status ping. """
  174. return "Pong"
  175. @app.route("/status")
  176. def status() -> None:
  177. """ Return a status dict with info about the database. """
  178. unsettled_q = Consumption.query.filter_by(settlement=None).filter_by(reversed=False)
  179. unsettled = unsettled_q.count()
  180. first = None
  181. last = None
  182. if unsettled:
  183. last = (
  184. unsettled_q.order_by(Consumption.created_at.desc())
  185. .first()
  186. .created_at.isoformat()
  187. )
  188. first = (
  189. unsettled_q.order_by(Consumption.created_at.asc())
  190. .first()
  191. .created_at.isoformat()
  192. )
  193. return jsonify({"unsettled": {"amount": unsettled, "first": first, "last": last}})
  194. # Person
  195. @app.route("/people", methods=["GET"])
  196. def get_people():
  197. """ Return a list of currently known people. """
  198. people = Person.query.order_by(Person.name).all()
  199. q = Person.query.order_by(Person.name)
  200. if request.args.get("active"):
  201. active_status = request.args.get("active", type=int)
  202. q = q.filter_by(active=active_status)
  203. people = q.all()
  204. result = [person.as_dict for person in people]
  205. return jsonify(people=result)
  206. @app.route("/people/<int:person_id>", methods=["GET"])
  207. def get_person(person_id: int):
  208. person = Person.query.get_or_404(person_id)
  209. return jsonify(person=person.as_dict)
  210. @app.route("/people", methods=["POST"])
  211. def add_person():
  212. """
  213. Add a new person.
  214. Required parameters:
  215. - name (str)
  216. """
  217. json = request.get_json()
  218. if not json:
  219. return jsonify({"error": "Could not parse JSON."}), 400
  220. data = json.get("person") or {}
  221. person = Person(name=data.get("name"), active=data.get("active", False))
  222. try:
  223. db.session.add(person)
  224. db.session.commit()
  225. except SQLAlchemyError:
  226. return jsonify({"error": "Invalid arguments for Person."}), 400
  227. return jsonify(person=person.as_dict), 201
  228. @app.route("/people/<int:person_id>/add_consumption", methods=["POST"])
  229. def add_consumption(person_id: int):
  230. person = Person.query.get_or_404(person_id)
  231. consumption = Consumption(person=person, consumption_type_id=1)
  232. try:
  233. db.session.add(consumption)
  234. db.session.commit()
  235. except SQLAlchemyError:
  236. return (
  237. jsonify(
  238. {"error": "Invalid Consumption parameters.", "person": person.as_dict}
  239. ),
  240. 400,
  241. )
  242. return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201
  243. @app.route("/people/<int:person_id>", methods=["PATCH"])
  244. def update_person(person_id: int):
  245. person = Person.query.get_or_404(person_id)
  246. data = request.json["person"]
  247. if "active" in data:
  248. person.active = data["active"]
  249. db.session.add(person)
  250. db.session.commit()
  251. return jsonify(person=person.as_dict)
  252. @app.route("/people/<int:person_id>/add_consumption/<int:ct_id>", methods=["POST"])
  253. def add_consumption2(person_id: int, ct_id: int):
  254. person = Person.query.get_or_404(person_id)
  255. consumption = Consumption(person=person, consumption_type_id=ct_id)
  256. try:
  257. db.session.add(consumption)
  258. db.session.commit()
  259. except SQLAlchemyError:
  260. return (
  261. jsonify(
  262. {"error": "Invalid Consumption parameters.", "person": person.as_dict}
  263. ),
  264. 400,
  265. )
  266. return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201
  267. @app.route("/consumptions/<int:consumption_id>", methods=["DELETE"])
  268. def reverse_consumption(consumption_id: int):
  269. """ Reverse a consumption. """
  270. consumption = Consumption.query.get_or_404(consumption_id)
  271. if consumption.reversed:
  272. return (
  273. jsonify(
  274. {
  275. "error": "Consumption already reversed",
  276. "consumption": consumption.as_dict,
  277. }
  278. ),
  279. 409,
  280. )
  281. try:
  282. consumption.reversed = True
  283. db.session.add(consumption)
  284. db.session.commit()
  285. except SQLAlchemyError:
  286. return jsonify({"error": "Database error."}), 500
  287. return jsonify(consumption=consumption.as_dict), 200
  288. # ConsumptionType
  289. @app.route("/consumption_types", methods=["GET"])
  290. def get_consumption_types():
  291. """ Return a list of currently active consumption types. """
  292. ctypes = ConsumptionType.query.all()
  293. result = [ct.as_dict for ct in ctypes]
  294. return jsonify(consumption_types=result)
  295. @app.route("/consumption_types/<int:consumption_type_id>", methods=["GET"])
  296. def get_consumption_type(consumption_type_id: int):
  297. ct = ConsumptionType.query.get_or_404(consumption_type_id)
  298. return jsonify(consumption_type=ct.as_dict)
  299. @app.route("/consumption_types", methods=["POST"])
  300. def add_consumption_type():
  301. """ Add a new ConsumptionType. """
  302. json = request.get_json()
  303. if not json:
  304. return jsonify({"error": "Could not parse JSON."}), 400
  305. data = json.get("consumption_type") or {}
  306. ct = ConsumptionType(name=data.get("name"), icon=data.get("icon"))
  307. try:
  308. db.session.add(ct)
  309. db.session.commit()
  310. except SQLAlchemyError:
  311. return jsonify({"error": "Invalid arguments for ConsumptionType."}), 400
  312. return jsonify(consumption_type=ct.as_dict), 201
  313. # Settlement
  314. @app.route("/settlements", methods=["GET"])
  315. def get_settlements():
  316. """ Return a list of the active Settlements. """
  317. result = Settlement.query.all()
  318. return jsonify(settlements=[s.as_dict for s in result])
  319. @app.route("/settlements/<int:settlement_id>", methods=["GET"])
  320. def get_settlement(settlement_id: int):
  321. """ Show full details for a single Settlement. """
  322. s = Settlement.query.get_or_404(settlement_id)
  323. per_person = s.per_person
  324. return jsonify(settlement=s.as_dict, count_info=per_person)
  325. @app.route("/settlements", methods=["POST"])
  326. def add_settlement():
  327. """ Create a Settlement, and link all un-settled Consumptions to it. """
  328. json = request.get_json()
  329. if not json:
  330. return jsonify({"error": "Could not parse JSON."}), 400
  331. data = json.get("settlement") or {}
  332. s = Settlement(name=data["name"])
  333. db.session.add(s)
  334. db.session.commit()
  335. Consumption.query.filter_by(settlement=None).update(
  336. {"settlement_id": s.settlement_id}
  337. )
  338. db.session.commit()
  339. return jsonify(settlement=s.as_dict)
  340. # Export
  341. @app.route("/exports", methods=["GET"])
  342. def get_exports():
  343. """ Return a list of the created Exports. """
  344. result = Export.query.all()
  345. return jsonify(exports=[e.as_dict for e in result])
  346. @app.route("/exports/<int:export_id>", methods=["GET"])
  347. def get_export(export_id: int):
  348. """ Return an overview for the given Export. """
  349. e = Export.query.get_or_404(export_id)
  350. ss = [s.as_dict for s in e.settlements]
  351. return jsonify(export=e.as_dict, settlements=ss)
  352. @app.route("/exports", methods=["POST"])
  353. def add_export():
  354. """ Create an Export, and link all un-exported Settlements to it. """
  355. # Assert that there are Settlements to be exported.
  356. s_count = Settlement.query.filter_by(export=None).count()
  357. if s_count == 0:
  358. return jsonify(error="No un-exported Settlements."), 403
  359. e = Export()
  360. db.session.add(e)
  361. db.session.commit()
  362. Settlement.query.filter_by(export=None).update({"export_id": e.export_id})
  363. db.session.commit()
  364. ss = [s.as_dict for s in e.settlements]
  365. return jsonify(export=e.as_dict, settlements=ss), 201