This repository has been archived by the owner on Jan 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathshoppinglist_controller.py
262 lines (206 loc) · 8.37 KB
/
shoppinglist_controller.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
from flask import jsonify, Blueprint
from flask_jwt_extended import current_user, jwt_required
from app import db
from app.models import Item, Shoppinglist, History, Status, Association, ShoppinglistItems
from app.helpers import validate_args, authorize_household
from .schemas import (RemoveItem, UpdateDescription,
AddItemByName, CreateList, AddRecipeItems, GetItems, UpdateList, GetRecentItems)
from app.errors import NotFoundRequest, InvalidUsage
from datetime import datetime, timedelta, timezone
import app.util.description_merger as description_merger
shoppinglist = Blueprint('shoppinglist', __name__)
shoppinglistHousehold = Blueprint('shoppinglist', __name__)
@shoppinglistHousehold.route('', methods=['POST'])
@jwt_required()
@authorize_household()
@validate_args(CreateList)
def createShoppinglist(args, household_id):
return jsonify(Shoppinglist(name=args['name'], household_id=household_id).save().obj_to_dict())
@shoppinglistHousehold.route('', methods=['GET'])
@jwt_required()
@authorize_household()
def getShoppinglists(household_id):
shoppinglists = Shoppinglist.all_from_household(household_id)
return jsonify([e.obj_to_dict() for e in shoppinglists])
@shoppinglist.route('/<int:id>', methods=['POST'])
@jwt_required()
@validate_args(UpdateList)
def updateShoppinglist(args, id):
shoppinglist = Shoppinglist.find_by_id(id)
if not shoppinglist:
raise NotFoundRequest()
shoppinglist.checkAuthorized()
if 'name' in args:
shoppinglist.name = args['name']
shoppinglist.save()
return jsonify(shoppinglist.obj_to_dict())
@shoppinglist.route('/<int:id>', methods=['DELETE'])
@jwt_required()
def deleteShoppinglist(id):
shoppinglist = Shoppinglist.find_by_id(id)
if not shoppinglist:
raise NotFoundRequest()
shoppinglist.checkAuthorized()
if shoppinglist.isDefault():
raise InvalidUsage()
shoppinglist.delete()
return jsonify({'msg': 'DONE'})
@shoppinglist.route('/<int:id>/item/<int:item_id>', methods=['POST'])
@jwt_required()
@validate_args(UpdateDescription)
def updateItemDescription(args, id, item_id):
con = ShoppinglistItems.find_by_ids(id, item_id)
if not con:
raise NotFoundRequest()
con.shoppinglist.checkAuthorized()
con.description = args['description'] or ''
con.save()
return jsonify(con.obj_to_item_dict())
@shoppinglist.route('/<int:id>/items', methods=['GET'])
@jwt_required()
@validate_args(GetItems)
def getAllShoppingListItems(args, id):
shoppinglist = Shoppinglist.find_by_id(id)
if not shoppinglist:
raise NotFoundRequest()
shoppinglist.checkAuthorized()
orderby = [Item.name]
if ('orderby' in args):
if (args['orderby'] == 1):
orderby = [Item.ordering == 0, Item.ordering]
elif (args['orderby'] == 2):
orderby = [Item.name]
items = ShoppinglistItems.query.filter(
ShoppinglistItems.shoppinglist_id == id).join(
ShoppinglistItems.item).order_by(*orderby, Item.name).all()
return jsonify([e.obj_to_item_dict() for e in items])
@shoppinglist.route('/<int:id>/recent-items', methods=['GET'])
@jwt_required()
@validate_args(GetRecentItems)
def getRecentItems(args, id):
shoppinglist = Shoppinglist.find_by_id(id)
if not shoppinglist:
raise NotFoundRequest()
shoppinglist.checkAuthorized()
items = History.get_recent(id, args["limit"])
return jsonify([e.item.obj_to_dict() | {'description': e.description} for e in items])
def getSuggestionsBasedOnLastAddedItems(id, item_count):
suggestions = []
# subquery for item ids which are on the shoppinglist
subquery = db.session.query(ShoppinglistItems.item_id).filter(
ShoppinglistItems.shoppinglist_id == id).subquery()
# suggestion based on recently added items
ten_minutes_back = datetime.now() - timedelta(minutes=10)
recently_added = History.query.filter(
History.shoppinglist_id == id,
History.status == Status.ADDED,
History.created_at > ten_minutes_back).order_by(
History.created_at.desc()).limit(3)
for recent in recently_added:
assocs = Association.query.filter(
Association.antecedent_id == recent.id,
Association.consequent_id.notin_(subquery)).order_by(
Association.lift.desc()).limit(item_count)
for rule in assocs:
suggestions.append(rule.consequent)
item_count -= 1
return suggestions
def getSuggestionsBasedOnFrequency(id, item_count):
suggestions = []
# subquery for item ids which are on the shoppinglist
subquery = db.session.query(ShoppinglistItems.item_id).filter(
ShoppinglistItems.shoppinglist_id == id).subquery()
# suggestion based on overall frequency
if item_count > 0:
suggestions = Item.query.filter(Item.id.notin_(subquery)).order_by(
Item.support.desc(), Item.name).limit(item_count)
return suggestions
@shoppinglist.route('/<int:id>/suggested-items', methods=['GET'])
@jwt_required()
def getSuggestedItems(id):
shoppinglist = Shoppinglist.find_by_id(id)
if not shoppinglist:
raise NotFoundRequest()
shoppinglist.checkAuthorized()
item_suggestion_count = 9
suggestions = []
suggestions += getSuggestionsBasedOnLastAddedItems(
id, item_suggestion_count)
suggestions += getSuggestionsBasedOnFrequency(
id, item_suggestion_count - len(suggestions))
return jsonify([item.obj_to_dict() for item in suggestions])
@shoppinglist.route('/<int:id>/add-item-by-name', methods=['POST'])
@jwt_required()
@validate_args(AddItemByName)
def addShoppinglistItemByName(args, id):
shoppinglist = Shoppinglist.find_by_id(id)
if not shoppinglist:
raise NotFoundRequest()
shoppinglist.checkAuthorized()
item = Item.find_by_name(shoppinglist.household_id, args['name'])
if not item:
item = Item.create_by_name(shoppinglist.household_id, args['name'])
con = ShoppinglistItems.find_by_ids(shoppinglist.id, item.id)
if not con:
description = args['description'] if 'description' in args else ''
con = ShoppinglistItems(description=description)
con.created_by = current_user.id
con.item = item
con.shoppinglist = shoppinglist
con.save()
History.create_added(shoppinglist, item, description)
return jsonify(item.obj_to_dict())
@shoppinglist.route('/<int:id>/item', methods=['DELETE'])
@jwt_required()
@validate_args(RemoveItem)
def removeShoppinglistItem(args, id):
shoppinglist = Shoppinglist.find_by_id(id)
if not shoppinglist:
raise NotFoundRequest()
shoppinglist.checkAuthorized()
item = Item.find_by_id(args['item_id'])
if not item:
item = Item.find_by_name(args['name'])
if not item:
raise NotFoundRequest()
con = ShoppinglistItems.find_by_ids(id, args['item_id'])
description = con.description
con.delete()
removed_at = None
if 'removed_at' in args:
removed_at = datetime.fromtimestamp(
args['removed_at']/1000, timezone.utc)
History.create_dropped(shoppinglist, item, description, removed_at)
return jsonify({'msg': "DONE"})
@shoppinglist.route('/<int:id>/recipeitems', methods=['POST'])
@jwt_required()
@validate_args(AddRecipeItems)
def addRecipeItems(args, id):
shoppinglist = Shoppinglist.find_by_id(id)
if not shoppinglist:
raise NotFoundRequest()
shoppinglist.checkAuthorized()
try:
for recipeItem in args['items']:
item = Item.find_by_id(recipeItem['id'])
if item:
description = recipeItem['description']
con = ShoppinglistItems.find_by_ids(shoppinglist.id, item.id)
if con:
# merge descriptions
con.description = description_merger.merge(
con.description, description)
db.session.add(con)
else:
con = ShoppinglistItems(description=description)
con.created_by = current_user.id
con.item = item
con.shoppinglist = shoppinglist
db.session.add(con)
db.session.add(
History.create_added_without_save(shoppinglist, item))
db.session.commit()
except Exception as e:
db.session.rollback()
raise e
return jsonify(item.obj_to_dict())