Open Elanchezhian2712 opened 2 months ago
try:
finalre[key] = [finalre[key].pop()]+int(entry[key].pop())
except:
finalre[key] = entry[key]
def calculate_work_hours(userid: int, specific_date: str, db: Session):
print(userid, specific_date, 'Calculating work hours...')
timezone = pytz.timezone('Asia/Kolkata')
date_object = datetime.strptime(specific_date, '%Y-%m-%d')
start_of_day = timezone.localize(date_object.replace(hour=0, minute=0, second=0, microsecond=0))
end_of_day = timezone.localize(date_object.replace(hour=23, minute=59, second=59, microsecond=999999))
login_logout_data = db.query(models.login_time).filter(
and_(
models.login_time.userid == userid,
models.login_time.login_time >= start_of_day.strftime('%Y-%m-%d %H:%M:%S'),
models.login_time.login_time <= end_of_day.strftime('%Y-%m-%d %H:%M:%S')
)
).all()
total_minutes_worked = 0
current_time = datetime.now(timezone)
print(f"Current Time: {current_time.strftime('%H:%M:%S')}")
for record in login_logout_data:
print(f"Processing Record: {record}")
login_dt = timezone.localize(datetime.strptime(record.login_time, '%Y-%m-%d %H:%M:%S'))
if record.logout_time:
logout_dt = timezone.localize(datetime.strptime(record.logout_time, '%Y-%m-%d %H:%M:%S'))
else:
logout_dt = current_time
if logout_dt < login_dt:
print(f"Warning: Logout time {logout_dt} is before login time {login_dt}. Skipping record.")
continue
minutes_worked = (logout_dt - login_dt).total_seconds() / 60
total_minutes_worked += minutes_worked
print(f"User ID: {userid}, Login Time: {login_dt.strftime('%H:%M:%S')}, Logout Time: {logout_dt.strftime('%H:%M:%S')}, "
f"Difference: {minutes_worked:.2f} minutes")
total_hours = int(total_minutes_worked // 60)
remaining_minutes = int(total_minutes_worked % 60)
print(f"Total Hours Worked: {total_hours}, Remaining Minutes: {remaining_minutes}")
return f"{total_hours} hours and {remaining_minutes} minutes"
# =======================================logout time auto update===================================
def time_check_logout(db: Session):
ist = pytz.timezone('Asia/Kolkata')
while True:
try:
current_time = datetime.now(ist)
current_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')
print(f"Checking time: {current_time_str} IST")
if current_time.hour == 14 and current_time.minute == 15:
print("Triggering logout status update...")
records_to_update = db.query(models.login_time).filter(
or_(models.login_time.logout_time == '', models.login_time.logout_time.is_(None))
).all()
print(f"Records before update: {records_to_update}")
if records_to_update:
updated_count = db.query(models.login_time).filter(
or_(models.login_time.logout_time == '', models.login_time.logout_time.is_(None))
).update({models.login_time.logout_time: current_time_str}, synchronize_session=False)
db.commit()
print(f"Number of records updated: {updated_count}")
records_updated = db.query(models.login_time).filter(
models.login_time.logout_time == current_time_str
).all()
print(f"Records after update: {records_updated}")
else:
print("No records found to update.")
time.sleep(60)
else:
print("Not the scheduled time, checking again in 30 seconds...")
time.sleep(30)
except Exception as e:
print(f"An error occurred: {str(e)}")
time.sleep(30)
#-------------------------------Change the Wrok statuses to Break, Call, Metting and Work in Progress--------------------------------------------
def check_and_update_work_status(db: Session):
# Get the current time in IST
ist = pytz.timezone('Asia/Kolkata')
current_datetime = datetime.now(ist)
# print(f"Current time: {current_datetime.strftime('%Y-%m-%d %H:%M:%S')} IST")
# # Proceed to update work statuses
# print("Updating work statuses...")
# Query all relevant records
all_records = db.query(models.TL).filter(models.TL.work_status.in_(["Break", "Clarification Call", "Meeting","Work in Progress"])).all()
print(f"Found {len(all_records)} records to process.")
for db_res in all_records:
# Get the current time for the record update
current_time_str = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
# Debugging output
# print(f"Current record Service_ID: {db_res.Service_ID}, Work Status: {db_res.work_status}")
# Update work status and corresponding records
if db_res.work_status == "Break":
# print(f"Updating Service_ID: {db_res.Service_ID} from Break to Hold")
db_res.work_status = "Hold"
# Update corresponding break record
break_record = db.query(models.BREAK).filter(models.BREAK.Service_ID == db_res.Service_ID).first()
if break_record:
break_record.break_time_end = current_time_str # Update end time
db.add(break_record)
# print(f"Updated break record for Service_ID: {db_res.Service_ID}")
elif db_res.work_status == "Clarification Call":
print(f"Updating Service_ID: {db_res.Service_ID} from Clarification Call to Hold")
db_res.work_status = "Hold"
call_record = db.query(models.CALL).filter(models.CALL.Service_ID == db_res.Service_ID).first()
if call_record:
call_record.call_time_end = current_time_str # Update end time
db.add(call_record)
# print(f"Updated call record for Service_ID: {db_res.Service_ID}")
elif db_res.work_status == "Meeting":
# print(f"Updating Service_ID: {db_res.Service_ID} from Meeting to Hold")
db_res.work_status = "Hold"
meeting_record = db.query(models.MEETING).filter(models.MEETING.Service_ID == db_res.Service_ID).first()
if meeting_record:
meeting_record.meeting_time_end = current_time_str # Update end time
db.add(meeting_record)
# print(f"Updated meeting record for Service_ID: {db_res.Service_ID}")
elif db_res.work_status == "Work in Progress":
# print(f"Updating Service_ID: {db_res.Service_ID} from Work in Progress to Hold")
db_res.work_status = "Hold"
#meeting_record = db.query(models.MEETING).filter(models.MEETING.Service_ID == db_res.Service_ID).first()
# Insert a new HOLD record
db_insert = models.HOLD(
Service_ID=db_res.Service_ID,
user_id=db_res.Assigned_To,
hold_time_start=current_time_str,
hold_time_end='', # Set to empty string initially
remarks="Auto Remark"
)
db.add(db_insert)
print(f"Inserted HOLD record for Service_ID: {db_res.Service_ID}")
# Commit all changes to the database
try:
db.commit()
print("Work statuses updated successfully.")
except Exception as e:
print(f"Error committing changes: {e}")
def time_check_loop(db: Session):
ist = pytz.timezone('Asia/Kolkata')
while True:
current_time = datetime.now(ist)
print(f"Checking time: {current_time.strftime('%Y-%m-%d %H:%M:%S')} IST")
if (current_time.hour == 9 and current_time.minute == 0) or (current_time.hour == 21 and current_time.minute == 0):
print("Triggering work status update...")
check_and_update_work_status(db)
time.sleep(60)
else:
print("Not the scheduled time, checking again in 30 seconds...")
time.sleep(30)
@app.on_event("startup")
async def startup_event():
def thread_target():
db = SessionLocal()
try:
crud.time_check_loop(db)
finally:
db.close()
thread = threading.Thread(target=thread_target)
thread.daemon = True
thread.start()
# -------------------------------------logout automatic------------------------------
@app.on_event("startup")
async def startup_event():
db = SessionLocal()
try:
def thread_target_logout():
db = SessionLocal() # Create a new session for the thread
try:
# Start the time check logout in a separate thread
crud.time_check_logout(db)
except Exception as e:
logging.error(f"Error in time_check_logout: {e}")
finally:
db.close()
# Start the time check logout in a separate thread
logout_thread = threading.Thread(target=thread_target_logout)
logout_thread.daemon = True # Daemonize thread to ensure it exits when the main program does
logout_thread.start()
except Exception as e:
logging.error(f"Error during startup: {e}")
finally:
db.close()
#-------------------------------Change the Wrok statuses to Break, Call, Metting and Work in Progress--------------------------------------------
def check_and_update_work_status(db: Session):
# Get the current time in IST
ist = pytz.timezone('Asia/Kolkata')
current_datetime = datetime.now(ist)
# print(f"Current time: {current_datetime.strftime('%Y-%m-%d %H:%M:%S')} IST")
# # Proceed to update work statuses
# print("Updating work statuses...")
# Query all relevant records
all_records = db.query(models.TL).filter(models.TL.work_status.in_(["Break", "Clarification Call", "Meeting","Work in Progress"])).all()
print(f"Found {len(all_records)} records to process.")
for db_res in all_records:
# Get the current time for the record update
current_time_str = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
# Debugging output
# print(f"Current record Service_ID: {db_res.Service_ID}, Work Status: {db_res.work_status}")
# Update work status and corresponding records
if db_res.work_status == "Break":
# print(f"Updating Service_ID: {db_res.Service_ID} from Break to Hold")
db_res.work_status = "Hold"
# Update corresponding break record
break_record = db.query(models.BREAK).filter(models.BREAK.Service_ID == db_res.Service_ID).first()
if break_record:
break_record.break_time_end = current_time_str # Update end time
db.add(break_record)
# print(f"Updated break record for Service_ID: {db_res.Service_ID}")
elif db_res.work_status == "Clarification Call":
print(f"Updating Service_ID: {db_res.Service_ID} from Clarification Call to Hold")
db_res.work_status = "Hold"
call_record = db.query(models.CALL).filter(models.CALL.Service_ID == db_res.Service_ID).first()
if call_record:
call_record.call_time_end = current_time_str # Update end time
db.add(call_record)
# print(f"Updated call record for Service_ID: {db_res.Service_ID}")
elif db_res.work_status == "Meeting":
# print(f"Updating Service_ID: {db_res.Service_ID} from Meeting to Hold")
db_res.work_status = "Hold"
meeting_record = db.query(models.MEETING).filter(models.MEETING.Service_ID == db_res.Service_ID).first()
if meeting_record:
meeting_record.meeting_time_end = current_time_str # Update end time
db.add(meeting_record)
# print(f"Updated meeting record for Service_ID: {db_res.Service_ID}")
elif db_res.work_status == "Work in Progress":
# print(f"Updating Service_ID: {db_res.Service_ID} from Work in Progress to Hold")
db_res.work_status = "Hold"
#meeting_record = db.query(models.MEETING).filter(models.MEETING.Service_ID == db_res.Service_ID).first()
# Insert a new HOLD record
db_insert = models.HOLD(
Service_ID=db_res.Service_ID,
user_id=db_res.Assigned_To,
hold_time_start=current_time_str,
hold_time_end='', # Set to empty string initially
remarks="Auto Remark"
)
db.add(db_insert)
print(f"Inserted HOLD record for Service_ID: {db_res.Service_ID}")
# Commit all changes to the database
try:
db.commit()
print("Work statuses updated successfully.")
except Exception as e:
print(f"Error committing changes: {e}")
def time_check_loop(db: Session):
ist = pytz.timezone('Asia/Kolkata')
while True:
current_time = datetime.now(ist)
print(f"Checking time: {current_time.strftime('%Y-%m-%d %H:%M:%S')} IST")
if (current_time.hour == 9 and current_time.minute == 0) or (current_time.hour == 21 and current_time.minute == 0):
print("Triggering work status update...")
check_and_update_work_status(db)
time.sleep(60)
else:
print("Not the scheduled time, checking again in 30 seconds...")
time.sleep(30)
# ------------------------------calculate_work_hours with specified user id-------------------------
def calculate_work_hours(userid: int, specific_date: str, db: Session):
print(userid, specific_date, 'Calculating work hours...')
timezone = pytz.timezone('Asia/Kolkata')
date_object = datetime.strptime(specific_date, '%Y-%m-%d')
start_of_day = timezone.localize(date_object.replace(hour=0, minute=0, second=0, microsecond=0))
end_of_day = timezone.localize(date_object.replace(hour=23, minute=59, second=59, microsecond=999999))
login_logout_data = db.query(models.login_time).filter(
and_(
models.login_time.userid == userid,
models.login_time.login_time >= start_of_day.strftime('%Y-%m-%d %H:%M:%S'),
models.login_time.login_time <= end_of_day.strftime('%Y-%m-%d %H:%M:%S')
)
).all()
total_minutes_worked = 0
current_time = datetime.now(timezone)
print(f"Current Time: {current_time.strftime('%H:%M:%S')}")
for record in login_logout_data:
print(f"Processing Record: {record}")
login_dt = timezone.localize(datetime.strptime(record.login_time, '%Y-%m-%d %H:%M:%S'))
if record.logout_time:
logout_dt = timezone.localize(datetime.strptime(record.logout_time, '%Y-%m-%d %H:%M:%S'))
else:
logout_dt = current_time
if logout_dt < login_dt:
print(f"Warning: Logout time {logout_dt} is before login time {login_dt}. Skipping record.")
continue
minutes_worked = (logout_dt - login_dt).total_seconds() / 60
total_minutes_worked += minutes_worked
print(f"User ID: {userid}, Login Time: {login_dt.strftime('%H:%M:%S')}, Logout Time: {logout_dt.strftime('%H:%M:%S')}, "
f"Difference: {minutes_worked:.2f} minutes")
total_hours = int(total_minutes_worked // 60)
remaining_minutes = int(total_minutes_worked % 60)
print(f"Total Hours Worked: {total_hours}, Remaining Minutes: {remaining_minutes}")
return f"{total_hours} hours and {remaining_minutes} minutes"
# =======================================logout time auto update===================================
def time_check_logout(db: Session):
ist = pytz.timezone('Asia/Kolkata')
while True:
try:
current_time = datetime.now(ist)
current_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')
print(f"Checking time: {current_time_str} IST")
if current_time.hour == 14 and current_time.minute == 15:
print("Triggering logout status update...")
records_to_update = db.query(models.login_time).filter(
or_(models.login_time.logout_time == '', models.login_time.logout_time.is_(None))
).all()
print(f"Records before update: {records_to_update}")
if records_to_update:
updated_count = db.query(models.login_time).filter(
or_(models.login_time.logout_time == '', models.login_time.logout_time.is_(None))
).update({models.login_time.logout_time: current_time_str}, synchronize_session=False)
db.commit()
print(f"Number of records updated: {updated_count}")
records_updated = db.query(models.login_time).filter(
models.login_time.logout_time == current_time_str
).all()
print(f"Records after update: {records_updated}")
else:
print("No records found to update.")
time.sleep(60)
else:
print("Not the scheduled time, checking again in 30 seconds...")
time.sleep(30)
except Exception as e:
print(f"An error occurred: {str(e)}")
time.sleep(30)
# ------------------------------calculate_work_hours with specified user id-------------------------
def calculate_work_hours(userid: int, specific_date: str, db: Session):
print(userid, specific_date, 'Calculating work hours...')
timezone = pytz.timezone('Asia/Kolkata')
date_object = datetime.strptime(specific_date, '%Y-%m-%d')
start_of_day = timezone.localize(date_object.replace(hour=0, minute=0, second=0, microsecond=0))
end_of_day = timezone.localize(date_object.replace(hour=23, minute=59, second=59, microsecond=999999))
login_logout_data = db.query(models.login_time).filter(
and_(
models.login_time.userid == userid,
models.login_time.login_time >= start_of_day.strftime('%Y-%m-%d %H:%M:%S'),
models.login_time.login_time <= end_of_day.strftime('%Y-%m-%d %H:%M:%S')
)
).all()
total_minutes_worked = 0
current_time = datetime.now(timezone)
print(f"Current Time: {current_time.strftime('%H:%M:%S')}")
for record in login_logout_data:
print(f"Processing Record: {record}")
login_dt = timezone.localize(datetime.strptime(record.login_time, '%Y-%m-%d %H:%M:%S'))
if record.logout_time:
logout_dt = timezone.localize(datetime.strptime(record.logout_time, '%Y-%m-%d %H:%M:%S'))
else:
logout_dt = current_time
if logout_dt < login_dt:
print(f"Warning: Logout time {logout_dt} is before login time {login_dt}. Skipping record.")
continue
minutes_worked = (logout_dt - login_dt).total_seconds() / 60
total_minutes_worked += minutes_worked
print(f"User ID: {userid}, Login Time: {login_dt.strftime('%H:%M:%S')}, Logout Time: {logout_dt.strftime('%H:%M:%S')}, "
f"Difference: {minutes_worked:.2f} minutes")
total_hours = int(total_minutes_worked // 60)
remaining_minutes = int(total_minutes_worked % 60)
print(f"Total Hours Worked: {total_hours}, Remaining Minutes: {remaining_minutes}")
return f"{total_hours} hours and {remaining_minutes} minutes"
# =======================================logout time auto update===================================
def time_check_logout(db: Session):
ist = pytz.timezone('Asia/Kolkata')
while True:
try:
current_time = datetime.now(ist)
current_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')
print(f"Checking time: {current_time_str} IST")
if current_time.hour == 14 and current_time.minute == 15:
print("Triggering logout status update...")
records_to_update = db.query(models.login_time).filter(
or_(models.login_time.logout_time == '', models.login_time.logout_time.is_(None))
).all()
print(f"Records before update: {records_to_update}")
if records_to_update:
updated_count = db.query(models.login_time).filter(
or_(models.login_time.logout_time == '', models.login_time.logout_time.is_(None))
).update({models.login_time.logout_time: current_time_str}, synchronize_session=False)
db.commit()
print(f"Number of records updated: {updated_count}")
records_updated = db.query(models.login_time).filter(
models.login_time.logout_time == current_time_str
).all()
print(f"Records after update: {records_updated}")
else:
print("No records found to update.")
time.sleep(60)
else:
print("Not the scheduled time, checking again in 30 seconds...")
time.sleep(30)
except Exception as e:
print(f"An error occurred: {str(e)}")
time.sleep(30)
idealname = ''
idealname = row.Assigned_To
print(idealname,type(date),'valuesssssssssssssssssssssssssssss') if idealname !='': from src import crud print(crud.calculate_work_hours(idealname, date, db),"1!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") data["idealname"] = crud.calculate_work_hours(idealname, date, db)