Skip to content

Commit

Permalink
update restaurateur service PUT
Browse files Browse the repository at this point in the history
  • Loading branch information
william57m committed Nov 20, 2014
1 parent fdd10ae commit 46e8236
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 52 deletions.
72 changes: 36 additions & 36 deletions webserver/controllers/orders.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from webserver.lib.base import jsonify
from webserver.models import Address, Order, StateOrder, Client, LineOrder, Restaurant

from twilio.rest import TwilioRestClient
from twilio.rest import TwilioRestClient
from webserver.config import TwilioConfig

from sqlalchemy.orm import lazyload
Expand Down Expand Up @@ -35,37 +35,37 @@ def list():
3: En cours de livraison
4: Livrée
"""

# Prepare query
query = db.session.query(Order)

# State
if 'state' in request.values:
try:
state_int = int(request.values['state'])
except:
return make_response(gettext(u"L'état doit être 0, 1, 2 ou 3."), 400)

states = {0: u"En attente", 1: u"En préparation", 2: u"Prête", 3: u"En cours de livraison", 4: u"Livrée"}
state = states[state_int]

query = query.join(StateOrder).filter(StateOrder.name == state)

if 'client_id' in request.values:
query = query.filter(Order.client_id == request.values['client_id'])

if 'restaurant_id' in request.values:
query = query.filter(Order.restaurant_id == request.values['restaurant_id'])

orders = query.all()

# Build the response
response = make_response(jsonify([o.to_dict() for o in orders]))
response.status_code = 200
response.mimetype = 'application/json'
return response


# Get one order
@orders.route('/<int:id>', methods=['GET', 'OPTIONS'])
def index(id):
Expand All @@ -89,8 +89,8 @@ def index(id):
response.mimetype = 'application/json'

return response


# Create an order
@orders.route('', methods=['POST', 'OPTIONS'])
def create():
Expand Down Expand Up @@ -122,7 +122,7 @@ def create():
address = db.session.query(Address).get(address_id)
if address is None:
return make_response(gettext(u"L'adresse n'existe pas."), 404)

# Check restaurant
if 'restaurant_id' not in datas:
return make_response(gettext(u"restaurant_id est obligatoire."), 400)
Expand All @@ -134,44 +134,44 @@ def create():
restaurant = db.session.query(Restaurant).get(restaurant_id)
if restaurant is None:
return make_response(gettext(u"Le restaurant n'existe pas."), 404)

# Get client id from logged used
from flask.ext.login import current_user
if not hasattr(current_user, "id"):
return make_response(gettext(u"Vous ne pouvez pas passer de commander si vous n'êtes pas connecté."), 400)

# Get state "En attente"
try:
state = db.session.query(StateOrder).filter(StateOrder.name=="En attente").one()
except:
return make_response(gettext(u"L'état 'En attente' est inexistant."), 400)

# Create menu
# TODO: generate order number !
order = Order(number=1, date=date, client_id=current_user.id, state_id=state.id, address_id=address_id, restaurant_id=restaurant.id)

# Create line order
if 'dishes' not in datas:
return make_response(gettext(u"Une commande doit comporté au moins un plat."), 400)

for dish in datas['dishes']:

if 'dish_id' not in dish or 'quantity' not in dish:
return make_response(gettext(u"Une erreur s'est produite."), 400)

try:
quantity = int(dish['quantity'])
except:
return make_response(gettext(u"La quantité doit être un nombre entier."), 400)

try:
dish_id = int(dish['dish_id'])
except:
return make_response(gettext(u"dish_id doit être un identifiant."), 400)

order.lines_order.append(LineOrder(dish_id=dish_id, quantity=quantity))


# Add menu
db.session.add(order)

Expand All @@ -188,8 +188,8 @@ def create():
response.mimetype = 'application/json'

return response


# Update menu
@orders.route('/<int:id>', methods=['PUT', 'OPTIONS'])
def update(id):
Expand All @@ -198,7 +198,7 @@ def update(id):
Method: *PUT*
URI: */orders/id*
"""

# Get request values
datas = request.values

Expand All @@ -208,33 +208,33 @@ def update(id):
# Check menu
if order is None:
return make_response(gettext(u"La commande n'existe pas."), 400)

# Check date
if 'date' in datas:
try:
date = datetime.datetime.strptime(datas['date'], '%Y-%m-%dT%H:%M:%S.%fZ')
except:
return make_response(gettext(u"Le format de la date est invalide."), 400)

order.date = date

# Check state
if 'state_id' in datas:
state = db.session.query(StateOrder).get(datas["state_id"])
if state is None:
return make_response(gettext(u"L'état est inexistant."), 400)

