from flask import request, jsonify from pony.orm import ObjectNotFound from datetime import datetime, timedelta from ITPlanning.db import Appointment, Planning, Service, Ticket, Customer from ITPlanning.api.exception import NotFound, GenericError from . import api def datefiltering(query): before, after = map(request.values.get, ("before", "after")) if before: before = datetime.strptime(before, "%Y-%m-%dT%H%M") query = query.filter(lambda a: a.start_datetime < before) if after: after = datetime.strptime(after, "%Y-%m-%dT%H%M") query = query.filter(lambda a: a.start_datetime > after) return query def search_appointment(by=None, id=None): rv = [] if by == None and id is not None: rv.append(Appointment[id].to_dict()) else: query = Appointment.select() if by is not None: query.filter(lambda a: getattr(a, by).id == id) query = datefiltering(query) for f in query: rv.append(f.to_dict()) if len(rv) == 0: raise NotFound("Appointment") return jsonify(rv) @api.route("/appointment") @api.route("/appointment/") @api.route("/appointment/") def get_appointment(id=None): return search_appointment(id=id) @api.route("/appointment/planning/") def get_appointment_by_planning(id=None): return search_appointment("planning", id) @api.route("/appointment/service/") def get_appointment_by_service(id): return search_appointment("service", id) @api.route("/appointment/customer/") def get_appointment_by_customer(id): return search_appointment("customer", id) @api.route("/appointment/ticket/") def get_appointment_by_ticket(id): return search_appointment("ticket", id) @api.route("/appointment", methods=["POST"]) def new_appointment(): book_datetime = datetime.now() start_datetime = request.values.get("start_datetime") service = request.values.get("service") planning = request.values.get("planning") ticket = request.values.get("ticket") customer = request.values.get("customer") is_unavaillable = request.values.get("is_unavaillable") notes = request.values.get("notes") if start_datetime is None or service is None or planning is None: return GenericError("missing parameter") if is_unavaillable is None: is_unavaillable = False service = Service[service] planning = Planning[planning] start_datetime = datetime.strptime(start_datetime, "%Y-%m-%dT%H%M") end_datetime = start_datetime + timedelta(minutes=service.service_category.duration) if customer: customer = Customer[customer] if ticket: ticket = Ticket[ticket] if notes is None: notes = "" newappointment = Appointment( book_datetime=book_datetime, start_datetime=start_datetime, end_datetime=end_datetime, is_unavaillable=is_unavaillable, service=service, planning=planning, ticket=ticket, customer=customer, notes="", ) rv = jsonify(newappointment.to_dict()) rv.status_code = 201 return rv @api.route("/appointment", methods=["PUT"]) def update_appointment(): raise NotImplementedError @api.route("/appointment", methods=["DELETE"]) def delete_appointment(): raise NotImplementedError