Digitale bierlijst

__init__.py 8.3KB

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