File size: 10,021 Bytes
cf739bf
2817797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf739bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9aefc6b
cf739bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
================================================================================
PERSISTENCE LAYER - Alert State & STR Reference Management
================================================================================

PURPOSE:
  Local SQLite database for:
    1. Alert metadata (seen/dismissed/confirmed state)
    2. STR reference numbering (sequential counter)
    3. Alert suppression (avoid duplicate notifications)

  Complements the case management database (Supabase) by storing transient
  operational state (alert lifecycle, STR numbering) that doesn't need
  cloud persistence.

KEY RESPONSIBILITIES:
  1. Store alert acknowledgment state (seen, dismissed, confirmed)
  2. Track alert-investigator assignment
  3. Generate sequential STR references (STR-YYYYMMDD-NNNN)
  4. Suppress duplicate alerts within time window
  5. Provide O(1) lookup of alert states

TABLES:

  alert_state
    - alert_id: TEXT PRIMARY KEY (unique alert identifier)
    - seen: INTEGER (0/1) - Has investigator viewed this?
    - dismissed: INTEGER (0/1) - Explicitly dismissed?
    - confirmed: INTEGER (0/1) - Confirmed as suspicious/clean?
    - assigned_to: TEXT - Investigator ID (optional)
    - last_updated: TEXT - ISO timestamp of last change
    - notes: TEXT - Investigator notes on this alert

  str_counter
    - id: INTEGER PRIMARY KEY AUTOINCREMENT
    - date: TEXT - Date in YYYYMMDD format
    - counter: INTEGER - Daily sequential counter

MAIN FUNCTIONS:

  init_db()
    - Create tables if they don't exist
    - Initialize directory structure
    - Safe to call multiple times (idempotent)
    - Called once at application startup

  get_alert_state(alert_id) β†’ dict
    - Fetch alert metadata by ID
    - Returns: {alert_id, seen, dismissed, confirmed, assigned_to, last_updated, notes}
    - If not found: returns empty state with defaults
    - Used for: checking alert lifecycle, displaying in UI

  update_alert_state(alert_id, **kwargs) β†’ None
    - Update one or more alert fields
    - Auto-updates last_updated timestamp
    - Inserts row if doesn't exist (upsert pattern)
    - Used for: marking seen, confirming alerts, assigning to investigator

  get_all_alert_states() β†’ dict
    - Fetch all alert states at once
    - Returns: {alert_id: state_dict, ...}
    - Enables O(1) lookup of alert state in memory
    - Used for: initialization, bulk state checks

  next_str_reference() β†’ str
    - Generate sequential STR reference number
    - Format: STR-YYYYMMDD-NNNN
    - Daily counter resets each day
    - Thread-safe: uses database lock (sequential)
    - Used for: PDF report naming, STR filing identification

  was_recently_suppressed(account, typology, suppress_hours) β†’ bool
    - Check if alert for this account+typology was seen recently
    - Returns: True if found within suppress_hours
    - Simple implementation: pattern-match on alert_id
    - Production: would use proper alert_id lookup
    - Used for: duplicate suppression, notification throttling

STATE MACHINE (Alert Lifecycle):

  New Alert (entry)
    seen=0, dismissed=0, confirmed=0

  Investigator Views Alert
    β†’ seen=1

  Investigator Dismisses (benign)
    β†’ dismissed=1, confirmed=0 (optional)

  Investigator Confirms (suspicious)
    β†’ confirmed=1, dismissed=0 (optional)

  Assigned to Investigator
    β†’ assigned_to="inv_001"

DATABASE OPERATIONS:

  Connections:
    - sqlite3.connect(_get_db_path()) with row_factory = sqlite3.Row
    - Enables dict-like row access: row['alert_id']

  Transactions:
    - Explicit conn.commit() after INSERT/UPDATE
    - Connection auto-closes with context manager

  Upsert Pattern (update_alert_state):
    1. INSERT OR IGNORE: Create row if missing
    2. UPDATE: Modify fields
    3. COMMIT: Persist changes

DATABASE LOCATION:
  - Path: config['data']['alerts_db_path']
  - Typically: data/alerts.db
  - Relative paths resolved to absolute by config_loader

PERFORMANCE CHARACTERISTICS:

  get_alert_state(id):
    - Single indexed lookup
    - O(log n) via PRIMARY KEY index
    - Negligible latency

  update_alert_state(id, **kwargs):
    - Lookup + update
    - O(log n) lookup + O(1) update
    - Database lock during write
    - Suitable for interactive operations

  get_all_alert_states():
    - Full table scan
    - O(n) where n = number of alerts
    - Returns all states for memory-backed lookup
    - Called sparingly (on startup or manual refresh)

  next_str_reference():
    - Lookup today's counter
    - Increment and commit
    - Database lock during write
    - Sequential (no gaps)
    - Suitable for reference generation

STR REFERENCE NUMBERING:

  Format: STR-YYYYMMDD-NNNN
    - STR prefix: Suspicious Transaction Report identifier
    - YYYYMMDD: Date of generation (resets daily)
    - NNNN: 4-digit sequential counter (0001, 0002, ..., 9999)

  Examples:
    - STR-20260531-0001 (May 31, 2026, first report)
    - STR-20260531-0042 (May 31, 2026, 42nd report)
    - STR-20260601-0001 (June 1, 2026, counter resets)

