-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathManualTimeCalculations.py
More file actions
209 lines (159 loc) · 8.63 KB
/
ManualTimeCalculations.py
File metadata and controls
209 lines (159 loc) · 8.63 KB
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
import sqlite3 # https://docs.python.org/3/library/sqlite3.html
from datetime import datetime, timedelta # Create calendar dates & time objects https://docs.python.org/3/library/datetime.html
from time import sleep # Import only the sleep function to pause prpgram execution
import pytz # World Timezone Definitions https://pypi.org/project/pytz/
import csv
import GlobalConstants as GC
EMPLOYEE_NAMES = ["Erick Maldonado", "Dago Reyes Astello", "Cesar Rene Cabrera", "Adrian Cardenas", "Miguel Lopez Perez", "Edgar Maldonado",
"German Maranto", "Juan Antonio", "Victor Mata", "Eric Mata Vazquez", "David Montoya", "Omar Palomo Galvan", "Nicolas Gomez Perez",
"Felipe Otero", "Ulises Rodriguez", "Fidencio Santiz Lopez", "Nicolas Perez Santiz", "Rigoberto Savedra", "Jorge Velazquez",
"Oscar Cruz Zaleta", "Oscar Rodriguez", "Osiel Hernandez", "Elias Castaneda", "Thomas Humphrey", "Chase Soliz", "Derrick Lohner"]
EMPLOYEE_IDS = [1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025]
EMPLOYEE_ID_OFFSET = 1000
def get_date_time() -> datetime:
""" Get date and time in Marianna, FL timezone, independent of location on server running code
Returns:
Datetime:
"""
tz = pytz.timezone('America/Chicago')
zulu = pytz.timezone('UTC')
now = datetime.now(tz)
if now.dst() == timedelta(0):
now = datetime.now(zulu) - timedelta(hours=6)
#print('Standard Time')
else:
now = datetime.now(zulu) - timedelta(hours=5)
#print('Daylight Savings')
return now
def calculate_time_delta(id: int, date: datetime) -> tuple:
""" Calculate hours worked using clock in and clock out times from TimeReport.db SQLite database
Args:
id (int): Employeed ID
date (datetime): Datetime object (e.g. "2023-08-27T05:26+00:00")
Returns:
Tuple (elaspedHours, clockedIn, clockedOut):
elaspedHours = Decimals hours between check in and check out time for an employee ID on a specific date
clockedIn = True if an employee ID clocked IN using GUI, False otherwise
clockedOut = True if an employee ID clocked OUT using GUI, False otherwise
"""
clockedIn = True
clockedOut = True
conn = sqlite3.connect('TimeReport.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM CheckInTable")
data = cursor.fetchall()
result = list(filter(lambda t: t[GC.EMPLOYEE_ID_COLUMN_NUMBER] == id, data))
dateToCalulate = date.isoformat(timespec="minutes")[0:10]
finalResult = list(filter(lambda t: t[GC.TIMESTAMP_COLUMN_NUMBER].startswith(dateToCalulate), result))
#print(finalResult)
try:
checkInIsoString = finalResult[0][GC.TIMESTAMP_COLUMN_NUMBER]
datetimeCheckInObject = datetime.fromisoformat(checkInIsoString) # Convert the ISO strings to datetime objects
except IndexError:
#print(f'Employee ID #{id} never clocked in on {dateToCalulate}')
clockedIn = False
datetimeCheckInObject = None
cursor.execute("SELECT * FROM CheckOutTable")
data = cursor.fetchall()
result = list(filter(lambda t: t[GC.EMPLOYEE_ID_COLUMN_NUMBER] == id, data))
finalResult = list(filter(lambda t: t[GC.TIMESTAMP_COLUMN_NUMBER].startswith(dateToCalulate), result))
#print(finalResult)
try:
checkOutIsoString = finalResult[0][GC.TIMESTAMP_COLUMN_NUMBER]
datetimeCheckOutObject = datetime.fromisoformat(checkOutIsoString) # Convert the ISO strings to datetime objects
except IndexError:
#print(f'Employee ID #{id} never clocked out on {dateToCalulate}')
clockedOut = False
datetimeCheckOutObject = None
elaspedHours = 0
if(not clockedIn and not clockedOut):
elaspedHours = 0.0
elif(not clockedIn and clockedOut):
elaspedHours = 12.0
elif(clockedIn and not clockedOut):
elaspedHours = 12.0
elif(not clockedIn and not clockedOut):
elaspedHours = 12.0
else:
if datetimeCheckInObject and datetimeCheckOutObject:
# Perform the absolute value subtraction (timeDeltaObject is NEVER negative)
timeDeltaObject = datetimeCheckOutObject - datetimeCheckInObject
elaspedSeconds = timeDeltaObject.seconds
elaspedHours = elaspedSeconds / 3600.0
return elaspedHours, clockedIn, clockedOut
def create_dates():
dates = []
now = get_date_time()
# Check day of week script is being run (7, 0, -1) if run on Sunday nigth and (8, 1, -1 in run Monday morning))
if now.weekday() == GC.SUNDAY:
for dayDelta in range(7, 0, -1):
dates.append((get_date_time() - timedelta(days=dayDelta)).isoformat(timespec="minutes")[0:10])
elif now.weekday() == GC.MONDAY:
for dayDelta in range(8, 1, -1):
dates.append((get_date_time() - timedelta(days=dayDelta)).isoformat(timespec="minutes")[0:10])
return dates
def labor_report():
dates = create_dates()
filename = dates[0] + '_' + dates[6] + '_LaborerTimeReport.csv'
with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Employee Name', 'Employee ID', 'Total Hours', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'CheckIn Comment', 'CheckOut Comment'])
for id, name in zip(EMPLOYEE_IDS, EMPLOYEE_NAMES):
print(f'{name} has ID #{id}')
dailyHours = []
dailyCheckedIn = []
dailyCheckedOut = []
for day in dates:
dateToCalculate = datetime.fromisoformat(day)
hoursWorks, checkedIn, checkedOut = calculate_time_delta(id, dateToCalculate)
dailyHours.append(round(hoursWorks, 4))
dailyCheckedIn.append(checkedIn)
dailyCheckedOut.append(checkedOut)
totalHours = sum(dailyHours)
inComment = 'Missed: '
outComment = 'Missed: '
dayOfWeek = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat']
for i in range(7):
if dailyCheckedIn[i] == False:
inComment = inComment + dayOfWeek[i] + ' '
if dailyCheckedOut[i] == False:
outComment = outComment + dayOfWeek[i] + ' '
if totalHours == 0:
data = [name, id, round(totalHours, 2), dailyHours[0], dailyHours[1], dailyHours[2], dailyHours[3], dailyHours[4], dailyHours[5], dailyHours[6], 'Missed: All Days', 'Missed: All Days']
else:
data = [name, id, round(totalHours, 2), dailyHours[0], dailyHours[1], dailyHours[2], dailyHours[3], dailyHours[4], dailyHours[5], dailyHours[6], inComment, outComment]
writer.writerow(data)
def check_x_report(direction: int):
dates = create_dates()
conn = sqlite3.connect('TimeReport.db')
cursor = conn.cursor()
if direction == GC.CLOCK_IN:
filename = dates[0] + '_' + dates[6] + '_CheckInTimes.csv'
cursor.execute("SELECT * FROM CheckInTable")
else:
filename = dates[0] + '_' + dates[6] + '_CheckOutTimes.csv'
cursor.execute("SELECT * FROM CheckOutTable")
data = cursor.fetchall()
result = list(filter(lambda t: t[GC.TIMESTAMP_COLUMN_NUMBER] >= dates[0], data))
#print(result)
with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Employee Name', 'Employee ID', 'Timestamp'])
for entry in result:
emplopyeeName = EMPLOYEE_NAMES[entry[GC.EMPLOYEE_ID_COLUMN_NUMBER] - EMPLOYEE_ID_OFFSET]
employeeId = entry[GC.EMPLOYEE_ID_COLUMN_NUMBER]
timestamp = entry[GC.TIMESTAMP_COLUMN_NUMBER]
data = [emplopyeeName, employeeId, timestamp]
writer.writerow(data)
file.close()
def job():
labor_report()
check_x_report(GC.CLOCK_IN)
check_x_report(GC.CLOCK_OUT)
if __name__ == "__main__":
try:
job()
except KeyboardInterrupt:
# Sleep so that only a single 'Ctrl+C' is needed to exit program
sleep(3)
raise SystemExit