autmation final reaftocrs and setitgns dafautls

This commit is contained in:
IGNY8 VPS (Salman)
2026-01-18 15:03:01 +00:00
parent 879ef6ff06
commit ebc4088ccb
14 changed files with 1367 additions and 90 deletions

View File

@@ -16,48 +16,38 @@ logger = get_task_logger(__name__)
@shared_task(name='automation.check_scheduled_automations')
def check_scheduled_automations():
"""
Check for scheduled automation runs (runs every 15 minutes)
Matches automations scheduled within the current 15-minute window.
Check for scheduled automation runs (runs every hour at :05)
SIMPLIFIED LOGIC:
- User selects hour only (0-23), stored as HH:00
- Celery runs at :05 of every hour
- Match: scheduled_hour == current_hour
"""
logger.info("[AutomationTask] Checking scheduled automations")
logger.info("[AutomationTask] Checking scheduled automations (hourly at :05)")
now = timezone.now()
current_time = now.time()
current_hour = now.hour
# Calculate 15-minute window boundaries
# Window starts at current quarter hour (0, 15, 30, 45)
window_start_minute = (current_time.minute // 15) * 15
window_end_minute = window_start_minute + 14
logger.info(f"[AutomationTask] Current hour: {current_hour}:05, checking for configs scheduled at hour {current_hour}")
logger.info(f"[AutomationTask] Current time: {current_time}, checking window {current_time.hour}:{window_start_minute:02d}-{current_time.hour}:{window_end_minute:02d}")
# Find configs that should run now
# Find configs that should run now (matching hour)
for config in AutomationConfig.objects.filter(is_enabled=True):
# Check if it's time to run
should_run = False
scheduled_hour = config.scheduled_time.hour
scheduled_minute = config.scheduled_time.minute
# Check if scheduled time falls within current 15-minute window
def is_in_window():
if current_time.hour != scheduled_hour:
return False
return window_start_minute <= scheduled_minute <= window_end_minute
# Simple hour match
should_run = False
if config.frequency == 'daily':
# Run if scheduled_time falls within current 15-minute window
if is_in_window():
should_run = True
# Run every day if hour matches
should_run = (scheduled_hour == current_hour)
elif config.frequency == 'weekly':
# Run on Mondays within scheduled window
if now.weekday() == 0 and is_in_window():
should_run = True
# Run on Mondays if hour matches
should_run = (now.weekday() == 0 and scheduled_hour == current_hour)
elif config.frequency == 'monthly':
# Run on 1st of month within scheduled window
if now.day == 1 and is_in_window():
should_run = True
# Run on 1st of month if hour matches
should_run = (now.day == 1 and scheduled_hour == current_hour)
logger.debug(f"[AutomationTask] Site {config.site_id}: freq={config.frequency}, scheduled={config.scheduled_time}, should_run={should_run}")
logger.debug(f"[AutomationTask] Site {config.site_id}: freq={config.frequency}, scheduled_hour={scheduled_hour}, current_hour={current_hour}, should_run={should_run}")
if should_run:
# Check if already ran within the last 23 hours (prevents duplicate runs)
@@ -90,6 +80,61 @@ def check_scheduled_automations():
logger.error(f"[AutomationTask] Failed to start automation for site {config.site.id}: {e}")
@shared_task(name='automation.check_test_triggers')
def check_test_triggers():
"""
Check for test triggers (runs every minute, but only processes if test_mode_enabled)
This allows admins to test automation without waiting for hourly schedule.
- Set test_mode_enabled=True and test_trigger_at=datetime on AutomationConfig
- When test_trigger_at <= now, automation triggers immediately
- Bypasses: is_enabled check, 23hr block, frequency rules
- Run is marked as trigger_type='test'
- test_trigger_at is cleared after trigger
"""
# Quick check - if no configs have test mode enabled, exit immediately
if not AutomationConfig.objects.filter(test_mode_enabled=True).exists():
return # No logging to avoid spam
logger.info("[AutomationTask] Checking test triggers")
now = timezone.now()
# Find configs with test mode enabled and trigger time passed
test_configs = AutomationConfig.objects.filter(
test_mode_enabled=True,
test_trigger_at__isnull=False,
test_trigger_at__lte=now
)
for config in test_configs:
logger.info(f"[AutomationTask] Test trigger found for site {config.site_id}, trigger_at={config.test_trigger_at}")
# Check if already running (still respect this to avoid conflicts)
if AutomationRun.objects.filter(site=config.site, status__in=['running', 'paused']).exists():
logger.info(f"[AutomationTask] Skipping test trigger for site {config.site_id} - automation in progress")
continue
try:
service = AutomationService(config.account, config.site)
run_id = service.start_automation(trigger_type='test')
# Clear test_trigger_at (don't update last_run_at - test runs don't affect production schedule)
config.test_trigger_at = None
config.save(update_fields=['test_trigger_at'])
logger.info(f"[AutomationTask] Started test automation for site {config.site_id}, run_id={run_id}")
# Start async processing
run_automation_task.delay(run_id)
except Exception as e:
logger.error(f"[AutomationTask] Failed to start test automation for site {config.site_id}: {e}")
# Clear trigger to prevent infinite retry
config.test_trigger_at = None
config.save(update_fields=['test_trigger_at'])
@shared_task(name='automation.run_automation_task', bind=True, max_retries=0)
def run_automation_task(self, run_id: str):
"""