Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions app/api/deps/db_admin.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from fastapi import Depends, Header, HTTPException
from fastapi import Depends, Header
from sqlalchemy.orm import Session

from app.api.deps.db import get_db_rls
from app.core.db import set_tenant_context

def get_db_admin(
db: Session = Depends(get_db_rls),
Expand Down
7 changes: 1 addition & 6 deletions app/api/routes/admin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from __future__ import annotations
import math
from typing import Optional
from uuid import UUID
from app.api.deps.auth import get_current_user
Expand All @@ -8,11 +7,7 @@
from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import text
from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import text, select, func
from uuid import UUID
from datetime import date, timedelta
from sqlalchemy import select, func

from app.api.deps.db import get_db_rls as get_db
from app.models.screening_db import (
Expand Down
13 changes: 6 additions & 7 deletions app/api/routes/analyst.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from __future__ import annotations

from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from typing import Any, Dict, List, Optional
from uuid import UUID
from io import StringIO
import csv
Expand All @@ -11,19 +11,16 @@
from fastapi.responses import StreamingResponse

from pydantic import BaseModel, Field
from sqlalchemy import func, select, text
from sqlalchemy import select, text
from sqlalchemy.orm import Session
from sqlalchemy.sql import desc

from app.api.deps.auth import get_current_user
from app.api.deps.db import get_db_rls as get_db

from app.models.case import Case
from app.models.screening_db import (
Entity,
ScreeningMatch,
ScreeningRequest,
ScreeningResult,
SourceRecord,
)

Expand Down Expand Up @@ -1041,7 +1038,8 @@ def iter_csv():

writer.writerow(HEADERS)
yield buf.getvalue()
buf.seek(0); buf.truncate()
buf.seek(0)
buf.truncate()

for row in result.mappings():
payload = row.get("request_payload") or {}
Expand Down Expand Up @@ -1109,7 +1107,8 @@ def iter_csv():
row.get("completed_at") or "",
])
yield buf.getvalue()
buf.seek(0); buf.truncate()
buf.seek(0)
buf.truncate()

risk_part = risk_norm.lower() if risk_norm else "all"
status_part = status_norm.lower() if status_norm else "all"
Expand Down
23 changes: 15 additions & 8 deletions app/api/routes/cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,10 @@ def list_cases(
).mappings().all()
risk_by_case = {r["case_id"]: r["risk_level"] for r in rows}
except Exception:
try: db.rollback()
except Exception: pass
try:
db.rollback()
except Exception:
pass

