-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
413 lines (373 loc) · 14.3 KB
/
util.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
"""
Bunch of utils used for the work log Database program
"""
import os
import datetime
from collections import namedtuple
from peewee import *
db = SqliteDatabase('work_log.db')
date_fmt = '%d/%m/%Y'
class Entry(Model):
date = DateTimeField(default=datetime.date.today, unique=False)
first_name = CharField(max_length=255)
last_name = CharField(max_length=255)
task_name = CharField(max_length=255)
time_spent = IntegerField(default=0)
notes = TextField()
class Meta:
database = db
def __repr__(self):
return 'Entry({self.date}, ' \
'{self.first_name}, ' \
'{self.last_name}, ' \
'{self.task_name},' \
' {self.time_spent}, ' \
'{self.notes})'.format(self=self)
def __str__(self):
return "Employee: {name}\n" \
"Task: {task}\n" \
"Date: {date}\n" \
"Time Spent: {time_spent}\n" \
"Notes: {notes}"\
.format(name=' '.join([str(self.first_name).title(),
str(self.last_name).title()]),
task=self.task_name,
date=datetime.date.strftime(self.date, date_fmt),
time_spent=self.time_spent,
notes=self.notes)
def delete_task(self):
"""Delete an entry."""
if input("Are you sure? [yN] ").lower() == 'y':
self.delete_instance()
input("Entry deleted!\nPlease press Enter to continue")
return True
return False
def edit_task(self):
"""edit an entry"""
if input("Are you sure? [yN] ").lower() == 'y':
# clear the screen
os.system("cls" if os.name == "nt" else "clear")
print("Please edit the following task:\n{}".format(self))
edited = set_entry_core_values(for_edit=True)
self.date = edited.task_date
self.task_name = edited.task_name
self.time_spent = edited.time_spent
self.notes = edited.task_notes
self.save()
input("Entry successfully edited!\nPlease press Enter to continue")
return True
return False
def set_entry_core_values(for_edit=False):
"""
Sets all the task parameters except for the name of the employee.
These settings are common for adding a new task or editing an existing one.
:param for_edit: a flag that indicates if the function is called for editing
:return: a CoreValues nametuple object holding the set core values of a task.
"""
CoreValues = namedtuple('CoreValues', [
'task_name',
'task_date',
'time_spent',
'task_notes',
])
# set task name
while True:
task_name = input("Task name: ").strip()
if not task_name:
print("Please enter a meaningful task name!")
continue
else:
break
# set task date
if for_edit:
while True:
# set task date
date_input = input("Task date (please use DD/MM/YYYY format): ")
try:
task_date = datetime.datetime.strptime(date_input,
date_fmt).date()
except ValueError:
input("Invalid date!!!, press Enter to try again...")
continue
else:
break
else:
task_date = datetime.date.today()
# set time_spent
while True:
try:
time_spent = int(input("Time spent (rounded minutes): "))
except ValueError:
input("Invalid value!!!, press Enter to try again...")
continue
else:
break
# set task notes
task_notes = input("Notes (Optional, you can leave this empty): ").strip()
return CoreValues(task_name, task_date, time_spent, task_notes)
def add_entry():
"""Add a new entry"""
# set employee name
while True:
name = input("Please enter your full name (first and last): ")
try:
first_name, last_name = name.split(None, 1)
except ValueError:
input("Not a valid full name!!!, press Enter to try again...")
continue
else:
break
entry_core = set_entry_core_values()
try:
Entry.create(first_name=str(first_name).lower(),
last_name=str(last_name).lower(),
task_name=entry_core.task_name,
date=entry_core.task_date,
time_spent=entry_core.time_spent,
notes=entry_core.task_notes,
)
except Exception as e:
print("Error occurred while adding entry to {}\n{}"
.format(db.database, e))
return False
else:
return True
def display_entries(entries):
"""
Display the selected entries resulted by a user search criteria.
:param entries: list of Task instances
:return: True
"""
i = 0
while True:
# clear the screen
os.system("cls" if os.name == "nt" else "clear")
commands = "[R]eturn to search menu"
if not len(entries):
print("no entries have been found.".upper())
else:
print(entries[i])
print("\nResult {} of {}\n".format(i + 1, len(entries)))
commands = "[E]dit, [D]elete, " + commands
if i < len(entries) - 1:
# Add Next command
commands = "[N]ext, " + commands
if i > 0:
# Add Back command
commands = "[B]ack, " + commands
elif i > 0:
# Add Back command
commands = "[B]ack, " + commands
print(commands)
option = input()
if option.lower() in ['n', 'next'] and i < len(entries) - 1:
i += 1
elif option.lower() in ['b', 'back'] and i > 0:
i -= 1
elif option.lower() in ['e', 'edit'] and len(entries):
# call edit method
if entries[i].edit_task():
return True # back to search menu
else:
continue
elif option.lower() in ['d', 'Delete'] and len(entries):
# call delete method
if entries[i].delete_task():
return True # back to search menu
else:
continue
elif option.lower() in ['r', 'return']:
return True # back to search menu
def look_for_partners(name):
"""
Looks for existing entries holding the name input.
Used in search by employee name when the user doesn't enter a full name.
:param name: string representing a first\last name
:return: entries: entries having the given name or
None: if there is no match
"""
potential_entries = Entry \
.select(Entry.first_name, Entry.last_name) \
.where((Entry.first_name == name) |
(Entry.last_name == name)) \
.distinct() \
.order_by(Entry.first_name, Entry.last_name)
if potential_entries:
while True:
# clear the screen
os.system("cls" if os.name == "nt" else "clear")
print("From below employees list\n"
"Please select the employee index: ")
counter = 1
for entry in potential_entries:
print('{counter}.\t{name}'
.format(counter=counter,
name=' '.join([
str(entry.first_name).title(),
str(entry.last_name).title(),
])))
counter += 1
user_input = input()
try:
index = int(user_input)
if 1 <= index < counter:
# locate records with selected index date
first_name = potential_entries[index-1].first_name
last_name = potential_entries[index-1].last_name
entries = Entry.select()\
.where(
(Entry.first_name == first_name) &
(Entry.last_name == last_name))\
.order_by(Entry.date)
else:
raise ValueError
except ValueError:
input("Invalid selection, please press Enter to try again...")
continue
else:
return entries
else:
return None
def find_employee():
"""Find by employee name"""
while True:
# clear the screen
os.system("cls" if os.name == "nt" else "clear")
print("Please, enter the employee name:")
name = input().strip().lower()
if name:
first_name, sep, last_name = name.partition(' ')
if last_name:
# we've got a full name and should search for exact match
last_name = last_name.strip()
entries = Entry.select().where(
(Entry.first_name == first_name) &
(Entry.last_name == last_name)
).order_by(Entry.date)
else:
# name is not full, we'd search for multiple options
entries = look_for_partners(name)
selected_entries = []
if entries is not None:
for entry in entries:
selected_entries.append(entry)
display_entries(selected_entries)
return len(selected_entries) # go back to Search menu
else:
continue
def find_date():
"""Find by date"""
while True:
# clear the screen
os.system("cls" if os.name == "nt" else "clear")
dates_query = Entry.select(Entry.date)\
.distinct()\
.order_by(Entry.date.desc())
if not dates_query:
print("No entries to search for!, Work Log Data-Base is empty.")
else:
print("From below dates list\nPlease select a date index: ")
print("(Enter 'r' to Return to Search menu)")
counter = 1
for record in dates_query:
print('{counter}.\t{date}'
.format(counter=counter,
date=record.date.strftime(date_fmt)))
counter += 1
user_input = input()
if user_input.upper() == 'r'.upper():
return True # return to Search menu
else:
try:
index = int(user_input)
if 1 <= index < counter:
# locate records with selected index date
selected_date = dates_query[index-1].date
entries = Entry.select().where(
(Entry.date.year == selected_date.year) &
(Entry.date.month == selected_date.month) &
(Entry.date.day == selected_date.day))
else:
raise ValueError
except ValueError:
input("Invalid selection, please press Enter to try again...")
continue
else:
selected_entries = []
for entry in entries:
selected_entries.append(entry)
display_entries(selected_entries)
return len(selected_entries) # go back to Search menu
def find_dates_range():
"""Find by dates range"""
while True:
# clear the screen
os.system("cls" if os.name == "nt" else "clear")
print("Please enter dates range, use DD/MM/YYYY format.")
print("(Enter 'r' to Return to Search menu)")
from_date = input("From date: ")
if from_date.upper() == 'r'.upper():
return # go back to Search menu
to_date = input("To date: ")
if to_date.upper() == 'r'.upper():
return # go back to Search menu
try:
from_date = datetime.datetime.strptime(from_date,
date_fmt)
from_date = from_date.date()
to_date = datetime.datetime.strptime(to_date,
date_fmt)
to_date = to_date.date()
except ValueError:
input("Invalid date!!!, press Enter to try again...")
continue
else:
# locate records within the requested dates range
entries = Entry.select().where(
Entry.date.between(from_date, to_date))
selected_entries = []
for entry in entries:
selected_entries.append(entry)
display_entries(selected_entries)
return len(selected_entries) # go back to Search menu
def find_time_spent():
"""Find by time spent"""
while True:
# clear the screen
os.system("cls" if os.name == "nt" else "clear")
print("Please enter a time spent value (rounded minutes):")
print("(Enter 'r' to Return to Search menu)")
time_spent = input()
if time_spent.upper() == 'r'.upper():
return # go back to Search menu
try:
time_spent = int(time_spent)
except ValueError:
input("Invalid value!!!, press Enter to try again...")
continue
else:
selected_entries = []
# locate records with entered time spent
entries = Entry.select() \
.where(Entry.time_spent == time_spent)
for entry in entries:
selected_entries.append(entry)
display_entries(selected_entries)
return len(selected_entries) # go back to Search menu
def find_phrase():
"""Find by a phrase"""
# clear the screen
os.system("cls" if os.name == "nt" else "clear")
phrase = input("Please enter a phrase to find in the Work Log:\n").strip()
selected_entries = []
# locate records which contains the entered phrase
# in task_name or notes fields
entries = Entry.select().where(
(Entry.task_name.contains(phrase)) |
(Entry.notes.contains(phrase)))
for entry in entries:
selected_entries.append(entry)
display_entries(selected_entries)
return len(selected_entries) # go back to Search menu
def quit_menu():
"""Quit menu"""