Skip to content

Commit

Permalink
add delete order service
Browse files Browse the repository at this point in the history
  • Loading branch information
William MURA authored and William MURA committed Nov 5, 2014
1 parent f278d21 commit 5d2f7b4
Show file tree
Hide file tree
Showing 7 changed files with 373 additions and 12 deletions.
61 changes: 60 additions & 1 deletion webserver/controllers/orders.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
from flask.ext.babel import gettext
from webserver import db, app
from webserver.lib.base import jsonify
from webserver.models import Order, StateOrder, Client
from webserver.models import Order, StateOrder, Client, LineOrder

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

from sqlalchemy.orm import lazyload

import datetime
import werkzeug

Expand Down Expand Up @@ -115,7 +117,30 @@ def create():
# Create menu
# TODO: generate order number !
order = Order(number=1, date=date, client_id=current_user.id, state_id=state.id)
#db.session.flush()

# 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 Down Expand Up @@ -191,4 +216,38 @@ def update(id):
response.status_code = 200
response.mimetype = 'application/json'

return response

# Delete a menu
@orders.route('/<int:id>', methods=['DELETE', 'OPTIONS'])
def delete(id):
""" Delete one order by id.
Method: *DELETE*
URI: */orders/id*
"""

# Query
query = db.session.query(Order).options(lazyload('*'))
order = query.get(id)

# Check menu
if order is None:
return make_response(gettext(u"La commande n'existe pas."), 404)

# Delete menu
db.session.delete(order)

# Commit
try:
db.session.commit()
except Exception: # pragma: no cover
db.session.rollback()
return make_response(gettext(u"Dûe a une erreur inconnu, la commande ne peut pas être supprimée."), 500)

# Build the response
response = make_response(jsonify(order.to_dict(lines_order=False)))
response.status_code = 200
response.mimetype = 'application/json'

return response
26 changes: 26 additions & 0 deletions webserver/models/address.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from webserver.models import Base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship

class Address(Base):
__tablename__ = 'address'

id = Column(Integer, primary_key=True)
address = Column(String(100), nullable=False)
zipcode = Column(String(100), nullable=False)
city = Column(String(100), nullable=False)
country_id = Column(Integer, ForeignKey('country.id'))
country = relationship("Country")

def to_dict(self):
my_dict = dict()

my_dict['address'] = self.address
my_dict['zipcode'] = self.zipcode
my_dict['city'] = self.city

if self.country:
my_dict['country_id'] = self.country_id
my_dict['country'] = self.country.to_dict()

return my_dict
9 changes: 8 additions & 1 deletion webserver/models/line_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,11 @@ class LineOrder(Base):
dish_id = Column(Integer, ForeignKey('dish.id'))
dish = relationship("Dish")

order_id = Column(Integer, ForeignKey('order.id'))
order_id = Column(Integer, ForeignKey('order.id'))

def to_dict(self, dishes=True):
my_dict = dict()

my_dict['id'] = self.id
my_dict['dish'] = self.dish.to_dict()
my_dict['quantity'] = self.quantity
6 changes: 3 additions & 3 deletions webserver/models/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ class Order(Base):

lines_order = relationship("LineOrder", cascade="save-update, merge, delete")

def to_dict(self, dishes=True):
def to_dict(self, lines_order=True):
my_dict = dict()

my_dict['id'] = self.id
my_dict['number'] = self.number
my_dict['date'] = unicode(self.date)
my_dict['client'] = self.client.to_dict() if self.client else None

if dishes:
my_dict['lines_orders'] = [{'dish': so.dish.to_dict(), 'quantity': so.quantity} for so in self.lines_order]
if lines_order:
my_dict['lines_orders'] = [so.to_dict() for so in self.lines_order]

return my_dict
24 changes: 23 additions & 1 deletion webserver/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
db.create_all()

# Import models
from webserver.models import Client, Country, Dish, Entrepreneur, Livreur, Menu, Order, Personne, Restaurant, Restaurateur, StateOrder
from webserver.models import Client, Country, Dish, Entrepreneur, Livreur, LineOrder, Menu, Order, Personne, Restaurant, Restaurateur, StateOrder

# Import others
import datetime
Expand Down Expand Up @@ -123,6 +123,28 @@ def delete_livreurs():
delete_countries()


# LineOrder
def build_line_order(id, order_id, dish_id=None, quantity=1):
""" Builder to create a livreur in database """

if dish_id is None:
build_dish(id=id)
dish_id=id

line_order = LineOrder(id=id, dish_id=dish_id, quantity=quantity, order_id=order_id)
db.session.add(line_order)

return line_order

def delete_lines_order():
""" Remove all line order from database """

for lo in db.session.query(LineOrder).all():
db.session.delete(lo)

delete_dishes()


# Menu
def build_menu(id, name="Menu de printemps", restaurant_id=None):
""" Builder to create a menu in database """
Expand Down
118 changes: 118 additions & 0 deletions webserver/tests/functional/orders/test_delete.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# -*- coding: utf-8 -*-

from webserver import db
from webserver.models import LineOrder, Order
from webserver.tests import build_order, build_line_order, build_dish
from webserver.tests import delete_orders, delete_lines_order, delete_dishes
from webserver.tests.functional import FunctionalTest


class Exists(FunctionalTest):
""" Check if the webservice exists """

@classmethod
def setup_class(cls):
""" Add database fixtures """

build_order(id=5)
db.session.commit()

@classmethod
def teardown_class(cls):
""" Clear database fixtures """

delete_orders()
db.session.commit()

def test_exists(self):
""" DELETE /orders/id: exists """

# Check request
response = self.delete('/orders/5')
assert response.status_code != 404
assert response.status_code != 500


class UnknownParameters(FunctionalTest):
""" Check with no datas """

@classmethod
def setup_class(cls):
""" Add database fixtures """

pass

@classmethod
def teardown_class(cls):
""" Clear database fixtures """

pass

def test_unkown_id(self):
""" DELETE /orders/id: with unkown id """

# Check request
response = self.delete('/orders/5')
assert response.status_code == 404
assert response.data == "La commande n'existe pas."


class Delete(FunctionalTest):
""" Check with valid data """

@classmethod
def setup_class(cls):
""" Add database fixtures """

build_order(id=5)
build_order(id=10)

build_line_order(id=20, order_id=10)
build_line_order(id=21, order_id=10)

db.session.commit()

@classmethod
def teardown_class(cls):
""" Clear database fixtures """

delete_orders()
delete_lines_order()

db.session.commit()

def test_delete(self):
""" DELETE /orders/id: with valid data """

# Check request
response = self.delete('/orders/5')
assert response.status_code == 200

# Check response
result = self.parse(response.data)
assert 'id' in result

# Check in database
order = db.session.query(Order).get(result['id'])
assert order is None

def test_delete_with_dishes(self):
""" DELETE /orders/id: with dishes """

# Check request
response = self.delete('/orders/10')
assert response.status_code == 200

# Check response
result = self.parse(response.data)
assert 'id' in result

# Check in database
order = db.session.query(Order).get(result['id'])
assert order is None

lo1 = db.session.query(LineOrder).get(20)
assert lo1 is None

lo2 = db.session.query(LineOrder).get(21)
assert lo2 is None
Loading

0 comments on commit 5d2f7b4

Please sign in to comment.