File size: 10,638 Bytes
4a2ab42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ae946d
 
 
4a2ab42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ae946d
 
4a2ab42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Database Seed Data Generator

This script generates realistic test data for the fraud detection system,
including sample cases, evidence, transactions, and users.
"""

import os
import random
import sys
from datetime import datetime, timedelta

# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy.orm import Session

from app.services.infrastructure.auth_service import auth_service
from core.database import (
    Base,
    Case,
    CaseNote,
    Evidence,
    Transaction,
    User,
    create_engine_and_session,
)

# Sample data
SAMPLE_COMPANIES = [
    "TechStart Solutions",
    "Global Trade Corp",
    "Pacific Imports",
    "Metro Construction",
    "Digital Services LLC",
    "Coastal Retail",
    "Summit Manufacturing",
    "Valley Logistics",
    "Urban Development",
    "Harbor Shipping Co",
]

SAMPLE_INVESTIGATORS = [
    "Sarah Chen",
    "Michael Rodriguez",
    "Emily Thompson",
    "David Park",
    "Jessica Williams",
    "Robert Kim",
]

FRAUD_INDICATORS = [
    "Unusual transaction pattern",
    "Duplicate invoices detected",
    "Vendor verification failed",
    "Timeline inconsistencies",
    "Document alterations found",
    "Suspicious bank transfers",
    "Shell company indicators",
    "Round number transactions",
    "Missing documentation",
    "Conflicting statements",
]

CASE_DESCRIPTIONS = [
    "Investigation into suspected invoice fraud scheme involving multiple vendors",
    "Analysis of potentially fraudulent expense reports submitted over 6-month period",
    "Review of suspicious wire transfers to overseas accounts",
    "Examination of construction project cost overruns and billing irregularities",
    "Investigation of employee embezzlement through falsified vendor payments",
    "Analysis of procurement fraud and kickback scheme",
    "Review of financial statement manipulation and revenue recognition issues",
    "Investigation of identity theft and fraudulent account access",
    "Examination of insurance claim fraud with fabricated evidence",
    "Analysis of cryptocurrency-related fraud and money laundering",
]


def generate_sample_users(db: Session, count: int = 5):
    """Generate sample users"""
    users = []
    for i in range(count):
        user = User(
            email=f"investigator{i + 1}@Zenith.com",
            username=f"investigator_{i + 1}",
            full_name=SAMPLE_INVESTIGATORS[i % len(SAMPLE_INVESTIGATORS)],
            password_hash=auth_service.hash_password("Test123!"),
            role="investigator" if i > 0 else "admin",
            is_active=True,
            created_at=datetime.now() - timedelta(days=random.randint(30, 365)),
        )
        users.append(user)
        db.add(user)

    db.commit()
    return users


def generate_sample_cases(db: Session, users: list, count: int = 20):
    """Generate sample fraud cases"""
    cases = []

    statuses = ["open", "in_progress", "under_review", "closed"]
    priorities = ["low", "medium", "high", "critical"]
    risk_levels = ["low", "medium", "high", "critical"]

    for i in range(count):
        # Random dates
        created_date = datetime.now() - timedelta(days=random.randint(1, 180))

        case_metadata = {
            "case_number": f"FR-2024-{str(i + 1).zfill(4)}",
            "company_name": SAMPLE_COMPANIES[i % len(SAMPLE_COMPANIES)],
            "risk_level": random.choice(risk_levels),
            "created_by": users[0].id,
            "amount_involved": random.uniform(5000, 500000),
            "currency": "USD",
        }

        case = Case(
            title=f"Investigation: {SAMPLE_COMPANIES[i % len(SAMPLE_COMPANIES)]}",
            description=random.choice(CASE_DESCRIPTIONS),
            status=random.choice(statuses),
            priority=random.choice(priorities),
            assignee_id=users[random.randint(0, len(users) - 1)].id,
            case_type=random.choice(
                [
                    "financial_fraud",
                    "procurement_fraud",
                    "embezzlement",
                    "identity_theft",
                ]
            ),
            created_at=created_date,
            updated_at=created_date + timedelta(days=random.randint(1, 30)),
            case_metadata=case_metadata,
        )

        cases.append(case)
        db.add(case)

    db.commit()
    return cases


def generate_sample_transactions(db: Session, cases: list, count_per_case: int = 5):
    """Generate sample transactions for cases"""
    transaction_types = ["debit", "credit", "transfer", "payment"]

    for case in cases:
        for i in range(random.randint(2, count_per_case)):
            tx_metadata = {
                "account_number": f"****{random.randint(1000, 9999)}",
                "is_suspicious": random.choice([True, False]),
                "fraud_score": random.uniform(0, 1) if random.random() > 0.5 else None,
            }
            transaction = Transaction(
                case_id=case.id,
                date=case.created_at + timedelta(days=random.randint(-30, 0)),
                amount=random.uniform(100, 50000),
                currency="USD",
                type=random.choice(transaction_types),
                description=f"Transaction {i + 1} - {random.choice(['Invoice payment', 'Wire transfer', 'Check payment', 'ACH transfer'])}",
                merchant_name=random.choice(SAMPLE_COMPANIES),
                transaction_metadata=tx_metadata,
            )
            db.add(transaction)

    db.commit()


def generate_sample_evidence(db: Session, cases: list):
    """Generate sample evidence entries"""
    evidence_types = ["document", "image", "video", "email", "financial_record"]

    for case in cases:
        for i in range(random.randint(1, 4)):
            import json

            tags_json = json.dumps(random.sample(FRAUD_INDICATORS, k=random.randint(1, 3)))
            metadata_json = json.dumps(
                {
                    "description": f"Evidence item {i + 1} - {random.choice(['Original invoice', 'Bank statement', 'Email correspondence', 'Photo evidence'])}"
                }
            )

            evidence = Evidence(
                case_id=case.id,
                filename=f"evidence_{i + 1}_{random.choice(['invoice', 'receipt', 'email', 'statement', 'photo'])}.pdf",
                file_type=random.choice(evidence_types),
                size_bytes=random.randint(100000, 5000000),
                uploaded_at=case.created_at + timedelta(days=random.randint(1, 20)),
                processing_status="processed",
                evidence_tags=tags_json,
                evidence_metadata=metadata_json,
            )
            db.add(evidence)

    db.commit()


def generate_sample_notes(db: Session, cases: list, users: list):
    """Generate sample case notes"""
    note_templates = [
        "Initial review completed. {indicator}",
        "Follow-up interview scheduled with subject.",
        "Additional documentation requested from {company}.",
        "Analysis reveals {indicator}",
        "Coordination with legal team regarding next steps.",
        "Updated fraud risk assessment based on new evidence.",
        "Case escalated to senior investigator for review.",
        "Witness statement obtained and documented.",
    ]

    for case in cases:
        # Since we moved company_name to metadata, access it from there
        company = case.case_metadata.get("company_name", "Unknown Company")
        for i in range(random.randint(2, 6)):
            note_content = random.choice(note_templates).format(
                indicator=random.choice(FRAUD_INDICATORS), company=company
            )

            note = CaseNote(
                case_id=case.id,
                user_id=users[random.randint(0, len(users) - 1)].id,
                content=note_content,
                created_at=case.created_at + timedelta(days=random.randint(1, 25)),
            )
            db.add(note)

    db.commit()


def seed_database(clear_existing: bool = False):
    """
    Seed the database with sample data.

    Args:
        clear_existing: If True, clear all existing data first
    """
    engine, session_local = create_engine_and_session()
    db = session_local()

    try:
        if clear_existing:
            print("⚠️  Clearing existing data...")
            # Clear all tables (be careful with this!)
            Base.metadata.drop_all(bind=engine)
            Base.metadata.create_all(bind=engine)
            print("βœ… Tables recreated")

        print("πŸ“ Generating sample data...")

        # Generate users
        print("  Creating users...")
        users = generate_sample_users(db, count=6)
        print(f"  βœ… Created {len(users)} users")

        # Generate cases
        print("  Creating cases...")
        cases = generate_sample_cases(db, users, count=150)
        print(f"  βœ… Created {len(cases)} cases")

        # Generate transactions
        print("  Creating transactions...")
        generate_sample_transactions(db, cases, count_per_case=5)
        print("  βœ… Created transactions")

        # Generate evidence
        print("  Creating evidence...")
        generate_sample_evidence(db, cases)
        print("  βœ… Created evidence entries")

        # Generate notes
        print("  Creating case notes...")
        generate_sample_notes(db, cases, users)
        print("  βœ… Created case notes")

        print("\nβœ… Database seeding completed successfully!")

        # Print summary
        print("\nπŸ“Š Summary:")
        print(f"  Users: {len(users)}")
        print(f"  Cases: {len(cases)}")
        print("  Status breakdown:")
        for status in ["open", "in_progress", "under_review", "closed"]:
            count = len([c for c in cases if c.status == status])
            print(f"    - {status}: {count}")

    except Exception as e:
        print(f"\n❌ Error seeding database: {e}")
        db.rollback()
        raise
    finally:
        db.close()


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Seed database with sample data")
    parser.add_argument(
        "--clear",
        action="store_true",
        help="Clear existing data before seeding (WARNING: destructive)",
    )

    args = parser.parse_args()

    if args.clear:
        confirm = input("⚠️  This will DELETE all existing data. Are you sure? (yes/no): ")
        if confirm.lower() != "yes":
            print("Cancelled.")
            exit(0)

    seed_database(clear_existing=args.clear)