diff --git a/src/khoj/database/adapters/__init__.py b/src/khoj/database/adapters/__init__.py index 6928f51c..5e3bfb88 100644 --- a/src/khoj/database/adapters/__init__.py +++ b/src/khoj/database/adapters/__init__.py @@ -937,14 +937,6 @@ class AutomationAdapters: if not automation.id.startswith(f"automation_{user.uuid}_"): raise ValueError("Invalid automation id") - django_job = DjangoJob.objects.filter(id=automation.id).first() - execution = DjangoJobExecution.objects.filter(job=django_job) - - last_run_time = None - - if execution.exists(): - last_run_time = execution.latest("run_time").run_time - automation_metadata = json.loads(automation.name) crontime = automation_metadata["crontime"] timezone = automation.next_run_time.strftime("%Z") @@ -957,9 +949,25 @@ class AutomationAdapters: "schedule": schedule, "crontime": crontime, "next": automation.next_run_time.strftime("%Y-%m-%d %I:%M %p %Z"), - "last_run": last_run_time.strftime("%Y-%m-%d %I:%M %p %Z") if last_run_time else None, } + @staticmethod + def get_job_last_run(user: KhojUser, automation: Job): + # Perform validation checks + # Check if user is allowed to delete this automation id + if not automation.id.startswith(f"automation_{user.uuid}_"): + raise ValueError("Invalid automation id") + + django_job = DjangoJob.objects.filter(id=automation.id).first() + execution = DjangoJobExecution.objects.filter(job=django_job, status="Executed") + + last_run_time = None + + if execution.exists(): + last_run_time = execution.latest("run_time").run_time + + return last_run_time.strftime("%Y-%m-%d %I:%M %p %Z") if last_run_time else None + @staticmethod def get_automations_metadata(user: KhojUser): for automation in AutomationAdapters.get_automations(user): diff --git a/src/khoj/routers/helpers.py b/src/khoj/routers/helpers.py index c56f1f34..99e702f9 100644 --- a/src/khoj/routers/helpers.py +++ b/src/khoj/routers/helpers.py @@ -891,9 +891,7 @@ def scheduled_chat( if job_id: # Get the job object and check whether the time is valid for it to run. This helps avoid race conditions that cause the same job to be run multiple times. job = AutomationAdapters.get_automation(user, job_id) - metadata = AutomationAdapters.get_automation_metadata(user, job) - - last_run_time = metadata.get("last_run", None) + last_run_time = AutomationAdapters.get_job_last_run(user, job) # Convert last_run_time from %Y-%m-%d %I:%M %p %Z to datetime object if last_run_time: