Repository navigation
Expand file tree
/
Copy pathscheduled_tasks.py
More file actions
2243 lines (1933 loc) · 88.4 KB
/
Copy pathscheduled_tasks.py
File metadata and controls
2243 lines (1933 loc) · 88.4 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Scheduled background tasks for the application"""
import logging
from datetime import datetime, timedelta
from flask import current_app
from app import db
from app.models import (
BudgetAlert,
Integration,
Invoice,
Project,
Quote,
RecurringInvoice,
ReportEmailSchedule,
TimeEntry,
User,
)
from app.services.integration_service import IntegrationService
from app.services.scheduled_report_service import ScheduledReportService
from app.utils.budget_forecasting import check_budget_alerts
from app.utils.email import (
send_missed_clock_in_email,
send_overdue_invoice_notification,
send_quote_expired_notification,
send_remind_to_log_email,
send_weekly_summary,
)
from app.utils.urls import external_url_context
logger = logging.getLogger(__name__)
def _parse_hhmm(value, default_hour=2, default_minute=0):
"""Parse HH:MM into (hour, minute); fall back to defaults on bad input."""
try:
text = (value or "").strip()
if not text or ":" not in text:
return default_hour, default_minute
hour_s, minute_s = text.split(":", 1)
hour, minute = int(hour_s), int(minute_s)
if 0 <= hour <= 23 and 0 <= minute <= 59:
return hour, minute
except (TypeError, ValueError):
pass
return default_hour, default_minute
def run_scheduled_backup():
"""Create a full backup archive and prune archives past retention.
Uses Settings.backup_retention_days (fallback: Config / BACKUP_RETENTION_DAYS).
Call within an app context (see register_scheduled_tasks wrappers).
"""
try:
from app.models.settings import Settings
from app.utils.backup import create_backup, prune_old_backups
app = current_app._get_current_object()
logger.info("Starting scheduled backup...")
archive_path = create_backup(app)
logger.info("Scheduled backup created: %s", archive_path)
settings = Settings.get_settings()
retention = int(getattr(settings, "backup_retention_days", None) or app.config.get("BACKUP_RETENTION_DAYS", 30))
removed = prune_old_backups(app, retention_days=retention)
logger.info("Scheduled backup prune removed %d old archive(s) (retention=%d days)", removed, retention)
return archive_path
except Exception as e:
logger.error("Scheduled backup failed: %s", e, exc_info=True)
return None
def check_overdue_invoices():
"""Check for overdue invoices and send notifications
This task should be run daily to check for invoices that are past their due date
and send notifications to users who have overdue invoice notifications enabled.
Note: Call within an app/external URL context (see register_scheduled_tasks wrappers).
"""
try:
from app.utils.timezone import now_in_app_timezone
logger.info("Checking for overdue invoices...")
# Calendar "today" in app timezone (not UTC / host local)
today = now_in_app_timezone().date()
overdue_invoices = Invoice.query.filter(
Invoice.due_date < today,
Invoice.status.in_(["sent", "issued"]),
Invoice.payment_status != "fully_paid",
).all()
logger.info(f"Found {len(overdue_invoices)} overdue invoices")
notifications_sent = 0
for invoice in overdue_invoices:
# Update invoice status to overdue if it's not already
if invoice.status != "overdue":
invoice.status = "overdue"
db.session.commit()
try:
from app.constants import WebhookEvent
from app.utils.invoice_events import emit_invoice_event
emit_invoice_event(WebhookEvent.INVOICE_OVERDUE.value, invoice)
except Exception as emit_exc:
logger.debug(
"Failed to emit invoice.overdue for %s: %s",
invoice.invoice_number,
emit_exc,
)
# Get users to notify (creator and admins)
users_to_notify = set()
# Add the invoice creator
if invoice.creator:
users_to_notify.add(invoice.creator)
# Add all admins
admins = User.query.filter_by(role="admin", is_active=True).all()
users_to_notify.update(admins)
# Send notifications
for user in users_to_notify:
if user.email and user.email_notifications and user.notification_overdue_invoices:
try:
send_overdue_invoice_notification(invoice, user)
notifications_sent += 1
logger.info(
f"Sent overdue notification for invoice {invoice.invoice_number} to {user.username}"
)
except Exception as e:
logger.error(f"Failed to send notification to {user.username}: {e}")
# Also notify the client via the portal notification channel
if invoice.client_id:
try:
from app.services.client_notification_service import ClientNotificationService
days_overdue = (today - invoice.due_date).days if invoice.due_date else 0
ClientNotificationService().notify_invoice_overdue(
invoice_id=invoice.id,
client_id=invoice.client_id,
days_overdue=max(days_overdue, 0),
)
except Exception as e:
logger.error(
f"Failed to send client portal overdue notification for invoice {invoice.invoice_number}: {e}"
)
logger.info(f"Sent {notifications_sent} overdue invoice notifications")
# --- Phase 4: multi-level reminder sends & late fees ---
try:
from app.services.invoice_reminder_service import process_due_reminders
reminders_sent = process_due_reminders(today=today)
if reminders_sent:
logger.info("Invoice reminder service sent %d reminder(s)", reminders_sent)
except Exception as reminder_exc:
logger.error("Invoice reminder service failed: %s", reminder_exc, exc_info=True)
return notifications_sent
except Exception as e:
logger.error(f"Error checking overdue invoices: {e}")
return 0
def send_weekly_summaries():
"""Send weekly time tracking summaries to users
This task should be run weekly (e.g., Sunday evening or Monday morning)
to send time tracking summaries to users who have opted in.
Note: Call within an app/external URL context (see register_scheduled_tasks wrappers).
"""
try:
logger.info("Sending weekly summaries...")
# Get users who want weekly summaries
users = User.query.filter_by(is_active=True, email_notifications=True, notification_weekly_summary=True).all()
from app.utils.timezone import now_in_app_timezone
logger.info(f"Found {len(users)} users with weekly summaries enabled")
# Calculate date range (last 7 days) in app timezone
end_date = now_in_app_timezone().date()
start_date = end_date - timedelta(days=7)
summaries_sent = 0
for user in users:
if not user.email:
continue
try:
# Get time entries for this user in the past week
entries = TimeEntry.query.filter(
TimeEntry.user_id == user.id,
TimeEntry.start_time >= datetime.combine(start_date, datetime.min.time()),
TimeEntry.start_time < datetime.combine(end_date + timedelta(days=1), datetime.min.time()),
TimeEntry.end_time.isnot(None),
).all()
if not entries:
logger.info(f"No entries for {user.username}, skipping")
continue
# Calculate hours worked
hours_worked = sum(e.duration_hours for e in entries)
# Group by project
projects_map = {}
for entry in entries:
if entry.project:
project_name = entry.project.name
if project_name not in projects_map:
projects_map[project_name] = {"name": project_name, "hours": 0}
projects_map[project_name]["hours"] += entry.duration_hours
projects_data = sorted(projects_map.values(), key=lambda x: x["hours"], reverse=True)
# Send email
send_weekly_summary(
user=user,
start_date=start_date.strftime("%Y-%m-%d"),
end_date=end_date.strftime("%Y-%m-%d"),
hours_worked=hours_worked,
projects_data=projects_data,
)
summaries_sent += 1
logger.info(f"Sent weekly summary to {user.username}")
except Exception as e:
logger.error(f"Failed to send weekly summary to {user.username}: {e}")
logger.info(f"Sent {summaries_sent} weekly summaries")
return summaries_sent
except Exception as e:
logger.error(f"Error sending weekly summaries: {e}")
return 0
def check_project_budget_alerts():
"""Check all active projects for budget alerts
This task should be run periodically (e.g., every 6 hours) to check
project budgets and create alerts when thresholds are exceeded.
Note: This function should be called within an app context.
Use check_project_budget_alerts_with_app() wrapper for scheduled tasks.
"""
try:
logger.info("Checking project budget alerts...")
# Get all active projects with budgets
projects = Project.query.filter(Project.budget_amount.isnot(None), Project.status == "active").all()
logger.info(f"Found {len(projects)} active projects with budgets")
total_alerts_created = 0
for project in projects:
try:
# Check for budget alerts
alerts_to_create = check_budget_alerts(project.id)
# Create alerts
for alert_data in alerts_to_create:
alert = BudgetAlert.create_alert(
project_id=alert_data["project_id"],
alert_type=alert_data["type"],
budget_consumed_percent=alert_data["budget_consumed_percent"],
budget_amount=alert_data["budget_amount"],
consumed_amount=alert_data["consumed_amount"],
)
total_alerts_created += 1
logger.info(f"Created {alert_data['type']} alert for project {project.name}")
try:
from app.utils.workflow_bridge import fire_budget_threshold_workflow
fire_budget_threshold_workflow(project, alert_data)
except Exception as wf_err:
logger.debug(f"Workflow budget_threshold trigger skipped: {wf_err}")
except Exception as e:
logger.error(f"Error checking budget alerts for project {project.id}: {e}")
logger.info(f"Created {total_alerts_created} budget alerts")
return total_alerts_created
except Exception as e:
logger.error(f"Error checking project budget alerts: {e}")
return 0
def check_task_deadline_approaching():
"""Notify workflow rules for tasks due tomorrow.
Note: Call within an app/external URL context (see register_scheduled_tasks wrappers).
"""
from datetime import timedelta
from app.models import Task
from app.utils.timezone import now_in_app_timezone
from app.utils.workflow_bridge import fire_deadline_approaching_workflow
try:
target_date = now_in_app_timezone().date() + timedelta(days=1)
tasks = Task.query.filter(
Task.due_date == target_date,
Task.status.notin_(["done", "cancelled"]),
).all()
for task in tasks:
for user_id in task.assignee_ids or ([task.created_by] if task.created_by else []):
fire_deadline_approaching_workflow(task, user_id)
return len(tasks)
except Exception as e:
logger.error(f"Error checking task deadlines: {e}")
return 0
def generate_recurring_invoices():
"""Generate invoices from active recurring invoice templates
This task should be run daily to check for recurring invoices that need to be generated.
Note: This function should be called within an app context.
Use generate_recurring_invoices_with_app() wrapper for scheduled tasks.
"""
try:
from app.utils.timezone import now_in_app_timezone
logger.info("Generating recurring invoices...")
# Calendar "today" in app timezone (matches Settings.timezone / TZ)
today = now_in_app_timezone().date()
recurring_invoices = RecurringInvoice.query.filter(
RecurringInvoice.is_active == True, RecurringInvoice.next_run_date <= today
).all()
logger.info(f"Found {len(recurring_invoices)} recurring invoices to process")
invoices_generated = 0
emails_sent = 0
for recurring in recurring_invoices:
try:
# Serialize per-template generation (Postgres FOR UPDATE; SQLite best-effort)
locked = RecurringInvoice.query.filter_by(id=recurring.id).with_for_update().first()
if not locked:
continue
recurring = locked
# Check if we've reached the end date
if recurring.end_date and today > recurring.end_date:
logger.info(f"Recurring invoice {recurring.id} has reached end date, deactivating")
recurring.is_active = False
db.session.commit()
continue
# Generate invoice
invoice = recurring.generate_invoice()
if invoice:
db.session.commit()
invoices_generated += 1
logger.info(f"Generated invoice {invoice.invoice_number} from recurring template {recurring.name}")
# Auto-send if enabled
if recurring.auto_send and invoice.client_email:
try:
from app.utils.email import send_invoice_email
send_invoice_email(invoice, invoice.client_email, sender_user=recurring.creator)
emails_sent += 1
logger.info(f"Auto-sent invoice {invoice.invoice_number} to {invoice.client_email}")
except Exception as e:
logger.error(f"Failed to auto-send invoice {invoice.invoice_number}: {e}")
else:
logger.warning(f"Failed to generate invoice from recurring template {recurring.id}")
except Exception as e:
logger.error(f"Error processing recurring invoice {recurring.id}: {e}")
db.session.rollback()
logger.info(f"Generated {invoices_generated} invoices, sent {emails_sent} emails")
return invoices_generated
except Exception as e:
logger.error(f"Error generating recurring invoices: {e}")
return 0
def generate_recurring_project_costs():
"""Generate project costs from active recurring cost templates."""
try:
logger.info("Generating recurring project costs...")
from app.services.recurring_project_cost_service import RecurringProjectCostService
generated = RecurringProjectCostService().generate_due_recurring_costs()
logger.info("Generated %s recurring project costs", generated)
return generated
except Exception as e:
logger.error(f"Error generating recurring project costs: {e}")
return 0
def send_monthly_unpaid_hours_reports():
"""Send monthly unpaid hours reports split by salesman
This task runs on the first day of each month and generates
unpaid hours reports for each salesman based on their client assignments.
Note: Call within an app/external URL context (see register_scheduled_tasks wrappers).
"""
try:
logger.info("Sending monthly unpaid hours reports by salesman...")
from datetime import datetime, timedelta
from app.models import SalesmanEmailMapping
from app.services.unpaid_hours_service import UnpaidHoursService
from app.utils.email import send_template_email
# Get last month's date range
now = datetime.now()
if now.month == 1:
last_month_start = datetime(now.year - 1, 12, 1)
last_month_end = datetime(now.year, 1, 1) - timedelta(seconds=1)
else:
last_month_start = datetime(now.year, now.month - 1, 1)
last_month_end = datetime(now.year, now.month, 1) - timedelta(seconds=1)
# Get unpaid hours grouped by salesman
unpaid_service = UnpaidHoursService()
salesman_reports = unpaid_service.get_unpaid_hours_by_salesman(
start_date=last_month_start,
end_date=last_month_end,
salesman_field_name="salesman",
)
sent_count = 0
for salesman_initial, report_data in salesman_reports.items():
if salesman_initial == "_UNASSIGNED_":
continue
# Get email for this salesman
email = SalesmanEmailMapping.get_email_for_initial(salesman_initial)
if not email:
logger.warning(f"No email mapping for salesman {salesman_initial}, skipping")
continue
# Format report data
formatted_data = {
"salesman_initial": salesman_initial,
"total_hours": report_data["total_hours"],
"total_entries": report_data["total_entries"],
"clients": report_data["clients"],
"projects": report_data["projects"],
"entries": [
{
"id": e.id,
"date": e.start_time.strftime("%Y-%m-%d") if e.start_time else "",
"project": e.project.name if e.project else "",
# Project.client is a string property; relationship is Project.client_obj
"client": (
(
e.project.client_obj.name
if (e.project and getattr(e.project, "client_obj", None))
else (e.project.client if e.project else "")
)
or (e.client.name if e.client else "Unknown")
),
"user": e.user.username if e.user else "",
"duration": e.duration_hours,
"notes": e.notes or "",
}
for e in report_data["entries"]
],
}
try:
from app.utils.urls import safe_external_url_for
send_template_email(
to=email,
subject=f"Monthly Unpaid Hours Report - {salesman_initial} ({last_month_start.strftime('%Y-%m-%d')} to {last_month_end.strftime('%Y-%m-%d')})",
template="email/unpaid_hours_report.html",
salesman_initial=salesman_initial,
report_data=formatted_data,
start_date=last_month_start.strftime("%Y-%m-%d"),
end_date=last_month_end.strftime("%Y-%m-%d"),
reports_url=safe_external_url_for("reports.reports"),
)
sent_count += 1
logger.info(f"Sent monthly unpaid hours report to {email} for {salesman_initial}")
except Exception as e:
logger.error(f"Error sending report to {email} ({salesman_initial}): {e}")
logger.info(f"Sent {sent_count} monthly unpaid hours reports")
return sent_count
except Exception as e:
logger.error(f"Error sending monthly unpaid hours reports: {e}")
return 0
def _add_job(scheduler, **kwargs):
"""Register a job with safe defaults (single instance, coalesce missed runs)."""
kwargs.setdefault("max_instances", 1)
kwargs.setdefault("coalesce", True)
func = kwargs.get("func")
job_id = kwargs.get("id") or getattr(func, "__name__", None) or "unknown"
if callable(func):
from app.utils.hardening_metrics import wrap_scheduler_job
kwargs["func"] = wrap_scheduler_job(func, str(job_id))
return scheduler.add_job(**kwargs)
def register_scheduled_tasks(scheduler, app=None):
"""Register all scheduled tasks with APScheduler
Args:
scheduler: APScheduler instance
app: Flask app instance (optional, will use current_app if not provided)
"""
try:
# Check overdue invoices daily at 9 AM
def check_overdue_invoices_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for overdue invoices check")
return
with external_url_context(app_instance):
return check_overdue_invoices()
_add_job(
scheduler,
func=check_overdue_invoices_with_app,
trigger="cron",
hour=9,
minute=0,
id="check_overdue_invoices",
name="Check for overdue invoices",
replace_existing=True,
)
logger.info("Registered overdue invoices check task")
# Send weekly summaries every Monday at 8 AM
def send_weekly_summaries_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for weekly summaries")
return
with external_url_context(app_instance):
return send_weekly_summaries()
_add_job(
scheduler,
func=send_weekly_summaries_with_app,
trigger="cron",
day_of_week="mon",
hour=8,
minute=0,
id="send_weekly_summaries",
name="Send weekly time summaries",
replace_existing=True,
)
logger.info("Registered weekly summaries task")
# Check budget alerts every 6 hours
def check_project_budget_alerts_with_app():
"""Wrapper that uses the captured app instance"""
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for budget alerts check")
return
with external_url_context(app_instance):
return check_project_budget_alerts()
_add_job(
scheduler,
func=check_project_budget_alerts_with_app,
trigger="cron",
hour="*/6",
minute=0,
id="check_budget_alerts",
name="Check project budget alerts",
replace_existing=True,
)
logger.info("Registered budget alerts check task")
def check_task_deadline_approaching_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for task deadline check")
return
with external_url_context(app_instance):
return check_task_deadline_approaching()
_add_job(
scheduler,
func=check_task_deadline_approaching_with_app,
trigger="cron",
hour=8,
minute=30,
id="check_task_deadlines",
name="Check approaching task deadlines",
replace_existing=True,
)
logger.info("Registered task deadline workflow check")
# Generate recurring invoices daily at 8 AM
# Create a closure that captures the app instance
def generate_recurring_invoices_with_app():
"""Wrapper that uses the captured app instance"""
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for recurring invoices generation")
return
with external_url_context(app_instance):
generate_recurring_invoices()
_add_job(
scheduler,
func=generate_recurring_invoices_with_app,
trigger="cron",
hour=8,
minute=0,
id="generate_recurring_invoices",
name="Generate recurring invoices",
replace_existing=True,
)
logger.info("Registered recurring invoices generation task")
def generate_recurring_project_costs_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for recurring project costs generation")
return
with external_url_context(app_instance):
generate_recurring_project_costs()
_add_job(
scheduler,
func=generate_recurring_project_costs_with_app,
trigger="cron",
hour=8,
minute=15,
id="generate_recurring_project_costs",
name="Generate recurring project costs",
replace_existing=True,
)
logger.info("Registered recurring project costs generation task")
# Send monthly unpaid hours reports by salesman (first day of month at 9 AM)
def send_monthly_unpaid_hours_reports_with_app():
"""Wrapper that uses the captured app instance"""
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for monthly unpaid hours reports")
return
with external_url_context(app_instance):
send_monthly_unpaid_hours_reports()
_add_job(
scheduler,
func=send_monthly_unpaid_hours_reports_with_app,
trigger="cron",
day=1,
hour=9,
minute=0,
id="send_monthly_unpaid_hours_reports",
name="Send monthly unpaid hours reports by salesman",
replace_existing=True,
)
logger.info("Registered monthly unpaid hours reports task")
# Retry failed webhook deliveries every 5 minutes
# Create a closure that captures the app instance
if app is None:
try:
app = current_app._get_current_object()
except RuntimeError:
logger.warning("Could not get app instance for webhook retry task")
app = None
def retry_failed_webhooks_with_app():
"""Wrapper that uses the captured app instance"""
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for webhook retry")
return
with external_url_context(app_instance):
retry_failed_webhooks()
_add_job(
scheduler,
func=retry_failed_webhooks_with_app,
trigger="cron",
minute="*/5",
id="retry_failed_webhooks",
name="Retry failed webhook deliveries",
replace_existing=True,
)
logger.info("Registered webhook retry task")
def poll_peppol_inbox_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for Peppol inbox poll")
return
with external_url_context(app_instance):
poll_peppol_inbox()
_add_job(
scheduler,
func=poll_peppol_inbox_with_app,
trigger="cron",
minute="*/10",
id="poll_peppol_inbox",
name="Poll Peppol bridge inbox",
replace_existing=True,
)
logger.info("Registered Peppol inbox poll task")
def poll_sdi_status_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for SDI status poll")
return
with external_url_context(app_instance):
poll_sdi_status()
_add_job(
scheduler,
func=poll_sdi_status_with_app,
trigger="cron",
minute="*/15",
id="poll_sdi_status",
name="Poll SDI transmission statuses",
replace_existing=True,
)
logger.info("Registered SDI status poll task")
# Check for expiring quotes daily at 9:30 AM
# Create a closure that captures the app instance
def check_expiring_quotes_with_app():
"""Wrapper that uses the captured app instance"""
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for expiring quotes check")
return
with external_url_context(app_instance):
check_expiring_quotes()
_add_job(
scheduler,
func=check_expiring_quotes_with_app,
trigger="cron",
hour=9,
minute=30,
id="check_expiring_quotes",
name="Check for expiring quotes",
replace_existing=True,
)
logger.info("Registered expiring quotes check task")
# Sync integrations every hour
def sync_integrations_with_app():
"""Wrapper that uses the captured app instance"""
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for integration sync")
return
with external_url_context(app_instance):
sync_integrations()
_add_job(
scheduler,
func=sync_integrations_with_app,
trigger="cron",
minute=0, # Every hour at minute 0
id="sync_integrations",
name="Sync all active integrations",
replace_existing=True,
)
logger.info("Registered integration sync task")
# Process scheduled reports every hour
# Create a closure that captures the app instance
def process_scheduled_reports_with_app():
"""Wrapper that uses the captured app instance"""
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for scheduled reports processing")
return
with external_url_context(app_instance):
process_scheduled_reports()
_add_job(
scheduler,
func=process_scheduled_reports_with_app,
trigger="cron",
minute=0,
id="process_scheduled_reports",
name="Process scheduled reports",
replace_existing=True,
)
logger.info("Registered scheduled reports task")
# Remind to log time (end-of-day reminder) – every hour, check users whose local time matches their reminder time
def process_remind_to_log_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for remind-to-log processing")
return
with external_url_context(app_instance):
process_remind_to_log()
_add_job(
scheduler,
func=process_remind_to_log_with_app,
trigger="cron",
minute=0,
id="process_remind_to_log",
name="Process remind-to-log notifications",
replace_existing=True,
)
logger.info("Registered remind-to-log task")
def process_missed_clock_in_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for missed clock-in processing")
return
with external_url_context(app_instance):
process_missed_clock_in()
_add_job(
scheduler,
func=process_missed_clock_in_with_app,
trigger="cron",
minute=0,
id="process_missed_clock_in",
name="Process missed clock-in email reminders",
replace_existing=True,
)
logger.info("Registered missed clock-in email task")
# Smart reminder browser push notifications – every 15 minutes
def send_smart_reminder_push_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for smart reminder push")
return
with external_url_context(app_instance):
try:
send_smart_reminder_push_notifications()
except Exception as e:
logger.warning("Smart reminder push job failed: %s", e)
_add_job(
scheduler,
func=send_smart_reminder_push_with_app,
trigger="interval",
minutes=15,
id="smart_reminder_push",
name="Send smart reminder browser push notifications",
replace_existing=True,
)
logger.info("Registered smart reminder push task")
# Idle timeout safety net – every 5 minutes
def check_idle_timers_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for idle timer check")
return
with external_url_context(app_instance):
try:
check_idle_timers()
except Exception as e:
logger.warning("Idle timer check job failed: %s", e)
_add_job(
scheduler,
func=check_idle_timers_with_app,
trigger="interval",
minutes=5,
id="check_idle_timers",
name="Check idle timers and auto-stop after grace",
replace_existing=True,
)
logger.info("Registered idle timer check task")
def check_working_time_limits_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
logger.error("No app instance available for working time limits check")
return
with external_url_context(app_instance):
check_working_time_limits()
_add_job(
scheduler,
func=check_working_time_limits_with_app,
trigger="interval",
minutes=15,
id="check_working_time_limits",
name="Check working time limits and auto-close stale workdays",
replace_existing=True,
)
logger.info("Registered working time limits check task")
# Base telemetry heartbeat (daily) – always-on minimal install footprint
def send_base_telemetry_heartbeat_with_app():
app_instance = app
if app_instance is None:
try:
app_instance = current_app._get_current_object()
except RuntimeError:
return
with external_url_context(app_instance):
try:
from app.telemetry.service import send_base_heartbeat
send_base_heartbeat()
except Exception:
logger.debug("Base telemetry heartbeat failed", exc_info=True)
_add_job(
scheduler,