SUPPRESSION LOGIC:

  Alert Suppression:
    - Prevents flooding with duplicate alerts
    - suppress_hours: grace period (default 24)
    - Pattern: Check if alert for same account+typology in recent period
    - Implementation: Basic pattern-match (would improve in production)

DEPENDENCIES:
  - sqlite3: Standard library
  - os: Path creation
  - datetime: Timestamps and time windows
  - src.config_loader: get_config() for database path

USAGE EXAMPLE:

  # Initialize on startup
  from src.persistence import init_db, next_str_reference, update_alert_state
  init_db()

  # Mark alert as seen
  update_alert_state('alert_123', seen=1)

  # Assign to investigator
  update_alert_state('alert_123', assigned_to='inv_001', confirmed=1)

  # Generate STR reference
  str_ref = next_str_reference()  # "STR-20260531-0042"

  # Check suppression
  from src.persistence import was_recently_suppressed
  if not was_recently_suppressed('ACC_123', 'RoundTripping', 24):
    # Send alert to investigator
    pass

NOTES:

  - SQLite is sufficient for this operational state
  - Production might migrate to Redis for speed
  - No schema migrations needed (simple tables)
  - Thread-safe for concurrent reads, serialized writes
  - Backup: include data/alerts.db in regular backups

================================================================================
"""
import sqlite3
import os
from datetime import datetime

from src.config_loader import get_config

_db_path: str = None


def _get_db_path() -> str:
    global _db_path
    if _db_path is None:
        _db_path = get_config()['data']['alerts_db_path']
    return _db_path


def _get_conn() -> sqlite3.Connection:
    conn = sqlite3.connect(_get_db_path())
    conn.row_factory = sqlite3.Row
    return conn


def init_db() -> None:
    """Create tables if they don't exist."""
    os.makedirs(os.path.dirname(_get_db_path()), exist_ok=True)
    with _get_conn() as conn:
        conn.execute("""
            CREATE TABLE IF NOT EXISTS alert_state (
                alert_id TEXT PRIMARY KEY,
                seen INTEGER DEFAULT 0,
                dismissed INTEGER DEFAULT 0,
                confirmed INTEGER DEFAULT 0,
                assigned_to TEXT DEFAULT NULL,
                last_updated TEXT,
                notes TEXT DEFAULT ''
            )
        """)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS str_counter (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                date TEXT NOT NULL,
                counter INTEGER NOT NULL DEFAULT 1
            )
        """)
        conn.commit()


def get_alert_state(alert_id: str) -> dict:
    with _get_conn() as conn:
        row = conn.execute(
            "SELECT * FROM alert_state WHERE alert_id = ?", (alert_id,)
        ).fetchone()
    if row is None:
        return {'alert_id': alert_id, 'seen': False, 'dismissed': False, 'confirmed': False}
    return dict(row)


def update_alert_state(alert_id: str, **kwargs) -> None:
    kwargs['last_updated'] = datetime.now().isoformat()
    fields = ', '.join(f"{k} = ?" for k in kwargs)
    values = list(kwargs.values()) + [alert_id]
    with _get_conn() as conn:
        conn.execute(
            "INSERT OR IGNORE INTO alert_state (alert_id, last_updated) VALUES (?, ?)",
            (alert_id, kwargs['last_updated'])
        )
        conn.execute(f"UPDATE alert_state SET {fields} WHERE alert_id = ?", values)
        conn.commit()


def get_all_alert_states() -> dict:
    """Returns a dict of alert_id -> state dict for O(1) lookup."""
    with _get_conn() as conn:
        rows = conn.execute("SELECT * FROM alert_state").fetchall()
    return {row['alert_id']: dict(row) for row in rows}


def next_str_reference() -> str:
    """Generate a sequential STR reference: STR-YYYYMMDD-NNNN."""
    today = datetime.now().strftime('%Y%m%d')
    with _get_conn() as conn:
        row = conn.execute(
            "SELECT counter FROM str_counter WHERE date = ?", (today,)
        ).fetchone()
        if row is None:
            conn.execute("INSERT INTO str_counter (date, counter) VALUES (?, 1)", (today,))
            counter = 1
        else:
            counter = row['counter'] + 1
            conn.execute(
                "UPDATE str_counter SET counter = ? WHERE date = ?", (counter, today)
            )
        conn.commit()
    return f"STR-{today}-{counter:04d}"


def was_recently_suppressed(account: str, typology: str, suppress_hours: int) -> bool:
    """Return True if this account+typology was seen within suppress_hours."""
    from datetime import timedelta
    cutoff = (datetime.now() - timedelta(hours=suppress_hours)).isoformat()
    with _get_conn() as conn:
        row = conn.execute("""
            SELECT 1 FROM alert_state
            WHERE alert_id LIKE ? AND last_updated > ? AND dismissed = 0
        """, (f"%{account}%", cutoff)).fetchone()
    # Basic suppression via alert_id pattern β€” production would use a proper lookup
    return row is not None