This repository has been archived by the owner on Dec 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
turnipCalculator.py
512 lines (474 loc) · 17.2 KB
/
turnipCalculator.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
"""
turnipCalculator.py
Contains all the functions for adding a user's turnip pricing to
the turnip Database as well as calculating turnip price trends.
"""
import boto3
import turnips.meta
from boto3.dynamodb.conditions import Key
import datetime
import errors
import os
from dotenv import load_dotenv
load_dotenv(".env")
# Starts the dynamoDB connection
session = boto3.Session(profile_name='default')
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ.get("turnipDB_Table"))
def addData(discordID, date, time, bells):
"""
adds Turnip Price data to the database
:param discordID: str
User's Discord User ID
:param date: datetime
The date to add the data for
:param time: str
the time of the turnip price, Either AM or PM
:param bells: int
the price of turnip sale
:return: True if operation successful
"""
# Works out the date for the beginning of the week
date = date.date()
beginningOfWeek = date - datetime.timedelta(days=date.weekday())
day = date.strftime('%A')
# Works out the field to place the data into.
if time == 'AM':
day = day + '_AM'
elif time == 'PM':
day = day + '_PM'
else:
raise errors.InvalidDateTime('Invalid time operator')
# Check that the day generated isn't Sunday
if "Sunday" in day:
raise errors.InvalidPeriod()
try:
# Check is if an entry is already available for the user
response = table.query(
KeyConditionExpression=Key('discordID').eq(str(discordID)) &
Key('weekBegining').eq(str(beginningOfWeek.strftime('%d/%m/%Y')))
)
# If there isn't we create a new base entry to work from
if len(response['Items']) == 0:
table.put_item(
Item={
'discordID': str(discordID),
'weekBegining': str(beginningOfWeek.strftime('%d/%m/%Y')),
'timeline': {}
}
)
# Then we update the entry available on database with the new turnip data
table.update_item(
Key={
'discordID': str(discordID),
'weekBegining': str(beginningOfWeek.strftime('%d/%m/%Y'))
},
UpdateExpression="set timeline.{} = :b".format(day),
ExpressionAttributeValues={
':b': int(bells)
},
ReturnValues="UPDATED_NEW"
)
except Exception:
raise errors.AWSError("Unable to interface with backend")
return True
def numericalTimeSlot(day) -> int:
"""
Returns the numerical day of thr timeslot given
:param day: str
the day to turn into
:return: int
The corresponding numerical time slot
"""
switch = {
"Sunday_AM": 1,
"Monday_AM": 2,
"Monday_PM": 3,
"Tuesday_AM": 4,
"Tuesday_PM": 5,
"Wednesday_AM": 6,
"Wednesday_PM": 7,
"Thursday_AM": 8,
"Thursday_PM": 9,
"Friday_AM": 10,
"Friday_PM": 11,
"Saturday_AM": 12,
"Saturday_PM": 13
}
return switch.get(day, -1)
def timeSlotToStr(timeSlot) -> str:
"""
Returns the time slot str from a numerical time slot
:param timeSlot: int
Time slot between 1-13
:return: str
The string for the time slot it is
"""
switch = {
1: "Sunday_AM",
2: "Monday_AM",
3: "Monday_PM",
4: "Tuesday_AM",
5: "Tuesday_PM",
6: "Wednesday_AM",
7: "Wednesday_PM",
8: "Thursday_AM",
9: "Thursday_PM",
10: "Friday_AM",
11: "Friday_PM",
12: "Saturday_AM",
13: "Saturday_PM"
}
return switch.get(timeSlot, "Invalid")
class TurnipClass:
"""
A class for dealing with creating models and handing the model the data
in the correct order.
"""
Sunday_AM = None
Monday_AM = None
Monday_PM = None
Tuesday_AM = None
Tuesday_PM = None
Wednesday_AM = None
Wednesday_PM = None
Thursday_AM = None
Thursday_PM = None
Friday_AM = None
Friday_PM = None
Saturday_AM = None
Saturday_PM = None
def addPrice(self, period, bells):
"""
Add the price and period to objects
:param period: int
date period
:param bells: int
Sale price
:return: boolean
if successful
"""
try:
bells = int(bells)
except ValueError:
raise ValueError("Give bells as an Int")
if period == 1:
self.Sunday_AM = bells
elif period == 2:
self.Monday_AM = bells
elif period == 3:
self.Monday_PM = bells
elif period == 4:
self.Tuesday_AM = bells
elif period == 5:
self.Tuesday_PM = bells
elif period == 6:
self.Wednesday_AM = bells
elif period == 7:
self.Wednesday_PM = bells
elif period == 8:
self.Thursday_AM = bells
elif period == 9:
self.Thursday_PM = bells
elif period == 10:
self.Friday_AM = bells
elif period == 11:
self.Friday_PM = bells
elif period == 12:
self.Saturday_AM = bells
elif period == 13:
self.Saturday_PM = bells
else:
raise ValueError("period doesn't exist")
return True
def createModel(self):
"""
Creates the model form the object fields
:return: turnips.meta.MetaModel
turnip model
"""
if self.Sunday_AM is not None:
turnipModel = turnips.meta.MetaModel.blank(self.Sunday_AM)
else:
turnipModel = turnips.meta.MetaModel.blank()
if self.Monday_AM is not None:
turnipModel.fix_price(2, self.Monday_AM)
if self.Monday_PM is not None:
turnipModel.fix_price(3, self.Monday_PM)
if self.Tuesday_AM is not None:
turnipModel.fix_price(4, self.Tuesday_AM)
if self.Tuesday_PM is not None:
turnipModel.fix_price(5, self.Tuesday_PM)
if self.Wednesday_AM is not None:
turnipModel.fix_price(6, self.Wednesday_AM)
if self.Wednesday_PM is not None:
turnipModel.fix_price(7, self.Wednesday_PM)
if self.Thursday_AM is not None:
turnipModel.fix_price(8, self.Thursday_AM)
if self.Thursday_PM is not None:
turnipModel.fix_price(9, self.Thursday_PM)
if self.Friday_AM is not None:
turnipModel.fix_price(10, self.Friday_AM)
if self.Friday_PM is not None:
turnipModel.fix_price(11, self.Friday_PM)
if self.Saturday_AM is not None:
turnipModel.fix_price(12, self.Saturday_AM)
if self.Saturday_PM is not None:
turnipModel.fix_price(13, self.Saturday_PM)
return turnipModel
def createTurnipModel(discordID, date):
"""
Creates the turnip model for a user at a specified week
:param discordID: str
the User's Discord ID
:param date: dateTime
The date of the week you want to look for
:return: turnip.model
The turnip model for the specified date and user
"""
date = date.date()
beginningOfWeek = date - datetime.timedelta(days=date.weekday())
response = table.query(
KeyConditionExpression=Key('discordID').eq(str(discordID)) &
Key('weekBegining').eq(str(beginningOfWeek.strftime('%d/%m/%Y')))
)
if len(response['Items']) == 0:
raise errors.NoData("No data available to make model")
elif len(response['Items']) > 1:
raise errors.AWSError("System Error, more than one response returned")
# A lookup error should in theory never happen because discordID and weekBegining as tied together
# as a dual pair key, so each set of data requires both attributes to exist and one the combo can only
# exist in one entry together
# Create blank object to hold data
turnipInstance = TurnipClass()
i = response['Items'][0]
for day in i['timeline']:
turnipInstance.addPrice(numericalTimeSlot(str(day)), int(i['timeline'][day]))
turnipModel = turnipInstance.createModel()
return turnipModel
def addBuyPrice(discordID, date, bells):
"""
Ass the buying of turnips price to DB
:param discordID: str
user's DiscordID
:param date: datetime
the date of when the turnips where bought
:param bells: int
The cost of the turnips
:return: boolean
if successful
"""
# Works out the date for the beginning of the week
if date.strftime('%A') == 'Sunday': # If it's a sunday we need to save the price for the next week actually
date = date + datetime.timedelta(days=2) # So we work out the next week.
date = date.date()
beginningOfWeek = date - datetime.timedelta(days=date.weekday())
day = 'Sunday_AM'
if int(bells) < 90 or int(bells) > 110:
raise errors.BellsOutOfRange("Purchase price must be between 90-110 bells")
try:
# Check is if an entry is already available for the user
response = table.query(
KeyConditionExpression=Key('discordID').eq(str(discordID)) &
Key('weekBegining').eq(str(beginningOfWeek.strftime('%d/%m/%Y')))
)
# If there isn't we create a new base entry to work from
if len(response['Items']) == 0:
table.put_item(
Item={
'discordID': str(discordID),
'weekBegining': str(beginningOfWeek.strftime('%d/%m/%Y')),
'timeline': {
'Sunday_AM': int(bells)
}
}
)
return True
# Then we update the entry available on database with the new turnip data
table.update_item(
Key={
'discordID': str(discordID),
'weekBegining': str(beginningOfWeek.strftime('%d/%m/%Y'))
},
UpdateExpression="set timeline.{} = :b".format(day),
ExpressionAttributeValues={
':b': int(bells)
},
ReturnValues="UPDATED_NEW"
)
except Exception as e:
raise errors.AWSError(e)
return True
def clearErrors(discordID, date) -> str:
"""
Attempts to remove data causing errors from Database
:param date: datetime
The datetime to correct for
:param discordID: str
The user's Discord ID
:return: str
The list of day/times removes
"""
# Work out the beginning of the week
beginningOfWeek = date - datetime.timedelta(days=date.weekday())
# We check if we actually need to fix errors by making sure data already present can't produce a report
try:
if bool((createTurnipModel(discordID, datetime.datetime.now()).summary())) is True:
raise errors.DataCorrect("Nothing to correct")
except AttributeError:
raise errors.NoData("No data available to make model")
except LookupError as e:
raise errors.InternalError(e)
# We query the DB for the current copy of the data
response = table.query(
KeyConditionExpression=Key('discordID').eq(str(discordID)) &
Key('weekBegining').eq(str(beginningOfWeek.strftime('%d/%m/%Y')))
)
if len(response['Items']) == 0:
raise errors.NoData("No data available to make model")
elif len(response['Items']) > 1:
raise errors.InternalError("Too Many Responses")
# we take the response and for each day we turn it into it's numerical id
dates = []
removedDates = []
i = response['Items'][0]
for day in i['timeline']: # for each day in the response
timeSlot = numericalTimeSlot(str(day))
if timeSlot != 1:
dates.append(timeSlot)
dates.sort() # Sort numerical dates out in order
for x in range(len(dates)): # for each date in the list
lastDate = dates.pop() # pop date
removedDates.append(timeSlotToStr(lastDate).replace("_", " ")) # add it to the list of removed dates
try:
# We remove that date we popped from the the DB
table.update_item(
Key={
'discordID': str(discordID),
'weekBegining': str(beginningOfWeek.strftime('%d/%m/%Y'))
},
UpdateExpression="Remove timeline.{}".format(timeSlotToStr(lastDate)),
ReturnValues="UPDATED_NEW"
)
except Exception as e:
raise errors.AWSError(e)
# We then check if we can then create a model.
if bool((createTurnipModel(discordID, datetime.datetime.now()).summary())) is True:
# if we can create a model, then we break
break
# if not the loop continues to remove dates in order till we can create a model
# if we finish the loop, then we return all the dates removed.
strReply = ""
for date in removedDates:
strReply = strReply + "{}, ".format(date)
return strReply
# We don't remove the Sunday_AM reference because we error check that value
# before it's entered anyway so will always be within range being the first value
def deleteTurnipData(discordID: str) -> int:
"""
Delete all turnip data from a given user
:param discordID: str
Discord ID of the User we want to delete turnip data for
:return: bool
If the operation was successful or not
"""
deleteCount = 0
try:
# We query the DB for all the entries the user has made, so we can get the sort key needed to delete items
response = table.query(
KeyConditionExpression=Key('discordID').eq(str(discordID))
)
if response['Count'] <= 0:
raise errors.NoData("No data in database")
else:
for entries in response['Items']:
deleteResponse = table.delete_item(
Key={
'discordID': discordID,
'weekBegining': entries['weekBegining']
}
)
if deleteResponse["ResponseMetadata"]['HTTPStatusCode'] != 200:
raise errors.AWSError("Unable to delete entry")
else:
deleteCount = deleteCount + 1
except Exception as e:
pass
return deleteCount
def removePrice(discordID: str, date: datetime, time: str) -> bool:
"""
Removes a price entry for a specified date and time
:param discordID: str
Discord ID of user
:param date: datetime
dateTme to delete entry for
:param time: str
Either PM or AM (Doesn't matter for Sunday)
:return: bool
If delete was successful or not.
"""
date = date.date()
beginningOfWeek = date - datetime.timedelta(days=date.weekday())
day = date.strftime('%A')
# Works out the field to place the data into.
if day == "Sunday":
day = "Sunday_AM"
elif time == 'AM':
day = day + '_AM'
elif time == 'PM':
day = day + '_PM'
else: # If an invalid date was given
raise errors.InvalidDateTime('Invalid time operator')
# Issue update command to DB to delete field
updateResponse = table.update_item(
Key={
'discordID': discordID,
'weekBegining': str(beginningOfWeek.strftime('%d/%m/%Y'))
},
UpdateExpression='REMOVE timeline.{}'.format(day),
ReturnValues='UPDATED_OLD',
)
# If we get something other than a 200, we raise an error from AWS
if updateResponse['ResponseMetadata']['HTTPStatusCode'] != 200:
raise errors.AWSError("Unable to delete entry on DB")
# Then we check if the response given has the date we asked
if "Attributes" in updateResponse:
if day in updateResponse['Attributes']['timeline']:
return True # If it does we return true
return False # Else we return false
def daySort(day):
day = day.split(" ")[0]
return {'Sunday': 0,
'Monday': 1,
"Tuesday": 2,
"Wednesday": 3,
"Thursday": 4,
"Friday": 5,
"Saturday": 6}[day]
def getPrices(discordID: str, date: datetime) -> dict:
"""
Get a dict with all the prices the user has for a week.
:param date: datetime
the datetime to look for
:param discordID: str
The discord ID of the user
:return: dict
A dict will all the days and the prices they've entered
"""
date = date.date()
beginningOfWeek = date - datetime.timedelta(days=date.weekday())
response = table.query(
KeyConditionExpression=Key('discordID').eq(str(discordID)) &
Key('weekBegining').eq(str(beginningOfWeek.strftime('%d/%m/%Y')))
)
if len(response['Items']) == 0:
raise errors.NoData("No data available to make model")
tempDict = {}
i = response['Items'][0]
for day in i['timeline']:
if "Sunday" in day:
tempDict["Sunday Buy Price"] = int(i['timeline'][day])
else:
date = day.split("_")
tempDict["{} {}".format(date[0], date[1])] = int(i['timeline'][day])
return dict(sorted(tempDict.items(), key=lambda t: daySort(t[0])))