-
Notifications
You must be signed in to change notification settings - Fork 0
/
sheets_api_project.py
384 lines (307 loc) · 11 KB
/
sheets_api_project.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
import datetime as dt
from datetime import *
import sys
import re
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
from googleapiclient import discovery
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name(
'client_secret.json', scope)
service = discovery.build('sheets', 'v4', credentials=creds)
# Spreadsheet ID
spreadsheetId = '1077v4MI09ZDjdiH8ikNJg55nN0qHAXJiqNI6QzIxEgk'
dateformat = '"%m/%d/%Y %H:%M:%S"'
with open('student_list', 'r') as f:
s = f.read().strip()
std_lst = re.split(r'\s', s)
def getEarnings(earningStr, total=False): # Total is false by default
earningStr = earningStr.lower()
if earningStr in std_lst:
range_ = earningStr + '!'
else:
print("No student named {0} !".format(earningStr))
return None # exits method without returning anything
# The A1 notation of the values to retrieve.
range_ = range_ + convertToA1(1, 8)
if total:
valRenderOption = 'UNFORMATTED_VALUE'
else:
valRenderOption = 'FORMATTED_VALUE'
request = service.spreadsheets().values().\
get(spreadsheetId=spreadsheetId,
range=range_,
valueRenderOption=valRenderOption)
response = request.execute()
return(response['values'][0][0])
def getTotalEarnings():
rawEarning = getEarnings('minju', True) + getEarnings('minsuk', True)
print("₩{:,}".format(rawEarning))
# need to change
def calcUnpaidHrs(unpaidStr):
unpaidStr = unpaidStr.lower()
if unpaidStr == 'minju':
range_ = 'Minju!'
elif unpaidStr == 'minsuk':
range_ = 'Minsuk!'
else:
print("No student named " + unpaidStr + "!")
return None # exits method without returning anything
range_ = range_ + 'D2:E'
valRenderOption = 'UNFORMATTED_VALUE'
request = service.spreadsheets().values().\
get(spreadsheetId=spreadsheetId,
range=range_,
valueRenderOption=valRenderOption)
response = request.execute()
values = response['values']
unpaidDays = 0 # Initialise variable
# Add up all unpaid hours
for i in values:
if i[1] == 'N':
unpaidDays += i[0]
# Change time from days to hours in string form
unpaidHrs = str(dt.timedelta(days=unpaidDays))
return unpaidHrs
def convertToA1(rows, col):
aASCII = ord('A') # Int value of 'A'
colASCII = aASCII + (col - 1)
formatedCell = chr(colASCII) + str(rows)
return formatedCell
# Delete function if not necessary
def convertTimeToSec(n):
(h, m) = n.split(':')
secondResult = int(h) * 3600 + int(m) * 60
return secondResult
def updateLesson():
date_error_str = "Invalid format for date! Format: mm/dd/yyyy"
month_error_str = "Month should be between 1 and 12!"
day_error_str = "Day should be between 1 and 31!"
year_error_str = "Year is probably 2019"
date_correct_str = "Format: Format: mm/dd/yyyy"
lessonDate = ''
startTime = ''
endTime = ''
while True:
dateCommand = input("Input date of lesson. If today, type today: ").\
lower()
if dateCommand == 'today':
lessonDate = str(date.today())
(y, m, d) = lessonDate.split('-')
lessonDate = str(m) + '/' + str(d) + '/' + str(y)
elif re.match(r'\d?\d\/\d{2}\/\d{4}', dateCommand):
date_split = re.split(r'/', dateCommand)
if int(date_split[0]) not in range(1, 13):
#print(month_error_str)
print(type(date_split[0]))
continue
elif int(date_split[1]) not in range(1, 32):
print(day_error_str)
continue
elif int(date_split[2]) != 2019:
print(year_error_str)
continue
else:
lessonDate = dateCommand
else:
print(date_error_str)
print(date_correct_str)
continue
print("Confirming date:", lessonDate)
confirm = input("Is this correct? (Y/N)? ").lower()
if confirm == 'y':
break
else:
continue
time_error_str = "Invalid format for Time! Format: hh:mm AMorPM"
while True:
timeCommand = input(
"Input the time the lesson started (i.e. 11:00 AM): ").lower()
if not re.match(r'\d?\d:\d{2}\s(am|pm)', timeCommand):
print(time_error_str)
continue
time_split = re.split(r':|\s', timeCommand)
h, m = int(time_split[0]), int(time_split[1])
# Change to 24 hour time
if time_split[2] == 'pm' and h != 12:
h += 12
try:
startTime = dt.time(h, m)
except ValueError:
print("Invalid range for hours and/or minutes")
continue
print("Confirming start time:", startTime)
confirm = input("Is this correct? (Y/N)? ").lower()
if confirm == 'y':
break
else:
continue
while True:
timeCommand = input(
"Input the time the lesson started (i.e. 11:00 AM): ").lower()
if not re.match(r'\d?\d:\d{2}\s(am|pm)', timeCommand):
print(time_error_str)
continue
time_split = re.split(r':|\s', timeCommand)
h, m = int(time_split[0]), int(time_split[1])
# Change to 24 hour time
if time_split[2] == 'pm' and h != 12:
h += 12
try:
endTime = dt.time(h, m)
except ValueError:
print("Invalid range for hours and/or minutes")
continue
print("Confirming start time:", endTime)
confirm = input("Is this correct? (Y/N)? ").lower()
if confirm == 'y':
break
else:
continue
while True:
student = input("Which student? ").lower()
if student == 'minju':
student_sheet = 0
break
elif student == 'minsuk':
student_sheet = 1741513205
break
else:
print("That student doesn't exist!")
continue
time1 = dt.datetime.combine(dt.date.today(), startTime)
time2 = dt.datetime.combine(dt.date.today(), endTime)
duration = str(dt.timedelta(seconds=(time2 - time1).total_seconds()))[:-3]
pushUpdate(student_sheet, lessonDate, startTime, endTime, duration)
def pushUpdate(sheet, date, time_1, time_2, dur):
batch_update_spreadsheet_request_body = {
# A list of updates to apply to the spreadsheet.
# Requests will be applied in the order they are specified.
# If any request is not valid, no requests will be applied.
"requests": [
{ # Insert row
"insertDimension": {
"range": {
"sheetId": sheet,
"dimension": "ROWS",
"startIndex": 1,
"endIndex": 2
},
"inheritFromBefore": False
}
},
{ # Bold First Row
"repeatCell": {
"range": {
"sheetId": sheet,
"endRowIndex": 1
},
"cell": {
"userEnteredFormat": {
"textFormat": {
"bold": True
}
}
},
"fields": "userEnteredFormat.textFormat.bold"
}
},
{ # Time format column B, C
"repeatCell": {
"range": {
"sheetId": sheet,
"startRowIndex": 1,
"startColumnIndex": 1,
"endColumnIndex": 3
},
"cell": {
"userEnteredFormat": {
"numberFormat": {
"type": "DATE",
"pattern": 'hh:mm A/P".M."'
}
}
},
"fields": "userEnteredFormat.numberFormat"
}
},
{ # Validation for column E
"setDataValidation": {
"range": {
"sheetId": sheet,
"startRowIndex": 1,
"startColumnIndex": 4,
"endColumnIndex": 5
},
"rule": {
"condition": {
"type": "ONE_OF_LIST",
"values": [
{"userEnteredValue": "Y"},
{"userEnteredValue": "N"}
]
}
}
}
},
{ # Enter Data
"pasteData": {
"data": concat([date, time_1, time_2, dur, 'N']),
"type": "PASTE_NORMAL",
"delimiter": ",",
"coordinate": {
"sheetId": sheet, # 1st sheet
"rowIndex": 1 # 2nd row
}
}
}
]
}
request = service.spreadsheets().\
batchUpdate(spreadsheetId=spreadsheetId,
body=batch_update_spreadsheet_request_body)
request.execute()
def concat(lst):
if len(lst) == 0:
return ''
elif len(lst) == 1:
return str(lst[0])
else:
return str(lst[0]) + ', ' + concat(lst[1:])
# def updateWork()
def main():
while(True):
command = ''
command = input("What do you want to do? ").lower()
if command == 'help':
print("Here are the list of commands you can use: \
\n - Total Earnings \n - Earnings \n - Unpaid Hours \
\n - New Entry \n - Quit")
if command == 'total earnings':
getTotalEarnings()
if command == 'unpaid hours':
while(True):
unpaidCmd = input("Which Student? (Minju or Minsuk) ")
unpaid = calcUnpaidHrs(unpaidCmd)
if unpaid is None:
continue
else:
print(unpaid)
break
if command == 'new entry':
updateLesson()
if command == 'quit':
print()
sys.exit(0)
if command == 'earnings':
while(True):
earnCmd = input("Which Student? (Minju or Minsuk) ")
earn = getEarnings(earnCmd)
if earn is None:
continue
else:
print(earn)
break
main()