Skip to content

Commit

Permalink
fix: working hours
Browse files Browse the repository at this point in the history
  • Loading branch information
okradze committed Jan 9, 2024
1 parent a4223f9 commit e9ef92b
Showing 1 changed file with 46 additions and 14 deletions.
60 changes: 46 additions & 14 deletions apps/worker/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import time
from datetime import timedelta
from datetime import date, datetime, timedelta

import pytz
import requests
from celery import Celery

Expand Down Expand Up @@ -141,6 +142,48 @@ def register_campaign_phone_call_tasks():
bind=True,
)
def make_phone_call(self, campaign_id: str, contact_id: str, account_id: str):
campaign_res = requests.get(
f"{Config.PR_DEV_SERVER_URL}/v1/campaign/{campaign_id}",
headers={
"Authorization": Config.SERVER_AUTH_TOKEN,
"Account-ID": account_id,
},
)

campaign = campaign_res.json()
retry_interval = campaign.get("retry_interval", 15)

working_hours_start = datetime.strptime(
campaign.get("working_hours_start"), "%H:%M"
)
working_hours_end = datetime.strptime(campaign.get("working_hours_end"), "%H:%M")

# Get current time in US timezone
# us_tz = pytz.timezone("US/Eastern") # replace with the appropriate US timezone

current_time_us = datetime.now().time()

# Check if current day is between Monday and Friday
current_day_us = datetime.now().weekday()

if current_day_us >= 0 and current_day_us <= 4: # 0 is Monday, 4 is Friday
# Check if current time is within working hours
if not working_hours_start <= current_time_us <= working_hours_end:
# Retry the task when the working hours start
current_datetime_us = datetime.combine(date.today(), current_time_us)
working_hours_start_datetime = datetime.combine(
date.today(), working_hours_start
)
countdown = (working_hours_start_datetime - current_datetime_us).seconds
self.retry(countdown=countdown)
return "Retrying in working hours"
else:
# Retry the task on next Monday
seconds_until_next_monday = (7 - current_day_us) * 24 * 60 * 60
self.retry(countdown=seconds_until_next_monday)
return "Retrying on next Monday"

# Start phone call
res = requests.post(
f"{Config.PR_DEV_SERVER_URL}/call/campaign",
headers={
Expand All @@ -161,22 +204,11 @@ def make_phone_call(self, campaign_id: str, contact_id: str, account_id: str):

chat_id = call_json.get("chat_id")

start_time = time.time()

campaign_res = requests.get(
f"{Config.PR_DEV_SERVER_URL}/v1/campaign/{campaign_id}",
headers={
"Authorization": Config.SERVER_AUTH_TOKEN,
"Account-ID": account_id,
},
)

campaign = campaign_res.json()
retry_interval = campaign.get("retry_interval", 15)

# Checks for the status of the phone call to make sure phone call is finished
FORTY_FIVE_MINUTES_IN_SECONDS = 2700

start_time = time.time()

while True:
# Just in case loop stuck for some reason
if time.time() - start_time > FORTY_FIVE_MINUTES_IN_SECONDS:
Expand Down

0 comments on commit e9ef92b

Please sign in to comment.