order.state_id = state.id

# SMS Notification
# if app.config['TESTING'] is False: # pragma: no cover
# client = TwilioRestClient(TwilioConfig.ACCOUNT_SID, TwilioConfig.AUTH_TOKEN)
# client.messages.create(
# to="+15142902316",
# to="+15144429905",
# from_="+14387932148",
# body=u"Bonjour votre commande n°%s est passée dans le statut: %s." % (order.number, state.name),
# )

# Commit
try:
db.session.commit()
Expand All @@ -248,7 +248,7 @@ def update(id):
response.mimetype = 'application/json'

return response

# Delete a menu
@orders.route('/<int:id>', methods=['DELETE', 'OPTIONS'])
def delete(id):
Expand All @@ -265,7 +265,7 @@ def delete(id):
# Check menu
if order is None:
return make_response(gettext(u"La commande n'existe pas."), 404)

# Delete menu
db.session.delete(order)

Expand Down
44 changes: 28 additions & 16 deletions webserver/controllers/restaurateurs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-

from flask import Blueprint, json, make_response, request
from flask import Blueprint, make_response, request
from flask.ext.babel import gettext
from webserver import db
from webserver.lib.base import jsonify
Expand All @@ -10,6 +10,7 @@
# Define blueprint
restaurateurs = Blueprint('restaurateurs', __name__)


# Get list
@restaurateurs.route('', methods=['GET', 'OPTIONS'])
def list():
Expand All @@ -30,6 +31,7 @@ def list():

return response


# Get one restaurateur
@restaurateurs.route('/<int:id>', methods=['GET', 'OPTIONS'])
def index(id):
Expand Down Expand Up @@ -133,7 +135,7 @@ def create():
restaurateur = Restaurateur(firstname=datas['firstname'], lastname=datas['lastname'], phone=datas['phone'], address=datas['address'], zipcode=datas['zipcode'], city=datas['city'], country=country, mail=datas['mail'], password=datas['password'])
db.session.flush()
restaurateur.create_order_address()

# Check birthdate
if 'birthdate' in datas:
try:
Expand Down Expand Up @@ -203,6 +205,14 @@ def update(id):
return make_response(gettext(u"Le prénom doit être une chaine de caractère."), 400)
restaurateur.lastname = datas['lastname']

# Check mail
if 'mail' in datas:
if not isinstance(datas['mail'], (str, unicode)):
return make_response(gettext(u"L'adresse mail doit être une chaine de caractère."), 400)
if len(db.session.query(Personne).filter(Personne.mail == datas['mail']).all()) > 1:
return make_response(gettext(u"L'adresse mail est deja utilisee par un utilisateur."), 400)
restaurateur.mail = datas['mail']

# Check password
if 'password' in datas:
if not isinstance(datas['password'], (str, unicode)):
Expand Down Expand Up @@ -261,22 +271,23 @@ def update(id):

# Check restaurateur
if 'restaurant_id' in datas:
try:
restaurant_id = int(datas['restaurant_id'])
except Exception: # pragma: no cover
return make_response(gettext(u"restaurant_id doit être un identifiant."), 400)
if datas['restaurant_id'] == 'no_restaurant':
restaurateur.restaurant = None
else:
try:
restaurant_id = int(datas['restaurant_id'])
except Exception: # pragma: no cover
return make_response(gettext(u"restaurant_id doit être un identifiant."), 400)

restaurant = db.session.query(Restaurant).get(restaurant_id)
if restaurant is None:
return make_response(gettext(u"Le restaurant n'existe pas."), 404)
restaurant = db.session.query(Restaurant).get(restaurant_id)
if restaurant is None:
return make_response(gettext(u"Le restaurant n'existe pas."), 404)

if restaurant.restaurateur is not None:
if restaurant.restaurateur.id != restaurateur.id:
return make_response(gettext(u"Le restaurant est déjà assigné à un restaurateur."), 400)
if restaurant.restaurateur is not None:
if restaurant.restaurateur.id != restaurateur.id:
return make_response(gettext(u"Le restaurant est déjà assigné à un restaurateur."), 400)

restaurateur.restaurant = restaurant
else:
restaurateur.restaurant = None
restaurateur.restaurant = restaurant

# Commit
try:
Expand All @@ -292,6 +303,7 @@ def update(id):

return response


# Delete a restaurateur
@restaurateurs.route('/<int:id>', methods=['DELETE', 'OPTIONS'])
def delete(id):
Expand Down Expand Up @@ -327,4 +339,4 @@ def delete(id):
response.status_code = 200
response.mimetype = 'application/json'

return response
return response

0 comments on commit 46e8236

Please sign in to comment.