-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmodule_manager.py
More file actions
2220 lines (1878 loc) · 79.3 KB
/
Copy pathmodule_manager.py
File metadata and controls
2220 lines (1878 loc) · 79.3 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
#!/usr/bin/env python3
"""
Module Manager - Core module loading and management system.
Discovers, loads, and manages application modules.
Each module lives in modules/<name>/ with an index.py that defines a class
inheriting from BaseModule.
"""
import os
import logging
logger = logging.getLogger(__name__)
def _sanitize_log(value):
"""Strip control characters to prevent log injection."""
if not isinstance(value, str):
value = str(value)
return value.replace('\n', '\\n').replace('\r', '\\r').replace('\t', '\\t')
import importlib
import importlib.util
from abc import ABC, abstractmethod
class BaseModule(ABC):
"""
Base class for all modules. Every module must inherit from this
and implement the required methods.
"""
def __init__(self, core):
"""
Initialize module with core services.
Args:
core: CoreServices instance providing db, app, settings access, etc.
"""
self.core = core
self.logger = logging.getLogger(f'module.{self.module_id}')
@property
@abstractmethod
def module_id(self):
"""Unique module identifier (e.g., 'tax_management')"""
pass
@property
@abstractmethod
def name(self):
"""Human-readable module name (e.g., 'Tax Management')"""
pass
@property
def description(self):
"""Module description"""
return ''
@property
def version(self):
"""Module version"""
return '0.1.0'
@property
def dependencies(self):
"""Module ids that must be enabled for this module to work correctly.
Returns a list of module_id strings (default: none)."""
return []
@property
def nav_items(self):
"""
Navigation menu items. Return list of dicts:
[{'label': 'Tax Forms', 'endpoint': 'tax_management.tax_forms_index', 'icon': '📋'}]
"""
return []
@property
def settings_panels(self):
"""
Settings panels to add. Return list of dicts:
[{'tab_id': 'tax_settings', 'tab_label': 'Tax Settings', 'template': 'tax_management/settings.html'}]
If empty, no settings tab is added.
"""
return []
def register_models(self, db):
"""
Register database models. Called once during module loading.
Models should be defined as classes inside the module and returned here.
Returns:
dict: {'ModelName': ModelClass, ...}
"""
return {}
def register_routes(self, app):
"""
Register Flask routes. Use self.blueprint to define routes,
then register the blueprint here.
"""
pass
def register_template_filters(self, app):
"""Register any Jinja2 template filters"""
pass
def get_api_routes(self):
"""
Contribute REST endpoints to the /api/v1 API (served by the 'api' module).
Only called for enabled modules, so endpoints are automatically
module-aware (a disabled module exposes nothing).
Returns:
list of dicts, each describing one endpoint:
- 'path': sub-path under /api/v1/ (e.g. 'expenses') — no leading slash
- 'methods': list of HTTP verbs (default ['GET'])
- 'handler': callable(request, **path_params) -> (data, status)
where `data` is a JSON-serializable object and `status`
is an int HTTP code. May also return a Flask Response.
- 'summary': short description for the OpenAPI manifest (optional)
Example:
return [
{'path': 'expenses', 'methods': ['GET'],
'handler': self._api_list_expenses,
'summary': 'List expenses'},
]
"""
return []
def on_enable(self):
"""Called when module is enabled. Use for DB table creation, etc."""
pass
def on_disable(self):
"""Called when module is disabled."""
pass
def get_dashboard_panels(self):
"""
Return dashboard panel data if module contributes to dashboard.
Returns:
list of dicts: [{'template': 'tax_management/dashboard_panel.html', 'data': {...}, 'order': 10}]
"""
return []
def get_capabilities(self):
"""
Declare capabilities this module provides for cross-module interaction.
Returns a list of capability dicts. Each must have at least:
- 'type': capability type string (e.g. 'pdf_sign', 'ocr', 'email_send')
- 'action': callable(context) that performs the action
Optional keys for filtering:
- 'method': sub-type (e.g. 'visual', 'digital', 'x509')
- 'name': human-readable label
- 'accepts': list of file types (e.g. ['pdf', 'jpg'])
- any other keys for filtering
Example:
return [
{
'type': 'pdf_sign',
'method': 'visual',
'name': 'Visual Signature',
'accepts': ['pdf'],
'action': self._sign_visual,
},
]
"""
return []
def get_report_sections(self):
"""
Return report section generators if module contributes to reports.
Returns:
list of dicts: [{'id': 'ss_payments', 'title': 'Social Security', 'generator': callable}]
"""
return []
def get_settings_html(self, settings):
"""
Return HTML to inject into a settings tab.
Called when rendering the settings page.
Args:
settings: The Settings model instance
Returns:
str or None: HTML string to inject, or None
"""
return None
@property
def settings_tab(self):
"""
Which settings tab this module's settings appear in.
Return 'general', 'security', or any custom tab id.
Default: 'general'
"""
return 'general'
def save_settings(self, settings, form):
"""
Handle saving module-specific settings from the General Settings form.
Called during settings POST.
Args:
settings: The Settings model instance
form: The request.form data
"""
pass
def get_tax_obligations(self, context):
"""
Contribute to the Tax Obligations panel on the dashboard.
Called with context dict containing: current_year, income, base_currency,
exchange_rates, settings.
Returns:
dict or None with keys:
- summary_columns: list of {'label': str, 'value': float} for the top summary row
- breakdown_rows: list of {'label': str, 'amount': float} for the tax breakdown table
- notes: list of str for the notes section
- deductions: float — amount to subtract from income for taxable_income
- tax_total: float — total tax amount this module contributes
"""
return None
def calculate_income_tax(self, context):
"""
Override the default income tax (IRPF) calculation.
If a module returns a non-None result, it completely replaces the
built-in Spanish IRPF progressive brackets. Only the first module
that returns a result is used.
Args:
context: dict with keys:
- taxable_income: float
- settings: Settings model instance
- base_currency: str (e.g. 'EUR')
- currency_symbol: str (e.g. '€')
Returns:
dict or None. If dict, must contain:
- income_tax: float — total income tax amount
- irpf_breakdown: list of dicts with keys:
bracket (str), rate (number), amount (float),
tax (float), active (bool)
- label: str — name for the tax (e.g. 'Income Tax (PIT)')
Return None to use the default calculation.
"""
return None
def calculate_vat(self, context):
"""
Override the default VAT collection calculation.
If a module returns a non-None result, it replaces the built-in
VAT calculation. Only the first module that returns a result is used.
Args:
context: dict with keys:
- invoices: list of paid invoices for current year
- settings: Settings model instance
- base_currency: str
Returns:
dict or None. If dict, must contain:
- vat_collected: float — total VAT collected
- vat_rate: float — rate used (e.g. 0.21)
- label: str — name for the tax (e.g. 'VAT', 'IVA', 'PTU')
Return None to use the default calculation.
"""
return None
def get_invoice_actions(self, invoice):
"""
Provide extra action buttons/forms for the invoice view page.
Called by core when rendering an invoice.
Args:
invoice: Invoice model instance
Returns:
list of str: rendered HTML snippets to inject into the actions bar
"""
return []
def get_invoice_view_panels(self, invoice):
"""
Provide extra content panels for the invoice view page.
Rendered below the action buttons. Use for comments, history, etc.
Args:
invoice: Invoice model instance
Returns:
list of str: rendered HTML snippets (full sections/panels)
"""
return []
def get_create_form_html(self):
"""
Return HTML to inject into the invoice create form.
Called when rendering the create invoice page.
Returns:
str or None: HTML string to inject before the submit button
"""
return None
def on_invoice_created(self, invoice, request):
"""
Called after a new invoice is created and committed.
Modules can process their custom form fields here.
Args:
invoice: the newly created Invoice instance (already committed)
request: Flask request object (access form data and files)
"""
pass
def get_edit_form_html(self, invoice):
"""
Return HTML to inject into the invoice edit form.
Called when rendering the edit invoice page.
Args:
invoice: the Invoice being edited
Returns:
str or None: HTML string to inject before the submit button
"""
return None
def on_invoice_updated(self, invoice, request):
"""
Called after an existing invoice is updated and committed.
Modules can process their custom form fields here.
Args:
invoice: the updated Invoice instance (already committed)
request: Flask request object (access form data and files)
"""
pass
def on_invoice_issued(self, invoice, request):
"""
F2 — called when a draft invoice becomes ISSUED, before the transition
commits. Unlike the swallowed panel hooks, a raise here ABORTS the issue
(transactional) so compliance modules (e.g. verifactu) can veto.
"""
pass
def on_invoice_rectified(self, new_invoice, original, request):
"""
F2 — called when a rectificative draft is created from an issued invoice,
before commit. A raise aborts the rectification. `original` is never
mutated.
"""
pass
def on_invoice_annulled(self, invoice, request):
"""
F2 — called when an issued invoice is annulled (marked cancelled), before
commit. A raise aborts the annulment.
"""
pass
def get_invoice_templates(self):
"""
Return invoice PDF templates provided by this module.
Returns:
list[dict]: each dict has:
- 'id': unique template identifier (used in Settings.invoice_template)
- 'name': human-readable name (shown in dropdown)
- 'path': absolute path to the .py template file
"""
return []
def get_field_labels(self):
"""
Override UI labels for core fields.
Country-specific modules can rename fields to match local terminology.
Returns:
dict: field_name -> label string, e.g. {'nie_number': 'PESEL'}
"""
return {}
def get_auth_providers(self):
"""Return auth providers this module offers.
Modules can implement this to add external authentication methods
(Google, Azure AD, Cognito, SAML, etc.).
Returns:
list[AuthProvider]: provider instances to register with AuthService
Example:
from auth import AuthProvider, AuthResult
class GoogleAuthProvider(AuthProvider):
provider_id = 'google'
display_name = 'Google Account'
icon = '🔵'
is_external = True
def authenticate(self, request):
# Handle OAuth callback
...
def get_login_form_html(self):
return '<a href="/auth/google/start" class="btn">Sign in with Google</a>'
def get_auth_providers(self):
return [GoogleAuthProvider(self.core)]
"""
return []
def on_user_authenticated(self, identity):
"""Called after a user successfully authenticates (any provider).
Args:
identity: dict with user info — at minimum {'provider': '...'}
May also include 'name', 'email', 'avatar_url', etc.
"""
pass
def on_user_logout(self):
"""Called when a user logs out."""
pass
class FileStorageBackend:
"""
Abstract file storage backend.
Modules can replace the default backend via CoreServices.set_storage_backend().
"""
def save(self, file_data, relative_path):
"""
Save file data to storage.
Args:
file_data: file-like object (e.g., from request.files) or bytes
relative_path: path relative to app root (e.g., 'documents_files/20260315_doc.pdf')
Returns:
str: the storage key/path used to retrieve the file later
"""
raise NotImplementedError
def delete(self, storage_key):
"""
Delete a file from storage.
Args:
storage_key: the key returned by save()
"""
raise NotImplementedError
def get(self, storage_key):
"""
Get file content.
Args:
storage_key: the key returned by save()
Returns:
tuple: (file_bytes, filename) or None
"""
raise NotImplementedError
def send(self, storage_key, download_name=None):
"""
Send file as Flask response (for downloads).
Args:
storage_key: the key returned by save()
download_name: filename for the download
Returns:
Flask response
"""
raise NotImplementedError
def exists(self, storage_key):
"""Check if file exists in storage"""
raise NotImplementedError
class LocalStorageBackend(FileStorageBackend):
"""Default local filesystem storage"""
def __init__(self, app_root):
self.app_root = app_root
def _full_path(self, relative_path):
# Handle both relative and absolute paths (backward compatibility)
if os.path.isabs(relative_path):
return relative_path
return os.path.join(self.app_root, relative_path)
def save(self, file_data, relative_path):
full_path = self._full_path(relative_path)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
if hasattr(file_data, 'save'):
file_data.save(full_path)
else:
with open(full_path, 'wb') as f:
f.write(file_data if isinstance(file_data, bytes) else file_data.read())
return relative_path
def delete(self, storage_key):
full_path = self._full_path(storage_key)
if os.path.exists(full_path):
os.remove(full_path)
def get(self, storage_key):
full_path = self._full_path(storage_key)
if not os.path.exists(full_path):
return None
with open(full_path, 'rb') as f:
return f.read(), os.path.basename(storage_key)
def send(self, storage_key, download_name=None):
from flask import send_from_directory
full = self._full_path(storage_key)
directory = os.path.dirname(full)
filename = os.path.basename(full)
return send_from_directory(directory, filename, as_attachment=True,
download_name=download_name or filename)
def exists(self, storage_key):
return os.path.exists(self._full_path(storage_key))
class ActivityLogger:
"""
Base activity logger. Stores user/system activity entries.
Modules can subclass or replace via CoreServices.set_activity_logger().
"""
def log(self, action, category='system', details=None, user=None):
"""
Log an activity entry.
Args:
action: short description, e.g. 'login', 'invoice_created'
category: 'auth', 'invoice', 'expense', 'backup', 'settings', 'system', etc.
details: optional extra info (str or dict)
user: optional user identifier
"""
pass
def get_entries(self, limit=100, category=None, offset=0):
"""
Retrieve log entries.
Returns:
list of dicts: [{'id', 'timestamp', 'action', 'category', 'details', 'user'}, ...]
"""
return []
def clear(self, before=None):
"""Clear log entries, optionally only those before a given datetime."""
pass
class FileActivityLogger(ActivityLogger):
"""Default file-based activity logger: one JSON-lines file per day."""
def __init__(self, log_dir):
import json as _json
self._json = _json
self._log_dir = os.path.join(log_dir, 'logs')
os.makedirs(self._log_dir, exist_ok=True)
@property
def log_dir(self):
return self._log_dir
@log_dir.setter
def log_dir(self, path):
self._log_dir = path
os.makedirs(self._log_dir, exist_ok=True)
def _today_file(self):
from datetime import date
return os.path.join(self._log_dir,
f'{date.today().isoformat()}.log')
def log(self, action, category='system', details=None, user=None):
try:
from datetime import datetime
det = details if isinstance(details, str) else (
self._json.dumps(details, ensure_ascii=False)
if details else None)
entry = {
'ts': datetime.utcnow().isoformat(),
'action': action,
'cat': category,
'details': det,
'user': user,
}
with open(self._today_file(), 'a', encoding='utf-8') as fh:
fh.write(self._json.dumps(entry, ensure_ascii=False) + '\n')
except Exception as e:
logger.error('FileLogger write error: %s', e)
def get_entries(self, limit=100, category=None, offset=0,
date_from=None, date_to=None, search=None):
"""Read entries from log files, newest first."""
files = sorted(
[f for f in os.listdir(self._log_dir) if f.endswith('.log')],
reverse=True)
if date_from:
files = [f for f in files if f[:-4] >= date_from]
if date_to:
files = [f for f in files if f[:-4] <= date_to]
entries = []
skipped = 0
for fname in files:
if len(entries) >= limit:
break
fpath = os.path.join(self._log_dir, fname)
try:
with open(fpath, 'r', encoding='utf-8') as fh:
lines = fh.read().strip().split('\n')
except Exception:
continue
for line in reversed(lines):
if not line.strip():
continue
try:
e = self._json.loads(line)
except Exception:
continue
if category and e.get('cat') != category:
continue
if search and search.lower() not in line.lower():
continue
if skipped < offset:
skipped += 1
continue
entries.append({
'timestamp': e.get('ts'),
'action': e.get('action'),
'category': e.get('cat', 'system'),
'details': e.get('details'),
'user': e.get('user'),
})
if len(entries) >= limit:
break
return entries
def get_categories(self):
"""Scan log files for unique categories."""
cats = set()
for fname in os.listdir(self._log_dir):
if not fname.endswith('.log'):
continue
fpath = os.path.join(self._log_dir, fname)
try:
with open(fpath, 'r', encoding='utf-8') as fh:
for line in fh:
if line.strip():
try:
cats.add(
self._json.loads(line).get('cat', 'system'))
except (ValueError, KeyError):
continue
except OSError:
continue
return sorted(cats)
def cleanup(self, retention_days):
"""Delete log files older than retention_days. 0 = keep all."""
if retention_days <= 0:
return
from datetime import date, timedelta
cutoff = (date.today() - timedelta(days=retention_days)).isoformat()
for fname in os.listdir(self._log_dir):
if fname.endswith('.log') and fname[:-4] < cutoff:
try:
os.remove(os.path.join(self._log_dir, fname))
except OSError:
continue
def clear(self, before=None):
if before:
cutoff = before.strftime('%Y-%m-%d')
for fname in os.listdir(self._log_dir):
if fname.endswith('.log') and fname[:-4] < cutoff:
try:
os.remove(os.path.join(self._log_dir, fname))
except OSError:
continue
else:
for fname in os.listdir(self._log_dir):
if fname.endswith('.log'):
try:
os.remove(os.path.join(self._log_dir, fname))
except OSError:
continue
class DbActivityLogger(ActivityLogger):
"""Database-backed activity logger: stores entries in an activity_log table."""
def __init__(self, db, app):
self._db = db
self._app = app
self._json = __import__('json')
self._ensure_table()
def _ensure_table(self):
from sqlalchemy import text
with self._app.app_context():
with self._db.engine.connect() as conn:
conn.execute(text('''
CREATE TABLE IF NOT EXISTS activity_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
action TEXT NOT NULL,
category TEXT DEFAULT 'system',
details TEXT,
user TEXT
)
'''))
conn.commit()
def log(self, action, category='system', details=None, user=None):
try:
from datetime import datetime
from sqlalchemy import text
det = details if isinstance(details, str) else (
self._json.dumps(details, ensure_ascii=False) if details else None)
with self._db.engine.connect() as conn:
conn.execute(text(
'INSERT INTO activity_log (timestamp, action, category, details, user) '
'VALUES (:ts, :action, :cat, :det, :usr)'),
{'ts': datetime.utcnow().isoformat(), 'action': action,
'cat': category, 'det': det, 'usr': user})
conn.commit()
except Exception as e:
logger.error('DbLogger log error: %s', e)
def get_entries(self, limit=100, category=None, offset=0,
date_from=None, date_to=None, search=None):
from sqlalchemy import text
clauses = []
params = {}
if category:
clauses.append('category = :cat')
params['cat'] = category
if date_from:
clauses.append('timestamp >= :df')
params['df'] = date_from
if date_to:
clauses.append('timestamp <= :dt')
params['dt'] = date_to + 'T23:59:59' if date_to and 'T' not in date_to else date_to
if search:
clauses.append("(action LIKE :s OR details LIKE :s)")
params['s'] = f'%{search}%'
where = (' WHERE ' + ' AND '.join(clauses)) if clauses else ''
sql = f'SELECT timestamp, action, category, details, user FROM activity_log{where} ORDER BY id DESC LIMIT :lim OFFSET :off'
params['lim'] = limit
params['off'] = offset
entries = []
try:
with self._db.engine.connect() as conn:
rows = conn.execute(text(sql), params).fetchall()
for r in rows:
entries.append({
'timestamp': r[0], 'action': r[1],
'category': r[2] or 'system',
'details': r[3], 'user': r[4],
})
except Exception as e:
logger.error('DbLogger get_entries error: %s', e)
return entries
def get_categories(self):
from sqlalchemy import text
try:
with self._db.engine.connect() as conn:
rows = conn.execute(text(
'SELECT DISTINCT category FROM activity_log ORDER BY category')).fetchall()
return [r[0] for r in rows if r[0]]
except Exception as e:
logger.error('DbLogger get_categories error: %s', e)
return []
def cleanup(self, retention_days):
if retention_days <= 0:
return
from datetime import date, timedelta
from sqlalchemy import text
cutoff = (date.today() - timedelta(days=retention_days)).isoformat()
try:
with self._db.engine.connect() as conn:
conn.execute(text('DELETE FROM activity_log WHERE timestamp < :c'), {'c': cutoff})
conn.commit()
except Exception as e:
logger.error('DbLogger cleanup error: %s', e)
def clear(self, before=None):
from sqlalchemy import text
try:
with self._db.engine.connect() as conn:
if before:
conn.execute(text('DELETE FROM activity_log WHERE timestamp < :b'),
{'b': before.strftime('%Y-%m-%dT%H:%M:%S')})
else:
conn.execute(text('DELETE FROM activity_log'))
conn.commit()
except Exception as e:
logger.error('DbLogger clear error: %s', e)
class TaskScheduler:
"""
Lightweight in-process task scheduler.
Modules register periodic jobs via core.scheduler.add_job().
The scheduler runs a single daemon thread that checks every 30 s
which jobs are due and executes them inside an app context.
Job types:
'interval' – run every *interval* seconds
'daily' – run once per day at *time_str* (HH:MM, 24-h, local)
"""
def __init__(self, app):
self._app = app
self._jobs = {} # job_id -> dict
self._lock = __import__('threading').Lock()
self._running = False
self._thread = None
# ---- public API used by modules ----
def add_job(self, job_id, func, job_type='interval',
interval=3600, time_str='03:00', description='', timeout=3600):
"""
Register a periodic job.
Args:
job_id: unique string, e.g. 'backup.daily'
func: callable (no args) to execute
job_type: 'interval' | 'daily'
interval: seconds between runs (for 'interval' type)
time_str: 'HH:MM' local time (for 'daily' type)
description: human-readable label
timeout: max seconds a single run may take before being
abandoned so it can't block the scheduler forever
"""
from datetime import datetime
with self._lock:
self._jobs[job_id] = {
'func': func,
'type': job_type,
'interval': interval,
'time_str': time_str,
'description': description,
'timeout': timeout,
'last_run': None,
'next_run': self._calc_next(job_type, interval, time_str),
'running': False,
'last_error': None,
'history': [], # last runs: {ran_at, duration_ms, error}
}
def remove_job(self, job_id):
"""Unregister a job."""
with self._lock:
self._jobs.pop(job_id, None)
def get_jobs(self):
"""Return a snapshot list of registered jobs (safe for templates)."""
with self._lock:
out = []
for jid, j in self._jobs.items():
out.append({
'id': jid,
'description': j['description'],
'type': j['type'],
'interval': j['interval'],
'time_str': j['time_str'],
'last_run': j['last_run'].isoformat() if j['last_run'] else None,
'next_run': j['next_run'].isoformat() if j['next_run'] else None,
'running': j['running'],
'last_error': j['last_error'],
'history': list(j.get('history', [])),
})
return out
def get_history(self, job_id, limit=10):
"""Return the recent run history for a job (most recent last)."""
with self._lock:
j = self._jobs.get(job_id)
return list(j.get('history', []))[-limit:] if j else []
def start(self):
"""Start the scheduler background thread (idempotent)."""
if self._running:
return
self._running = True
import threading
self._thread = threading.Thread(target=self._loop, daemon=True,
name='task-scheduler')
self._thread.start()
def stop(self):
"""Signal the scheduler to stop."""
self._running = False
# ---- internals ----
def _calc_next(self, job_type, interval, time_str):
from datetime import datetime, timedelta
now = datetime.now()
if job_type == 'daily':
h, m = (int(x) for x in time_str.split(':'))
target = now.replace(hour=h, minute=m, second=0, microsecond=0)
if target <= now:
target += timedelta(days=1)
return target
else:
return now + timedelta(seconds=interval)
def _loop(self):
import time as _time
while self._running:
self._tick()
_time.sleep(30)
def _tick(self):
from datetime import datetime
now = datetime.now()
with self._lock:
due = [(jid, j) for jid, j in self._jobs.items()
if j['next_run'] and j['next_run'] <= now and not j['running']]
for jid, j in due:
self._run_job(jid, j)
def _run_job(self, jid, j):
from datetime import datetime
import threading
import time as _time
_started = _time.time()
with self._lock:
j['running'] = True
# Run the job body in a separate daemon thread so a hung job (slow S3,
# an AI parse that never returns) can't block the scheduler indefinitely.
result = {'error': None}
def _execute():
try:
with self._app.app_context():
j['func']()
except Exception as e:
result['error'] = str(e)
logger.error('Scheduler job %s failed: %s', jid, e)
timeout = j.get('timeout', 3600)
worker = threading.Thread(target=_execute, name=f'job:{jid}', daemon=True)
worker.start()
worker.join(timeout=timeout)
try:
if worker.is_alive():
# The thread keeps running (daemon) but we stop waiting on it and
# schedule the next run so other jobs aren't starved.
j['last_error'] = f'Job timed out after {timeout}s'
logger.error('Scheduler job %s timed out after %ss', jid, timeout)
else:
j['last_error'] = result['error']
finally:
with self._lock:
j['running'] = False
j['last_run'] = datetime.now()
j['next_run'] = self._calc_next(
j['type'], j['interval'], j['time_str'])
# Keep a bounded in-memory run history for the Scheduled Tasks page.
hist = j.setdefault('history', [])
hist.append({
'ran_at': j['last_run'].isoformat(),
'duration_ms': int((_time.time() - _started) * 1000),
'error': j['last_error'],
})