""" Provides routes related to managing Person objects. """ from flask import jsonify, request from sqlalchemy.exc import SQLAlchemyError from piket_server.models import Consumption, Person from piket_server.flask import app, db @app.route("/people", methods=["GET"]) def get_people(): """ Return a list of currently known people. """ people = Person.query.order_by(Person.full_name).all() q = Person.query.order_by(Person.full_name) if request.args.get("active"): active_status = request.args.get("active", type=int) q = q.filter_by(active=active_status) people = q.all() result = [person.as_dict for person in people] return jsonify(people=result) @app.route("/people/", methods=["GET"]) def get_person(person_id: int): person = Person.query.get_or_404(person_id) return jsonify(person=person.as_dict) @app.route("/people", methods=["POST"]) def add_person(): """ Add a new person. Required parameters: - name (str) """ json = request.get_json() if not json: return jsonify({"error": "Could not parse JSON."}), 400 data = json.get("person") or {} person = Person( full_name=data.get("full_name"), active=data.get("active", False), display_name=data.get("display_name", None), ) try: db.session.add(person) db.session.commit() except SQLAlchemyError: return jsonify({"error": "Invalid arguments for Person."}), 400 return jsonify(person=person.as_dict), 201 @app.route("/people/", methods=["PATCH"]) def update_person(person_id: int): person = Person.query.get_or_404(person_id) data = request.json["person"] changed = False if "active" in data: person.active = data["active"] changed = True if "full_name" in data: person.full_name = data["full_name"] changed = True if "display_name" in data: person.display_name = data["display_name"] changed = True if changed: db.session.add(person) db.session.commit() return jsonify(person=person.as_dict) @app.route("/people//add_consumption", methods=["POST"]) def add_consumption(person_id: int): person = Person.query.get_or_404(person_id) consumption = Consumption(person=person, consumption_type_id=1) try: db.session.add(consumption) db.session.commit() except SQLAlchemyError: return ( jsonify( {"error": "Invalid Consumption parameters.", "person": person.as_dict} ), 400, ) return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201 @app.route("/people//add_consumption/", methods=["POST"]) def add_consumption2(person_id: int, ct_id: int): person = Person.query.get_or_404(person_id) consumption = Consumption(person=person, consumption_type_id=ct_id) try: db.session.add(consumption) db.session.commit() except SQLAlchemyError: return ( jsonify( {"error": "Invalid Consumption parameters.", "person": person.as_dict} ), 400, ) return jsonify(person=person.as_dict, consumption=consumption.as_dict), 201