# ── Bulk: client_name depuis screening_requests ──────────────────
name_by_case: dict[str, str] = {}
Expand Down Expand Up @@ -135,17 +137,22 @@ def list_cases(
if name:
name_by_case[r["case_id"]] = name
except Exception:
try: db.rollback()
except Exception: pass
try:
db.rollback()
except Exception:
pass

# ── Sérialisation manuelle (bypass Pydantic) ─────────────────────
def _str(v) -> str | None:
return str(v) if v is not None else None

def _dt(v) -> str | None:
if v is None: return None
try: return v.isoformat()
except Exception: return str(v)
if v is None:
return None
try:
return v.isoformat()
except Exception:
return str(v)

items = []
for c in cases:
Expand Down Expand Up @@ -285,7 +292,7 @@ def update_case_status(

candidates = STATUS_CANDIDATES.get(new_status)
if not candidates:
raise HTTPException(422, f"Status invalide. Valeurs: PENDING, IN_PROGRESS, CLOSED")
raise HTTPException(422, "Status invalide. Valeurs: PENDING, IN_PROGRESS, CLOSED")

# Premier candidat présent dans l'enum réel
mapped = next((c for c in candidates if c in valid_values), None)
Expand Down
15 changes: 9 additions & 6 deletions app/api/routes/documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from uuid import UUID
from pathlib import Path
from typing import Dict, Any
from sqlalchemy import text
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, Query
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session
Expand Down Expand Up @@ -61,10 +60,14 @@ def _guess_mime(doc: Document) -> str:
if getattr(doc, "mime_type", None):
return str(doc.mime_type)
name = (getattr(doc, "original_filename", None) or getattr(doc, "object_key", None) or "").lower()
if name.endswith(".pdf"): return "application/pdf"
if name.endswith(".png"): return "image/png"
if name.endswith(".jpg") or name.endswith(".jpeg"): return "image/jpeg"
if name.endswith(".webp"): return "image/webp"
if name.endswith(".pdf"):
return "application/pdf"
if name.endswith(".png"):
return "image/png"
if name.endswith(".jpg") or name.endswith(".jpeg"):
return "image/jpeg"
if name.endswith(".webp"):
return "image/webp"
return "application/octet-stream"


Expand Down Expand Up @@ -244,7 +247,7 @@ def _run_ocr_background(doc_id: UUID, tenant_id: str) -> None:
f"prefill={list(prefill.keys())}"
)

except Exception as e:
except Exception:
import traceback
print(f"[ocr background] ❌ doc={doc_id} tenant={tenant_id}")
print(traceback.format_exc())
Expand Down
3 changes: 1 addition & 2 deletions app/api/routes/settings_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from sqlalchemy import text
from sqlalchemy.orm import Session

Expand Down Expand Up @@ -401,7 +400,7 @@ def list_users(
).mappings().all()
return JSONResponse(content=[dict(r) for r in rows])

except Exception as e:
except Exception:
# Retry without role/is_active if columns don't exist
try:
db.rollback()
Expand Down
6 changes: 3 additions & 3 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
# --- Routers (import après setup_logging) ---
from app.api.routes import admin # noqa: E402
from app.api.routes.admin_tenants import router as admin_tenants_router # noqa: E402
from app.api.routes.adverse_media import router as adverse_media_router
from app.api.routes.adverse_media import router as adverse_media_router # noqa: E402
from app.api.routes.blacklist import router as blacklist_router # noqa: E402
from app.api.routes.alerting import router as alerting_router # noqa: E402
from app.api.routes.analyst import router as analyst_router # noqa: E402
Expand All @@ -32,8 +32,8 @@
from app.api.routes.documents import router as documents_router # noqa: E402
from app.api.routes.health import router as health_router # noqa: E402
from app.api.routes.integration import router as integration_router # noqa: E402
from app.api.routes.kyt import router as kyt_router
from app.api.routes.ubo import router as ubo_router
from app.api.routes.kyt import router as kyt_router # noqa: E402
from app.api.routes.ubo import router as ubo_router # noqa: E402
from app.api.routes.offshore import router as offshore_router # noqa: E402
from app.api.routes.rbac import router as rbac_router # noqa: E402
from app.api.routes.referentiel import router as referentiel_router # noqa: E402
Expand Down
1 change: 0 additions & 1 deletion app/models/offshore.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
from __future__ import annotations

import enum
import uuid

from sqlalchemy import Column, DateTime, Enum, Index, Integer, String, Text
from sqlalchemy.dialects.postgresql import JSONB
Expand Down
2 changes: 1 addition & 1 deletion app/services/blacklist_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from sqlalchemy import text
from sqlalchemy.orm import Session

from app.services import list_ingest, list_refresh
from app.services import list_refresh

logger = logging.getLogger("simandou.blacklist")

Expand Down
4 changes: 2 additions & 2 deletions app/services/cascading_screening.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

from datetime import datetime, timezone
from typing import Any, Callable, Optional
from typing import Any, Callable
import json

from sqlalchemy import text
Expand Down Expand Up @@ -110,7 +110,7 @@ def start_post_kyc_cascade(case_id: str, db: Session) -> str:
# 3) Run now (synchronous MVP)
try:
_run_screening_request_now(request_id=request_id, db=db)
except Exception as e:
except Exception:
# Optionnel: marquer FAILED si tu veux un état DB clair
# (si ton runner gère déjà FAILED, tu peux enlever ce bloc)
try:
Expand Down
12 changes: 8 additions & 4 deletions app/services/documents_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,14 @@ def _local_path(object_key: str) -> Path:

def _ocr_fields_to_prefill(fields: Dict[str, Any]) -> Dict[str, Any]:
prefill: Dict[str, Any] = {}
if fields.get("last_name"): prefill["nom"] = fields["last_name"]
if fields.get("first_name"): prefill["prenom"] = fields["first_name"]
if fields.get("date_of_birth"): prefill["dob"] = fields["date_of_birth"]
if fields.get("document_number"): prefill["card_number"] = fields["document_number"]
if fields.get("last_name"):
prefill["nom"] = fields["last_name"]
if fields.get("first_name"):
prefill["prenom"] = fields["first_name"]
if fields.get("date_of_birth"):
prefill["dob"] = fields["date_of_birth"]
if fields.get("document_number"):
prefill["card_number"] = fields["document_number"]
return prefill


Expand Down
10 changes: 5 additions & 5 deletions app/services/export_pdf_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from reportlab.lib.units import mm
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER
from reportlab.lib.enums import TA_LEFT, TA_RIGHT
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
Image, PageBreak, HRFlowable, KeepTogether,
Expand All @@ -26,7 +26,7 @@
from app.core.db import set_tenant_context

from app.models.screening_db import (
ScreeningMatch, SourceRecord, Entity,
SourceRecord, Entity,
)

# ─── Constants ────────────────────────────────────────────────
Expand Down Expand Up @@ -234,9 +234,9 @@ def _run() -> tuple[dict | None, list[dict]]:
rows = db.execute(
text(Q.format(col="request_id", p="rid")), {"rid": request_id}
).mappings().all()
l, h = _rows(rows)
if l:
return l, h
lignes, h = _rows(rows)
if lignes:
return lignes, h

if case_id:
rows = db.execute(
Expand Down
12 changes: 8 additions & 4 deletions app/services/local_ocr_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,14 @@ class OCRResult:

def ocr_to_prefill(fields: dict) -> dict:
prefill: Dict[str, Any] = {}
if fields.get("last_name"): prefill["nom"] = fields["last_name"]
if fields.get("first_name"): prefill["prenom"] = fields["first_name"]
if fields.get("date_of_birth"): prefill["dob"] = fields["date_of_birth"]
if fields.get("document_number"): prefill["card_number"] = fields["document_number"]
if fields.get("last_name"):
prefill["nom"] = fields["last_name"]
if fields.get("first_name"):
prefill["prenom"] = fields["first_name"]
if fields.get("date_of_birth"):
prefill["dob"] = fields["date_of_birth"]
if fields.get("document_number"):
prefill["card_number"] = fields["document_number"]
return prefill


Expand Down
2 changes: 1 addition & 1 deletion app/services/matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from app.core.cache import cache, make_key
from app.core.config import settings
from app.core.logging import get_logger
from app.models.screening_db import ScreeningMatch, SourceRecord
from app.models.screening_db import ScreeningMatch

logger = get_logger("simandou.matching")

Expand Down
1 change: 0 additions & 1 deletion app/services/sanctions_sources/un.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from typing import List
from xml.etree import ElementTree as ET

import httpx

from .config import UN_LIST_URL
from .http_client import fetch_bytes
Expand Down
2 changes: 1 addition & 1 deletion app/services/simple_screening_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from sqlalchemy import text
from sqlalchemy.orm import Session

from app.models.screening_db import ScreeningMatch, ScreeningRequest, ScreeningResult
from app.models.screening_db import ScreeningMatch, ScreeningRequest
from app.services.matching import (
band,
normalize_name,
Expand Down
Loading
Loading