Digitale bierlijst

__init__.py 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 flask import Flask, jsonify, abort, request
  8. from flask_sqlalchemy import SQLAlchemy
  9. DATA_HOME = os.environ.get("XDG_DATA_HOME", "~/.local/share")
  10. CONFIG_DIR = os.path.join(DATA_HOME, "piket_server")
  11. DB_PATH = os.path.expanduser(os.path.join(CONFIG_DIR, "database.sqlite3"))
  12. DB_URL = f"sqlite:///{DB_PATH}"
  13. app = Flask("piket_server")
  14. app.config["SQLALCHEMY_DATABASE_URI"] = DB_URL
  15. app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
  16. db = SQLAlchemy(app)
  17. # ---------- Models ----------
  18. class Person(db.Model):
  19. """ Represents a person to be shown on the lists. """
  20. __tablename__ = "people"
  21. person_id = db.Column(db.Integer, primary_key=True)
  22. name = db.Column(db.String, nullable=False)
  23. consumptions = db.relationship("Consumption", backref="person", lazy=True)
  24. def __repr__(self) -> str:
  25. return f"<Person {self.person_id}: {self.name}>"
  26. @property
  27. def as_dict(self) -> dict:
  28. return {
  29. "person_id": self.person_id,
  30. "name": self.name,
  31. "consumptions": {
  32. ct.consumption_type_id: Consumption.query.filter_by(person=self)
  33. .filter_by(consumption_type=ct)
  34. .filter_by(reversed=False)
  35. .count()
  36. for ct in ConsumptionType.query.all()
  37. },
  38. }
  39. class Settlement(db.Model):
  40. """ Represents a settlement of the list. """
  41. __tablename__ = "settlements"
  42. settlement_id = db.Column(db.Integer, primary_key=True)
  43. name = db.Column(db.String, nullable=False)
  44. consumptions = db.relationship("Consumption", backref="settlement", lazy=True)
  45. def __repr__(self) -> str:
  46. return f"<Settlement {self.settlement_id}: {self.name}>"
  47. class ConsumptionType(db.Model):
  48. """ Represents a type of consumption to be counted. """
  49. __tablename__ = "consumption_types"
  50. consumption_type_id = db.Column(db.Integer, primary_key=True)
  51. name = db.Column(db.String, nullable=False)
  52. icon = db.Column(db.String)
  53. consumptions = db.relationship("Consumption", backref="consumption_type", lazy=True)
  54. def __repr__(self) -> str:
  55. return f"<ConsumptionType: {self.name}>"
  56. @property
  57. def as_dict(self) -> dict:
  58. return {
  59. "consumption_type_id": self.consumption_type_id,
  60. "name": self.name,
  61. "icon": self.icon,
  62. }
  63. class Consumption(db.Model):
  64. """ Represent one consumption to be counted. """
  65. __tablename__ = "consumptions"
  66. consumption_id = db.Column(db.Integer, primary_key=True)
  67. person_id = db.Column(db.Integer, db.ForeignKey("people.person_id"), nullable=True)
  68. consumption_type_id = db.Column(
  69. db.Integer,
  70. db.ForeignKey("consumption_types.consumption_type_id"),
  71. nullable=False,
  72. )
  73. settlement_id = db.Column(
  74. db.Integer, db.ForeignKey("settlements.settlement_id"), nullable=True
  75. )
  76. created_at = db.Column(
  77. db.DateTime, default=datetime.datetime.utcnow, nullable=False
  78. )
  79. reversed = db.Column(db.Boolean, default=False, nullable=False)
  80. def __repr__(self) -> str:
  81. return f"<Consumption: {self.consumption_type.name} for {self.person.name}>"
  82. @property
  83. def as_dict(self) -> dict:
  84. return {
  85. "consumption_id": self.consumption_id,
  86. "person_id": self.person_id,
  87. "consumption_type_id": self.consumption_type_id,
  88. "settlement_id": self.settlement_id,
  89. "created_at": self.created_at.isoformat(),
  90. "reversed": self.reversed,
  91. }
  92. # ---------- Models ----------
  93. @app.route("/ping")
  94. def ping() -> None:
  95. """ Return a status ping. """
  96. return "Pong"
  97. # Person
  98. @app.route("/people", methods=["GET"])
  99. def get_people():
  100. """ Return a list of currently known people. """
  101. people = Person.query.order_by(Person.name).all()
  102. result = [person.as_dict for person in people]
  103. return jsonify(people=result)
  104. @app.route("/people/<int:person_id>", methods=["GET"])
  105. def get_person(person_id: int):
  106. person = Person.query.get_or_404(person_id)
  107. return jsonify(person=person.as_dict)
  108. @app.route("/people", methods=["POST"])
  109. def add_person():
  110. """
  111. Add a new person.
  112. Required parameters:
  113. - name (str)
  114. """
  115. json = request.get_json()
  116. if not json:
  117. return jsonify({"error": "Could not parse JSON."}), 400
  118. data = json.get("person") or {}
  119. person = Person(name=data.get("name"))
  120. try:
  121. db.session.add(person)
  122. db.session.commit()
  123. except SQLAlchemyError:
  124. return jsonify({"error": "Invalid arguments for Person."}), 400
  125. return jsonify(person=person.as_dict), 201
  126. @app.route("/people/<int:person_id>/add_consumption", methods=["POST"])
  127. def add_consumption(person_id: int):
  128. person = Person.query.get_or_404(person_id)
  129. consumption = Consumption(person=person, consumption_type_id=1)
  130. try:
  131. db.session.add(consumption)
  132. db.session.commit()
  133. except SQLAlchemyError:
  134. return (
  135. jsonify(
  136. {"error": "Invalid Consumption parameters.", "person": person.as_dict}
  137. ),
  138. 400,
  139. )
  140. return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201
  141. @app.route("/people/<int:person_id>/add_consumption/<int:ct_id>", methods=["POST"])
  142. def add_consumption2(person_id: int, ct_id: int):
  143. person = Person.query.get_or_404(person_id)
  144. consumption = Consumption(person=person, consumption_type_id=ct_id)
  145. try:
  146. db.session.add(consumption)
  147. db.session.commit()
  148. except SQLAlchemyError:
  149. return (
  150. jsonify(
  151. {"error": "Invalid Consumption parameters.", "person": person.as_dict}
  152. ),
  153. 400,
  154. )
  155. return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201
  156. @app.route("/consumptions/<int:consumption_id>", methods=["DELETE"])
  157. def reverse_consumption(consumption_id: int):
  158. """ Reverse a consumption. """
  159. consumption = Consumption.query.get_or_404(consumption_id)
  160. if consumption.reversed:
  161. return (
  162. jsonify(
  163. {
  164. "error": "Consumption already reversed",
  165. "consumption": consumption.as_dict,
  166. }
  167. ),
  168. 409,
  169. )
  170. try:
  171. consumption.reversed = True
  172. db.session.add(consumption)
  173. db.session.commit()
  174. except SQLAlchemyError:
  175. return jsonify({"error": "Database error."}), 500
  176. return jsonify(consumption=consumption.as_dict), 200
  177. # ConsumptionType
  178. @app.route("/consumption_types", methods=["GET"])
  179. def get_consumption_types():
  180. """ Return a list of currently active consumption types. """
  181. ctypes = ConsumptionType.query.all()
  182. result = [ct.as_dict for ct in ctypes]
  183. return jsonify(consumption_types=result)
  184. @app.route("/consumption_types/<int:consumption_type_id>", methods=["GET"])
  185. def get_consumption_type(consumption_type_id: int):
  186. ct = ConsumptionType.query.get_or_404(consumption_type_id)
  187. return jsonify(consumption_type=ct.as_dict)
  188. @app.route("/consumption_types", methods=["POST"])
  189. def add_consumption_type():
  190. """ Add a new ConsumptionType. """
  191. json = request.get_json()
  192. if not json:
  193. return jsonify({"error": "Could not parse JSON."}), 400
  194. data = json.get("consumption_type") or {}
  195. ct = ConsumptionType(name=data.get("name"), icon=data.get("icon"))
  196. try:
  197. db.session.add(ct)
  198. db.session.commit()
  199. except SQLAlchemyError:
  200. return jsonify({"error": "Invalid arguments for ConsumptionType."}), 400
  201. return jsonify(consumption_type=ct.as_dict), 201