-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
346 lines (299 loc) · 15.4 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
from flask import jsonify, request
from flask_login import login_required, current_user
from flask_restful import reqparse, abort, Resource
import werkzeug
from data.db_session import get_session
from operations import abort_if_restaurant, abort_if_user
from data.models.menus import Menu
from data.models.menu_items import MenuItem
from data.models.restaurants import Restaurant
from data.models.categories import Category
from data.models.orders import Order
from data.models.order_items import OrderItem
from data.models.restaurant_places import RestaurantPlace
from setup import socketio
# Menu
class MenuItemListResource(Resource):
def get(self, restaurant_id):
restaurant = get_session().query(Restaurant).get(restaurant_id)
if not restaurant:
abort(404)
categories = get_session().query(Category).filter(Category.menu_id == restaurant.menu_id)
response = jsonify({'categories': [category.to_dict(only=('id', 'title', 'menu_items.id', 'menu_items.title', 'menu_items.price')) for category in categories.order_by(Category.id)], 'restaurant': restaurant.to_dict(only=('id', 'title'))})
return response
@login_required
def post(self, restaurant_id):
abort_if_user()
parser = reqparse.RequestParser()
parser.add_argument('item_image', type=werkzeug.datastructures.FileStorage, location='files')
parser.add_argument('title', required=True, type=str, location='values')
parser.add_argument('price', required=True, type=int, location='values')
parser.add_argument('category', required=True, type=str, location='values')
args = parser.parse_args()
# Check to errors
if restaurant_id != current_user.id:
abort(404)
restaurant = get_session().query(Restaurant).filter(Restaurant.id == restaurant_id, current_user.id == restaurant_id).first()
if not restaurant:
abort(404)
nice = True
errors = []
if get_session().query(MenuItem).filter(MenuItem.menu == current_user.menu, MenuItem.title == args['title']).first():
errors.append({'error': 'Продукт с таким именем уже существует', 'error_field': 'title'})
nice = False
if not get_session().query(Category).filter(Category.menu == current_user.menu, Category.title == args['category']).first():
errors.append({'error': 'Такой категории не существует', 'error_field': 'category'})
nice = False
if not nice:
response = jsonify({'successfully': False, 'errors': errors})
return response
menu = get_session().query(Menu).get(current_user.menu_id)
menu_item = MenuItem(
title=args['title'],
price=args['price'],
category=get_session().query(Category).filter(Category.menu == current_user.menu, Category.title == args['category']).first(),
menu=menu
)
menu.items.append(menu_item)
get_session().commit()
if args['item_image']:
f = args['item_image']
menu_item.item_image = f.read()
get_session().commit()
return jsonify({'successfully': True})
class MenuItemResource(Resource):
def get(self, restaurant_id, menu_item_id):
restaurant = get_session().query(Restaurant).get(restaurant_id)
if not restaurant:
abort(404)
menu_item = get_session().query(MenuItem).filter(MenuItem.menu == restaurant.menu, MenuItem.id == menu_item_id).first()
if not menu_item:
abort(404)
response = jsonify(**menu_item.to_dict(only=('title', 'price', 'category.title')), **{'item_image_url': f'/menu_item_image/{menu_item_id}'})
return response
@login_required
def put(self, restaurant_id, menu_item_id):
abort_if_user()
parser = reqparse.RequestParser()
parser.add_argument('item_image', type=werkzeug.datastructures.FileStorage, location='files')
parser.add_argument('title', required=True, type=str, location='values')
parser.add_argument('price', required=True, type=int, location='values')
parser.add_argument('category', required=True, type=str, location='values')
args = parser.parse_args()
if restaurant_id != current_user.id:
abort(404)
restaurant = get_session().query(Restaurant).filter(Restaurant.id == restaurant_id, current_user.id == restaurant_id).first()
if not restaurant:
abort(404)
menu_item = get_session().query(MenuItem).filter(MenuItem.menu == restaurant.menu, MenuItem.id == menu_item_id).first()
if not menu_item:
abort(404)
nice = True
errors = []
if get_session().query(MenuItem).filter(MenuItem.menu == current_user.menu, MenuItem.title == args['title'], MenuItem.id != menu_item_id).first():
errors.append({'error': 'Продукт с таким названием уже существует', 'error_field': 'title'})
nice = False
if not get_session().query(Category).filter(Category.menu == current_user.menu, Category.title == args['category']).first():
errors.append({'error': 'Такой категории не существует', 'error_field': 'category'})
nice = False
if not nice:
response = jsonify({'successfully': False, 'errors': errors})
return response
menu_item.title = args['title']
menu_item.price = args['price']
menu_item.category = get_session().query(Category).filter(Category.menu == current_user.menu, Category.title == args['category']).first()
if args['item_image']:
file_data = request.files['item_image'].read()
if file_data:
menu_item.item_image = file_data
get_session().commit()
return jsonify({'successfully': True})
@login_required
def delete(self, restaurant_id, menu_item_id):
abort_if_user()
if restaurant_id != current_user.id:
abort(404)
restaurant = get_session().query(Restaurant).filter(Restaurant.id == restaurant_id, current_user.id == restaurant_id).first()
if not restaurant:
abort(404)
menu_item = get_session().query(MenuItem).filter(MenuItem.menu == restaurant.menu, MenuItem.id == menu_item_id).first()
if not menu_item:
abort(404)
get_session().delete(get_session().query(MenuItem).filter(MenuItem.id == menu_item_id).first())
get_session().commit()
return jsonify({'successfully': True})
class MenuCategoryListResource(Resource):
def get(self, restaurant_id):
restaurant = get_session().query(Restaurant).get(restaurant_id)
if not restaurant:
abort(404)
categories = get_session().query(Category).filter(Category.menu_id == restaurant.menu_id)
response = jsonify({'categories': [category.to_dict(only=('id', 'title', 'menu_items.id', 'menu_items.title', 'menu_items.price')) for category in categories.order_by(Category.id)], 'restaurant': restaurant.to_dict(only=('id', 'title'))})
return response
@login_required
def post(self, restaurant_id):
abort_if_user()
parser = reqparse.RequestParser()
parser.add_argument('title', required=True, type=str, location='values')
args = parser.parse_args()
if restaurant_id != current_user.id:
abort(404)
restaurant = get_session().query(Restaurant).filter(Restaurant.id == restaurant_id, current_user.id == restaurant_id).first()
if not restaurant:
abort(404)
nice = True
errors = []
if get_session().query(Category).filter(Category.menu == current_user.menu, Category.title == args['title']).first():
errors.append({'error': 'Категория с таким названием уже существует', 'error_field': 'title'})
nice = False
if not nice:
response = jsonify({'successfully': False, 'errors': errors})
return response
menu = get_session().query(Menu).get(current_user.menu_id)
category = Category(
title=args['title']
)
menu.categories.append(category)
get_session().commit()
return jsonify({'successfully': True})
class MenuCategoryResource(Resource):
def get(self, restaurant_id, category_id):
restaurant = get_session().query(Restaurant).get(restaurant_id)
if not restaurant:
abort(404)
category = get_session().query(Category).filter(Category.menu == restaurant.menu, Category.id == category_id).first()
if not category:
abort(404)
response = jsonify(category.to_dict(only=('title',)))
return response
@login_required
def put(self, restaurant_id, category_id):
abort_if_user()
parser = reqparse.RequestParser()
parser.add_argument('title', required=True, type=str, location='values')
args = parser.parse_args()
if restaurant_id != current_user.id:
abort(404)
restaurant = get_session().query(Restaurant).filter(Restaurant.id == restaurant_id, current_user.id == restaurant_id).first()
if not restaurant:
abort(404)
category = get_session().query(Category).filter(Category.id == category_id).first()
if not category:
abort(404)
nice = True
errors = []
if get_session().query(Category).filter(Category.menu == current_user.menu, Category.title == args['title'], Category.id != category_id).first():
errors.append({'error': 'Категория с таким названием уже существует', 'error_field': 'title'})
nice = False
if not nice:
response = jsonify({'successfully': False, 'errors': errors})
return response
category.title = args['title']
get_session().commit()
return jsonify({'successfully': True})
@login_required
def delete(self, restaurant_id, category_id):
abort_if_user()
if restaurant_id != current_user.id:
abort(404)
restaurant = get_session().query(Restaurant).filter(Restaurant.id == restaurant_id, current_user.id == restaurant_id).first()
if not restaurant:
abort(404)
category = get_session().query(Category).filter(Category.id == category_id).first()
if not category:
abort(404)
nice = True
errors = []
if category.menu_items:
errors.append({'error': 'В категории остались продукты', 'error_field': 'menu'})
nice = False
if not nice:
response = jsonify({'successfully': False, 'errors': errors})
return response
get_session().delete(get_session().query(Category).filter(Category.id == category_id).first())
get_session().commit()
return jsonify({'successfully': True})
# Order
def update_order_price(order_id):
order = get_session().query(Order).get(order_id)
order.price = sum([item.menu_item.price * item.count for item in order.order_items])
get_session().commit()
class OrderListResource(Resource):
@login_required
def get(self, order_id):
order = get_session().query(Order).filter(Order.id == order_id).first()
if not order:
abort(404)
if current_user.__class__ == 'User':
if order.user_id != current_user.id:
abort(404)
if current_user.__class__ == 'Restaurant':
if order.restaurant_id == current_user.id:
abort(404)
return jsonify(order.to_dict(only=('id', 'price', 'state', 'restaurant.id', 'restaurant.menu.id', 'restaurant.places.id', 'restaurant.places.title', 'user.id', 'user.name', 'user.surname', 'order_items.id', 'order_items.count', 'order_items.menu_item.title', 'order_items.menu_item.price', 'restaurant_place_id')))
@login_required
def post(self, order_id): # For change state of order
parser = reqparse.RequestParser()
parser.add_argument('new_state', required=True, type=str, location='values')
args = parser.parse_args()
if current_user.__class__.__name__ == 'User':
order = get_session().query(Order).filter(Order.id == order_id, Order.user_id == current_user.id).first()
if not len(order.order_items):
return jsonify({'successfully': False, 'message': 'Empty order'})
allowed_state = ['Awaiting payment']
if current_user.__class__.__name__ == 'Restaurant':
order = get_session().query(Order).filter(Order.id == order_id, Order.restaurant_id == current_user.id).first()
allowed_state = ['In progress', 'Ready', 'Finished']
if not order:
abort(404)
if args['new_state'] not in allowed_state:
abort(403)
socketio.emit('order_change', {'order_id': order_id}, room=f'restaurant_{str(order.restaurant_place_id)}', namespace='/')
socketio.emit('order_change', {'order_id': order_id}, room=f'user_{str(order.user_id)}', namespace='/')
order.state = args['new_state']
get_session().commit()
return jsonify({'successfully': True})
@login_required
def put(self, order_id): # For change data
abort_if_restaurant()
parser = reqparse.RequestParser()
parser.add_argument('restaurant_place_id', required=True, type=int, location='values')
args = parser.parse_args()
order = get_session().query(Order).filter(Order.id == order_id, Order.user_id == current_user.id, Order.state == 'Is not sent').first()
if not order:
abort(404)
if order.user_id != current_user.id:
abort(404)
restaurant_place = get_session().query(RestaurantPlace).filter(RestaurantPlace.id == args['restaurant_place_id'], RestaurantPlace.restaurant_id == order.restaurant_id).first()
if not restaurant_place:
abort(404)
order.restaurant_place_id = restaurant_place.id
get_session().commit()
return jsonify({'successfully': True})
class OrderItemResource(Resource):
@login_required
def put(self, order_id, order_item_id):
abort_if_restaurant()
parser = reqparse.RequestParser()
parser.add_argument('count', required=True, type=int, location='values')
args = parser.parse_args()
order = get_session().query(Order).filter(Order.id == order_id, Order.user_id == current_user.id, Order.state == 'Is not sent').first()
if not order:
abort(404)
order_item = get_session().query(OrderItem).filter(OrderItem.id == order_item_id, OrderItem.order_id == order.id).first()
if not order_item:
abort(404)
order_item.count = args['count']
get_session().commit()
update_order_price(order_id)
return jsonify({'successfully': True})
@login_required
def delete(self, order_id, order_item_id):
abort_if_restaurant()
order = get_session().query(Order).filter(Order.id == order_id, Order.user_id == current_user.id, Order.state == 'Is not sent').first()
if not order:
abort(404)
get_session().delete(get_session().query(OrderItem).filter(OrderItem.id == order_item_id, OrderItem.order_id == order.id).first())
get_session().commit()
update_order_price(order_id)
return jsonify({'successfully': True})