MustafaHussein commited on
Commit
1fce3ef
·
1 Parent(s): 6f963f8
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +9 -7
  2. SaudiLawTxt/data.txt +0 -0
  3. SaudiLawTxt/saudi_laws_complete.txt +0 -0
  4. app/__init__.py +0 -0
  5. app/__pycache__/__init__.cpython-310.pyc +0 -0
  6. app/__pycache__/create_temp_user.cpython-310.pyc +0 -0
  7. app/__pycache__/init_db.cpython-310.pyc +0 -0
  8. app/__pycache__/main.cpython-310.pyc +0 -0
  9. app/api/__init__.py +0 -0
  10. app/api/__pycache__/__init__.cpython-310.pyc +0 -0
  11. app/api/deps.py +90 -0
  12. app/api/v1/__init__.py +0 -0
  13. app/api/v1/__pycache__/__init__.cpython-310.pyc +0 -0
  14. app/api/v1/__pycache__/anpr.cpython-310.pyc +0 -0
  15. app/api/v1/__pycache__/api.cpython-310.pyc +0 -0
  16. app/api/v1/__pycache__/auth.cpython-310.pyc +0 -0
  17. app/api/v1/__pycache__/chat.cpython-310.pyc +0 -0
  18. app/api/v1/__pycache__/create_temp_user.cpython-310.pyc +0 -0
  19. app/api/v1/__pycache__/stream.cpython-310.pyc +0 -0
  20. app/api/v1/api.py +39 -0
  21. app/api/v1/endpoints/__init__.py +0 -0
  22. app/api/v1/endpoints/__pycache__/__init__.cpython-310.pyc +0 -0
  23. app/api/v1/endpoints/__pycache__/analytics.cpython-310.pyc +0 -0
  24. app/api/v1/endpoints/__pycache__/auth.cpython-310.pyc +0 -0
  25. app/api/v1/endpoints/__pycache__/cases.cpython-310.pyc +0 -0
  26. app/api/v1/endpoints/__pycache__/clients.cpython-310.pyc +0 -0
  27. app/api/v1/endpoints/__pycache__/dashboard.cpython-310.pyc +0 -0
  28. app/api/v1/endpoints/__pycache__/documents.cpython-310.pyc +0 -0
  29. app/api/v1/endpoints/__pycache__/financial.cpython-310.pyc +0 -0
  30. app/api/v1/endpoints/__pycache__/lawyers.cpython-310.pyc +0 -0
  31. app/api/v1/endpoints/__pycache__/llm.cpython-310.pyc +0 -0
  32. app/api/v1/endpoints/__pycache__/notifications.cpython-310.pyc +0 -0
  33. app/api/v1/endpoints/__pycache__/reminders.cpython-310.pyc +0 -0
  34. app/api/v1/endpoints/__pycache__/tickets.cpython-310.pyc +0 -0
  35. app/api/v1/endpoints/__pycache__/users.cpython-310.pyc +0 -0
  36. app/api/v1/endpoints/analytics.py +134 -0
  37. app/api/v1/endpoints/auth.py +144 -0
  38. app/api/v1/endpoints/cases.py +205 -0
  39. app/api/v1/endpoints/clients.py +113 -0
  40. app/api/v1/endpoints/dashboard.py +45 -0
  41. app/api/v1/endpoints/documents.py +166 -0
  42. app/api/v1/endpoints/financial.py +26 -0
  43. app/api/v1/endpoints/lawyers.py +84 -0
  44. app/api/v1/endpoints/llm - original.py +441 -0
  45. app/api/v1/endpoints/llm.py +463 -0
  46. app/api/v1/endpoints/notifications.py +72 -0
  47. app/api/v1/endpoints/reminders.py +149 -0
  48. app/api/v1/endpoints/tickets.py +218 -0
  49. app/api/v1/endpoints/users.py +165 -0
  50. app/core/__init__.py +0 -0
README.md CHANGED
@@ -1,13 +1,15 @@
1
  ---
2
  title: Saudi Law Vision
3
- emoji: 🌍
4
- colorFrom: indigo
5
- colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 6.29.1
8
- python_version: '3.12'
9
- app_file: app.py
10
  pinned: false
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
1
  ---
2
  title: Saudi Law Vision
3
+ emoji: ⚖️
4
+ colorFrom: green
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 4.44.1
8
+ python_version: "3.10"
9
+ app_file: start.py
10
  pinned: false
11
  ---
12
 
13
+ # Saudi Law Vision
14
+
15
+ Arabic legal RAG demo: FastAPI + Qdrant Cloud + Gemini.
SaudiLawTxt/data.txt ADDED
The diff for this file is too large to render. See raw diff
 
SaudiLawTxt/saudi_laws_complete.txt ADDED
The diff for this file is too large to render. See raw diff
 
app/__init__.py ADDED
File without changes
app/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (153 Bytes). View file
 
app/__pycache__/create_temp_user.cpython-310.pyc ADDED
Binary file (747 Bytes). View file
 
app/__pycache__/init_db.cpython-310.pyc ADDED
Binary file (1.31 kB). View file
 
app/__pycache__/main.cpython-310.pyc ADDED
Binary file (5.92 kB). View file
 
app/api/__init__.py ADDED
File without changes
app/api/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (141 Bytes). View file
 
app/api/deps.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Security dependencies - FIXED to accept token from BOTH header AND cookie"""
2
+ from typing import Optional
3
+ from fastapi import Depends, HTTPException, status, Request
4
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
5
+ from jose import JWTError, jwt
6
+ from sqlalchemy.orm import Session
7
+
8
+ from app.core.database import get_db
9
+ from app.core.config import settings
10
+ from app.models.user import User
11
+
12
+ security = HTTPBearer(auto_error=False)
13
+
14
+
15
+ def get_current_user(
16
+ request: Request,
17
+ credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
18
+ db: Session = Depends(get_db)
19
+ ) -> User:
20
+ """
21
+ Get current user from token - accepts BOTH:
22
+ 1. Authorization: Bearer <token> header (JavaScript fetch)
23
+ 2. access_token cookie (iframe/img tags)
24
+ """
25
+
26
+ # Try Authorization header first
27
+ token = None
28
+ if credentials:
29
+ token = credentials.credentials
30
+
31
+ # If no header, try cookie
32
+ if not token:
33
+ token = request.cookies.get("access_token")
34
+
35
+ # No token at all
36
+ if not token:
37
+ raise HTTPException(
38
+ status_code=status.HTTP_401_UNAUTHORIZED,
39
+ detail="Not authenticated",
40
+ headers={"WWW-Authenticate": "Bearer"},
41
+ )
42
+
43
+ # Validate token
44
+ try:
45
+ payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
46
+ user_id: int = payload.get("sub")
47
+ if user_id is None:
48
+ raise HTTPException(
49
+ status_code=status.HTTP_401_UNAUTHORIZED,
50
+ detail="Could not validate credentials"
51
+ )
52
+ except JWTError:
53
+ raise HTTPException(
54
+ status_code=status.HTTP_401_UNAUTHORIZED,
55
+ detail="Could not validate credentials"
56
+ )
57
+
58
+ # Get user from database
59
+ user = db.query(User).filter(User.id == user_id).first()
60
+ if user is None:
61
+ raise HTTPException(
62
+ status_code=status.HTTP_404_NOT_FOUND,
63
+ detail="User not found"
64
+ )
65
+
66
+ return user
67
+
68
+
69
+ def get_current_active_user(
70
+ current_user: User = Depends(get_current_user)
71
+ ) -> User:
72
+ """Ensure user is active"""
73
+ if not current_user.is_active:
74
+ raise HTTPException(
75
+ status_code=status.HTTP_400_BAD_REQUEST,
76
+ detail="Inactive user"
77
+ )
78
+ return current_user
79
+
80
+
81
+ def get_current_superuser(
82
+ current_user: User = Depends(get_current_active_user)
83
+ ) -> User:
84
+ """Ensure user is superuser"""
85
+ if not current_user.is_superuser:
86
+ raise HTTPException(
87
+ status_code=status.HTTP_403_FORBIDDEN,
88
+ detail="Not enough permissions"
89
+ )
90
+ return current_user
app/api/v1/__init__.py ADDED
File without changes
app/api/v1/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (144 Bytes). View file
 
app/api/v1/__pycache__/anpr.cpython-310.pyc ADDED
Binary file (5.47 kB). View file
 
app/api/v1/__pycache__/api.cpython-310.pyc ADDED
Binary file (1.46 kB). View file
 
app/api/v1/__pycache__/auth.cpython-310.pyc ADDED
Binary file (1.68 kB). View file
 
app/api/v1/__pycache__/chat.cpython-310.pyc ADDED
Binary file (380 Bytes). View file
 
app/api/v1/__pycache__/create_temp_user.cpython-310.pyc ADDED
Binary file (711 Bytes). View file
 
app/api/v1/__pycache__/stream.cpython-310.pyc ADDED
Binary file (701 Bytes). View file
 
app/api/v1/api.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Main API Router — combines all endpoint routers
3
+ File: app/api/v1/api.py
4
+ """
5
+
6
+ from fastapi import APIRouter
7
+
8
+ api_router = APIRouter()
9
+
10
+ _routers = [
11
+ ("app.api.v1.endpoints.auth", "/auth", ["Authentication"]),
12
+ ("app.api.v1.endpoints.users", "/users", ["Users"]),
13
+ ("app.api.v1.endpoints.clients", "/clients", ["Clients"]),
14
+ ("app.api.v1.endpoints.tickets", "/tickets", ["Tickets"]),
15
+ ("app.api.v1.endpoints.reminders", "/reminders", ["Reminders"]),
16
+ ("app.api.v1.endpoints.documents", "/documents", ["Documents"]),
17
+ ("app.api.v1.endpoints.notifications", "/notifications", ["Notifications"]),
18
+ ("app.api.v1.endpoints.financial", "/financial", ["Financial"]),
19
+ ("app.api.v1.endpoints.analytics", "/analytics", ["Analytics"]),
20
+ ("app.api.v1.endpoints.dashboard", "/dashboard", ["Dashboard"]),
21
+ ("app.api.v1.endpoints.lawyers", "/lawyers", ["Lawyers"]),
22
+ ("app.api.v1.endpoints.cases", "/cases", ["Cases"]),
23
+ ("app.api.v1.endpoints.llm", "/llm", ["AI Assistant"]),
24
+ ]
25
+
26
+ for module_path, prefix, tags in _routers:
27
+ try:
28
+ import importlib
29
+ module = importlib.import_module(module_path)
30
+ api_router.include_router(
31
+ module.router,
32
+ prefix=prefix,
33
+ tags=tags,
34
+ # redirect_slashes removed — not supported in this FastAPI version
35
+ # Handled at app level: FastAPI(redirect_slashes=False) in main.py
36
+ )
37
+ print(f" ✅ Loaded: {prefix}")
38
+ except Exception as e:
39
+ print(f" ⚠️ Skipped {prefix}: {e}")
app/api/v1/endpoints/__init__.py ADDED
File without changes
app/api/v1/endpoints/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (154 Bytes). View file
 
app/api/v1/endpoints/__pycache__/analytics.cpython-310.pyc ADDED
Binary file (5.62 kB). View file
 
app/api/v1/endpoints/__pycache__/auth.cpython-310.pyc ADDED
Binary file (4.07 kB). View file
 
app/api/v1/endpoints/__pycache__/cases.cpython-310.pyc ADDED
Binary file (6.45 kB). View file
 
app/api/v1/endpoints/__pycache__/clients.cpython-310.pyc ADDED
Binary file (4.52 kB). View file
 
app/api/v1/endpoints/__pycache__/dashboard.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
app/api/v1/endpoints/__pycache__/documents.cpython-310.pyc ADDED
Binary file (6.08 kB). View file
 
app/api/v1/endpoints/__pycache__/financial.cpython-310.pyc ADDED
Binary file (1.16 kB). View file
 
app/api/v1/endpoints/__pycache__/lawyers.cpython-310.pyc ADDED
Binary file (4.01 kB). View file
 
app/api/v1/endpoints/__pycache__/llm.cpython-310.pyc ADDED
Binary file (14 kB). View file
 
app/api/v1/endpoints/__pycache__/notifications.cpython-310.pyc ADDED
Binary file (3.26 kB). View file
 
app/api/v1/endpoints/__pycache__/reminders.cpython-310.pyc ADDED
Binary file (5.1 kB). View file
 
app/api/v1/endpoints/__pycache__/tickets.cpython-310.pyc ADDED
Binary file (7.09 kB). View file
 
app/api/v1/endpoints/__pycache__/users.cpython-310.pyc ADDED
Binary file (6.19 kB). View file
 
app/api/v1/endpoints/analytics.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analytics API endpoints"""
2
+ from typing import Any
3
+ from fastapi import APIRouter, Depends
4
+ from sqlalchemy.orm import Session
5
+ from sqlalchemy import func
6
+ from datetime import datetime, timedelta
7
+
8
+ from app.core.database import get_db
9
+ from app.core.deps import get_current_active_user # FIX: was from security
10
+ from app.models.user import User # FIX: was from app.models
11
+ from app.models.reminder import Reminder, ReminderStatus
12
+ from app.models.ticket import Ticket, TicketStatus
13
+ from app.models.client import Client # FIX: was missing
14
+
15
+ router = APIRouter()
16
+
17
+
18
+ @router.get("/dashboard")
19
+ def dashboard_analytics(db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
20
+ r = {s.value: 0 for s in ReminderStatus}
21
+ for status, cnt in db.query(Reminder.status, func.count(Reminder.id)).group_by(Reminder.status).all():
22
+ r[status.value if hasattr(status, "value") else str(status)] = cnt
23
+
24
+ t = {s.value: 0 for s in TicketStatus}
25
+ for status, cnt in db.query(Ticket.status, func.count(Ticket.id)).group_by(Ticket.status).all():
26
+ t[status.value if hasattr(status, "value") else str(status)] = cnt
27
+
28
+ # FIX: Case imported safely — only if model exists
29
+ case_total = 0
30
+ case_by_status = {}
31
+ try:
32
+ from app.models.case import Case, CaseStatus # FIX: Case in case.py not client.py
33
+ for status, cnt in db.query(Case.status, func.count(Case.id)).group_by(Case.status).all():
34
+ case_by_status[status.value if hasattr(status, "value") else str(status)] = cnt
35
+ case_total = db.query(func.count(Case.id)).scalar() or 0
36
+ except Exception:
37
+ pass
38
+
39
+ return {
40
+ "reminders": {"total": db.query(func.count(Reminder.id)).scalar() or 0, "by_status": r},
41
+ "tickets": {"total": db.query(func.count(Ticket.id)).scalar() or 0, "by_status": t},
42
+ "cases": {"total": case_total, "by_status": case_by_status},
43
+ "clients": {"total": db.query(func.count(Client.id)).scalar() or 0}, # FIX: Client now imported
44
+ "quick": {
45
+ "pending": r.get("pending", 0),
46
+ "in_progress": r.get("in_progress", 0),
47
+ "waiting": t.get("open", 0),
48
+ }
49
+ }
50
+
51
+
52
+ @router.get("/reminders/stats")
53
+ def reminder_statistics(db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
54
+ now = datetime.utcnow()
55
+ return {
56
+ "total": db.query(func.count(Reminder.id)).scalar() or 0,
57
+ "pending": db.query(func.count(Reminder.id)).filter(Reminder.status == ReminderStatus.PENDING).scalar() or 0,
58
+ "in_progress": db.query(func.count(Reminder.id)).filter(Reminder.status == ReminderStatus.IN_PROGRESS).scalar() or 0,
59
+ "completed": db.query(func.count(Reminder.id)).filter(Reminder.status == ReminderStatus.COMPLETED).scalar() or 0,
60
+ "overdue": db.query(func.count(Reminder.id)).filter(
61
+ Reminder.due_date < now,
62
+ Reminder.status.in_([ReminderStatus.PENDING, ReminderStatus.IN_PROGRESS])
63
+ ).scalar() or 0,
64
+ }
65
+
66
+
67
+ @router.get("/tickets/stats")
68
+ def ticket_statistics(db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
69
+ return {
70
+ "total": db.query(func.count(Ticket.id)).scalar() or 0,
71
+ "open": db.query(func.count(Ticket.id)).filter(Ticket.status == TicketStatus.OPEN).scalar() or 0,
72
+ "in_progress": db.query(func.count(Ticket.id)).filter(Ticket.status == TicketStatus.IN_PROGRESS).scalar() or 0,
73
+ "resolved": db.query(func.count(Ticket.id)).filter(Ticket.status == TicketStatus.RESOLVED).scalar() or 0,
74
+ "closed": db.query(func.count(Ticket.id)).filter(Ticket.status == TicketStatus.CLOSED).scalar() or 0,
75
+ }
76
+
77
+
78
+ @router.get("/cases/stats")
79
+ def case_statistics(db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
80
+ try:
81
+ from app.models.case import Case, CaseStatus # FIX: correct module
82
+ return {
83
+ "total": db.query(func.count(Case.id)).scalar() or 0,
84
+ "active": db.query(func.count(Case.id)).filter(Case.status == CaseStatus.ACTIVE).scalar() or 0,
85
+ "pending": db.query(func.count(Case.id)).filter(Case.status == CaseStatus.PENDING).scalar() or 0,
86
+ "closed": db.query(func.count(Case.id)).filter(Case.status == CaseStatus.CLOSED).scalar() or 0,
87
+ }
88
+ except Exception:
89
+ return {"total": 0, "active": 0, "pending": 0, "closed": 0}
90
+
91
+
92
+ @router.get("/activity/recent")
93
+ def recent_activity(limit: int = 10, db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
94
+ activity = []
95
+ for r in db.query(Reminder).order_by(Reminder.created_at.desc()).limit(limit).all():
96
+ activity.append({"type": "reminder", "id": r.id, "title": r.title,
97
+ "status": r.status.value if hasattr(r.status, "value") else str(r.status),
98
+ "created_at": r.created_at.isoformat() if r.created_at else ""})
99
+ for t in db.query(Ticket).order_by(Ticket.created_at.desc()).limit(limit).all():
100
+ activity.append({"type": "ticket", "id": t.id, "title": t.title,
101
+ "status": t.status.value if hasattr(t.status, "value") else str(t.status),
102
+ "created_at": t.created_at.isoformat() if t.created_at else ""})
103
+ activity.sort(key=lambda x: x["created_at"], reverse=True)
104
+ return activity[:limit]
105
+
106
+
107
+ @router.get("/trends/weekly")
108
+ def weekly_trends(db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
109
+ start = datetime.utcnow() - timedelta(days=7)
110
+ end = datetime.utcnow()
111
+ # FIX: Reminder.completed_at doesn't exist — use updated_at + status filter instead
112
+ completed = db.query(func.count(Reminder.id)).filter(
113
+ Reminder.status == ReminderStatus.COMPLETED,
114
+ Reminder.updated_at >= start # FIX: was Reminder.completed_at
115
+ ).scalar() or 0
116
+ return {
117
+ "period": "last_7_days", "start_date": start.isoformat(), "end_date": end.isoformat(),
118
+ "new_reminders": db.query(func.count(Reminder.id)).filter(Reminder.created_at >= start).scalar() or 0,
119
+ "new_tickets": db.query(func.count(Ticket.id)).filter(Ticket.created_at >= start).scalar() or 0,
120
+ "completed_reminders": completed,
121
+ }
122
+
123
+
124
+ @router.get("/performance/user/{user_id}")
125
+ def user_performance(user_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
126
+ a_r = db.query(func.count(Reminder.id)).filter(Reminder.assigned_to_id == user_id).scalar() or 0
127
+ c_r = db.query(func.count(Reminder.id)).filter(Reminder.assigned_to_id == user_id, Reminder.status == ReminderStatus.COMPLETED).scalar() or 0
128
+ a_t = db.query(func.count(Ticket.id)).filter(Ticket.assigned_to_id == user_id).scalar() or 0
129
+ r_t = db.query(func.count(Ticket.id)).filter(Ticket.assigned_to_id == user_id, Ticket.status == TicketStatus.RESOLVED).scalar() or 0
130
+ return {
131
+ "user_id": user_id,
132
+ "reminders": {"assigned": a_r, "completed": c_r, "completion_rate": round(c_r/a_r*100,1) if a_r else 0},
133
+ "tickets": {"assigned": a_t, "resolved": r_t, "resolution_rate": round(r_t/a_t*100,1) if a_t else 0},
134
+ }
app/api/v1/endpoints/auth.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Auth endpoints - Creates BOTH User AND Client on registration"""
2
+ from datetime import timedelta
3
+ from typing import Any
4
+ from fastapi import APIRouter, Depends, HTTPException, status, Response
5
+ from fastapi.security import OAuth2PasswordRequestForm
6
+ from sqlalchemy.orm import Session
7
+ from pydantic import BaseModel, EmailStr
8
+
9
+ from app.core.database import get_db
10
+ from app.core.security import create_access_token, get_password_hash, verify_password
11
+ from app.core.config import settings
12
+ from app.core.deps import get_current_active_user
13
+ from app.models.user import User, UserRole
14
+ from app.models.client import Client
15
+
16
+ router = APIRouter()
17
+
18
+
19
+ class Token(BaseModel):
20
+ access_token: str
21
+ token_type: str
22
+
23
+
24
+ class UserRegisterIn(BaseModel):
25
+ email: EmailStr
26
+ password: str
27
+ full_name: str
28
+ full_name_ar: str = None
29
+ phone: str = None
30
+
31
+
32
+ @router.post("/login", response_model=Token)
33
+ def login(
34
+ response: Response,
35
+ form_data: OAuth2PasswordRequestForm = Depends(),
36
+ db: Session = Depends(get_db)
37
+ ) -> Any:
38
+ """Login - returns token AND sets cookie"""
39
+ user = db.query(User).filter(User.email == form_data.username).first()
40
+ if not user or not verify_password(form_data.password, user.hashed_password):
41
+ raise HTTPException(
42
+ status_code=status.HTTP_401_UNAUTHORIZED,
43
+ detail="Incorrect email or password",
44
+ headers={"WWW-Authenticate": "Bearer"},
45
+ )
46
+ if not user.is_active:
47
+ raise HTTPException(
48
+ status_code=status.HTTP_400_BAD_REQUEST,
49
+ detail="Inactive user"
50
+ )
51
+
52
+ access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
53
+ access_token = create_access_token(
54
+ data={"sub": str(user.id)}, expires_delta=access_token_expires
55
+ )
56
+
57
+ # Set cookie for iframe/img authentication
58
+ response.set_cookie(
59
+ key="access_token",
60
+ value=access_token,
61
+ httponly=True,
62
+ max_age=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
63
+ samesite="lax"
64
+ )
65
+
66
+ return {"access_token": access_token, "token_type": "bearer"}
67
+
68
+
69
+ @router.post("/register", status_code=201)
70
+ def register(user_in: UserRegisterIn, db: Session = Depends(get_db)) -> Any:
71
+ """
72
+ Register new user - Creates BOTH:
73
+ 1. User record (for login)
74
+ 2. Client record (for clients list)
75
+ """
76
+ # Check if email already exists
77
+ if db.query(User).filter(User.email == user_in.email).first():
78
+ raise HTTPException(
79
+ status_code=status.HTTP_409_CONFLICT,
80
+ detail="Email already registered"
81
+ )
82
+
83
+ try:
84
+ # 1. Create User (for login)
85
+ user = User(
86
+ email=user_in.email,
87
+ full_name=user_in.full_name,
88
+ full_name_ar=user_in.full_name_ar,
89
+ phone=user_in.phone,
90
+ hashed_password=get_password_hash(user_in.password),
91
+ role=UserRole.CLIENT,
92
+ is_active=True
93
+ )
94
+ db.add(user)
95
+ db.flush() # Get user.id without committing
96
+
97
+ # 2. Create Client (for clients list)
98
+ client = Client(
99
+ full_name=user_in.full_name,
100
+ full_name_ar=user_in.full_name_ar,
101
+ email=user_in.email,
102
+ phone=user_in.phone,
103
+ is_active=True,
104
+ notes=f"Registered via portal (User ID: {user.id})"
105
+ )
106
+ db.add(client)
107
+
108
+ db.commit()
109
+ db.refresh(user)
110
+
111
+ return {
112
+ "id": user.id,
113
+ "email": user.email,
114
+ "message": "User and client created successfully"
115
+ }
116
+
117
+ except Exception as e:
118
+ db.rollback()
119
+ raise HTTPException(
120
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
121
+ detail=f"Registration failed: {str(e)}"
122
+ )
123
+
124
+
125
+ @router.get("/me")
126
+ def get_me(current_user: User = Depends(get_current_active_user)) -> Any:
127
+ """Get current user info"""
128
+ return {
129
+ "id": current_user.id,
130
+ "email": current_user.email,
131
+ "full_name": current_user.full_name,
132
+ "full_name_ar": current_user.full_name_ar,
133
+ "phone": current_user.phone,
134
+ "role": current_user.role.value if hasattr(current_user.role, "value") else str(current_user.role),
135
+ "is_active": current_user.is_active,
136
+ "is_superuser": current_user.is_superuser
137
+ }
138
+
139
+
140
+ @router.post("/logout")
141
+ def logout(response: Response) -> Any:
142
+ """Logout - clear cookie"""
143
+ response.delete_cookie(key="access_token")
144
+ return {"message": "Successfully logged out"}
app/api/v1/endpoints/cases.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cases API endpoints"""
2
+ from typing import Any, Optional
3
+ from fastapi import APIRouter, Depends, HTTPException, status
4
+ from sqlalchemy.orm import Session
5
+ from sqlalchemy.exc import IntegrityError
6
+ from datetime import datetime
7
+ from pydantic import BaseModel
8
+
9
+ from app.core.database import get_db
10
+ from app.core.deps import get_current_active_user
11
+ from app.models.user import User
12
+ from app.models.case import Case, CaseStatus, CaseType
13
+
14
+ router = APIRouter()
15
+
16
+
17
+ class CaseIn(BaseModel):
18
+ case_number: Optional[str] = None
19
+ title: str
20
+ title_ar: Optional[str] = None
21
+ description: Optional[str] = None
22
+ case_type: Optional[str] = "civil"
23
+ status: Optional[str] = "pending"
24
+ client_id: Optional[int] = None
25
+ lawyer_id: Optional[int] = None
26
+ court_name: Optional[str] = None
27
+ judge_name: Optional[str] = None
28
+ filing_date: Optional[str] = None
29
+ next_hearing_date: Optional[str] = None
30
+ estimated_value: Optional[float] = None
31
+ priority: Optional[str] = "normal"
32
+ notes: Optional[str] = None
33
+ is_confidential: bool = False
34
+
35
+
36
+ def _parse_date(val):
37
+ if not val:
38
+ return None
39
+ try:
40
+ return datetime.fromisoformat(str(val))
41
+ except Exception:
42
+ try:
43
+ return datetime.strptime(str(val), "%Y-%m-%d")
44
+ except Exception:
45
+ return None
46
+
47
+
48
+ def _d(c: Case) -> dict:
49
+ return {k: (v.value if hasattr(v, "value") else (str(v) if hasattr(v, "isoformat") else v))
50
+ for k, v in c.__dict__.items() if not k.startswith("_")}
51
+
52
+
53
+ def _next_case_number(db: Session) -> str:
54
+ last = db.query(Case).order_by(Case.id.desc()).first()
55
+ num = (last.id + 1) if last else 1
56
+ return f"CASE-{num:06d}"
57
+
58
+
59
+ @router.get("")
60
+ def list_cases(
61
+ skip: int = 0,
62
+ limit: int = 50,
63
+ client_id: Optional[int] = None,
64
+ lawyer_id: Optional[int] = None,
65
+ status_filter: Optional[str] = None,
66
+ db: Session = Depends(get_db),
67
+ current_user: User = Depends(get_current_active_user)
68
+ ) -> Any:
69
+ q = db.query(Case)
70
+ if client_id:
71
+ q = q.filter(Case.client_id == client_id)
72
+ if lawyer_id:
73
+ q = q.filter(Case.lawyer_id == lawyer_id)
74
+ if status_filter:
75
+ try:
76
+ q = q.filter(Case.status == CaseStatus(status_filter))
77
+ except ValueError:
78
+ pass
79
+ cases = q.order_by(Case.created_at.desc()).offset(skip).limit(limit).all()
80
+ return {"total": db.query(Case).count(), "cases": [_d(c) for c in cases]}
81
+
82
+
83
+ @router.post("", status_code=201)
84
+ def create_case(
85
+ case_in: CaseIn,
86
+ db: Session = Depends(get_db),
87
+ current_user: User = Depends(get_current_active_user)
88
+ ) -> Any:
89
+ try:
90
+ case_type = CaseType(case_in.case_type or "civil")
91
+ except ValueError:
92
+ case_type = CaseType.CIVIL
93
+ try:
94
+ case_status = CaseStatus(case_in.status or "pending")
95
+ except ValueError:
96
+ case_status = CaseStatus.PENDING
97
+
98
+ try:
99
+ case = Case(
100
+ case_number=case_in.case_number or _next_case_number(db),
101
+ title=case_in.title,
102
+ title_ar=case_in.title_ar,
103
+ description=case_in.description,
104
+ case_type=case_type,
105
+ status=case_status,
106
+ client_id=case_in.client_id,
107
+ lawyer_id=case_in.lawyer_id,
108
+ court_name=case_in.court_name,
109
+ judge_name=case_in.judge_name,
110
+ filing_date=_parse_date(case_in.filing_date),
111
+ next_hearing_date=_parse_date(case_in.next_hearing_date),
112
+ estimated_value=case_in.estimated_value,
113
+ priority=case_in.priority or "normal",
114
+ notes=case_in.notes,
115
+ is_confidential=case_in.is_confidential,
116
+ )
117
+ db.add(case)
118
+ db.commit()
119
+ db.refresh(case)
120
+ return _d(case)
121
+ except Exception as e:
122
+ db.rollback()
123
+ raise HTTPException(500, detail=str(e))
124
+
125
+
126
+ @router.get("/{case_id}")
127
+ def get_case(
128
+ case_id: int,
129
+ db: Session = Depends(get_db),
130
+ current_user: User = Depends(get_current_active_user)
131
+ ) -> Any:
132
+ case = db.query(Case).filter(Case.id == case_id).first()
133
+ if not case:
134
+ raise HTTPException(404, "القضية غير موجودة")
135
+ result = _d(case)
136
+ # Include hearings
137
+ try:
138
+ from app.models.case import Hearing
139
+ result["hearings"] = [
140
+ {"id": h.id, "title": h.title, "hearing_date": str(h.hearing_date),
141
+ "status": h.status.value if hasattr(h.status, "value") else str(h.status),
142
+ "location": h.location}
143
+ for h in db.query(Hearing).filter(Hearing.case_id == case_id).order_by(Hearing.hearing_date).all()
144
+ ]
145
+ except Exception:
146
+ result["hearings"] = []
147
+ return result
148
+
149
+
150
+ @router.put("/{case_id}")
151
+ def update_case(
152
+ case_id: int,
153
+ case_in: CaseIn,
154
+ db: Session = Depends(get_db),
155
+ current_user: User = Depends(get_current_active_user)
156
+ ) -> Any:
157
+ case = db.query(Case).filter(Case.id == case_id).first()
158
+ if not case:
159
+ raise HTTPException(404, "القضية غير موجودة")
160
+ try:
161
+ for k, v in case_in.model_dump(exclude_unset=True).items():
162
+ if k == "case_type":
163
+ try: setattr(case, k, CaseType(v))
164
+ except: pass
165
+ elif k == "status":
166
+ try: setattr(case, k, CaseStatus(v))
167
+ except: pass
168
+ elif k in ("filing_date", "next_hearing_date"):
169
+ setattr(case, k, _parse_date(v))
170
+ else:
171
+ setattr(case, k, v)
172
+ db.commit()
173
+ db.refresh(case)
174
+ return _d(case)
175
+ except Exception as e:
176
+ db.rollback()
177
+ raise HTTPException(500, detail=str(e))
178
+
179
+
180
+ @router.post("/{case_id}/close")
181
+ def close_case(
182
+ case_id: int,
183
+ db: Session = Depends(get_db),
184
+ current_user: User = Depends(get_current_active_user)
185
+ ) -> Any:
186
+ case = db.query(Case).filter(Case.id == case_id).first()
187
+ if not case:
188
+ raise HTTPException(404, "القضية غير موجودة")
189
+ case.status = CaseStatus.CLOSED
190
+ db.commit()
191
+ return {"message": "تم إغلاق القضية", "id": case_id}
192
+
193
+
194
+ @router.delete("/{case_id}")
195
+ def delete_case(
196
+ case_id: int,
197
+ db: Session = Depends(get_db),
198
+ current_user: User = Depends(get_current_active_user)
199
+ ) -> Any:
200
+ case = db.query(Case).filter(Case.id == case_id).first()
201
+ if not case:
202
+ raise HTTPException(404, "القضية غير موجودة")
203
+ db.delete(case)
204
+ db.commit()
205
+ return {"message": "تم حذف القضية", "id": case_id}
app/api/v1/endpoints/clients.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Clients API - Shows ALL from Client table (not User table)"""
2
+ from typing import Any, Optional
3
+ from fastapi import APIRouter, Depends, HTTPException
4
+ from sqlalchemy.orm import Session
5
+ from sqlalchemy.exc import IntegrityError
6
+ from pydantic import BaseModel
7
+
8
+ from app.core.database import get_db
9
+ from app.core.deps import get_current_active_user
10
+ from app.models.user import User
11
+ from app.models.client import Client
12
+
13
+ router = APIRouter()
14
+
15
+
16
+ class ClientIn(BaseModel):
17
+ full_name: str
18
+ full_name_ar: Optional[str] = None
19
+ email: Optional[str] = None
20
+ phone: Optional[str] = None
21
+ phone_secondary: Optional[str] = None
22
+ national_id: Optional[str] = None
23
+ passport_number: Optional[str] = None
24
+ address: Optional[str] = None
25
+ city: Optional[str] = None
26
+ country: Optional[str] = "Saudi Arabia"
27
+ company_name: Optional[str] = None
28
+ company_name_ar: Optional[str] = None
29
+ company_registration: Optional[str] = None
30
+ notes: Optional[str] = None
31
+ notes_ar: Optional[str] = None
32
+ is_active: bool = True
33
+
34
+
35
+ def _d(c: Client) -> dict:
36
+ return {k: (str(v) if hasattr(v, "isoformat") else v)
37
+ for k, v in c.__dict__.items() if not k.startswith("_")}
38
+
39
+
40
+ @router.get("")
41
+ def list_clients(skip: int = 0, limit: int = 100, search: Optional[str] = None,
42
+ db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
43
+ """
44
+ List ALL clients from Client table
45
+ NOTE: This is SEPARATE from users with role=client
46
+ """
47
+ q = db.query(Client)
48
+
49
+ if search:
50
+ q = q.filter(
51
+ (Client.full_name.contains(search)) |
52
+ (Client.full_name_ar.contains(search)) |
53
+ (Client.email.contains(search)) |
54
+ (Client.phone.contains(search))
55
+ )
56
+
57
+ total = q.count()
58
+ clients = q.order_by(Client.created_at.desc()).offset(skip).limit(limit).all()
59
+
60
+ return {"total": total, "clients": [_d(c) for c in clients]}
61
+
62
+
63
+ @router.post("", status_code=201)
64
+ def create_client(client_in: ClientIn, db: Session = Depends(get_db),
65
+ current_user: User = Depends(get_current_active_user)) -> Any:
66
+ if client_in.email:
67
+ if db.query(Client).filter(Client.email == client_in.email).first():
68
+ raise HTTPException(409, detail=f"البريد {client_in.email} مسجل بالفعل")
69
+
70
+ try:
71
+ client = Client(**client_in.model_dump())
72
+ db.add(client); db.commit(); db.refresh(client)
73
+ return _d(client)
74
+ except IntegrityError:
75
+ db.rollback(); raise HTTPException(409, "بيانات مكررة")
76
+ except Exception as e:
77
+ db.rollback(); raise HTTPException(500, str(e))
78
+
79
+
80
+ @router.get("/{client_id}")
81
+ def get_client(client_id: int, db: Session = Depends(get_db),
82
+ current_user: User = Depends(get_current_active_user)) -> Any:
83
+ c = db.query(Client).filter(Client.id == client_id).first()
84
+ if not c: raise HTTPException(404, "العميل غير موجود")
85
+ return _d(c)
86
+
87
+
88
+ @router.put("/{client_id}")
89
+ def update_client(client_id: int, client_in: ClientIn, db: Session = Depends(get_db),
90
+ current_user: User = Depends(get_current_active_user)) -> Any:
91
+ c = db.query(Client).filter(Client.id == client_id).first()
92
+ if not c: raise HTTPException(404, "العميل غير موجود")
93
+
94
+ if client_in.email and client_in.email != c.email:
95
+ if db.query(Client).filter(Client.email == client_in.email, Client.id != client_id).first():
96
+ raise HTTPException(409, "البريد مسجل بالفعل")
97
+
98
+ try:
99
+ for k, v in client_in.model_dump(exclude_unset=True).items():
100
+ setattr(c, k, v)
101
+ db.commit(); db.refresh(c)
102
+ return _d(c)
103
+ except Exception as e:
104
+ db.rollback(); raise HTTPException(500, str(e))
105
+
106
+
107
+ @router.delete("/{client_id}")
108
+ def delete_client(client_id: int, db: Session = Depends(get_db),
109
+ current_user: User = Depends(get_current_active_user)) -> Any:
110
+ c = db.query(Client).filter(Client.id == client_id).first()
111
+ if not c: raise HTTPException(404, "العميل غير موجود")
112
+ db.delete(c); db.commit()
113
+ return {"message": "تم الحذف", "id": client_id}
app/api/v1/endpoints/dashboard.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dashboard API - FIXED"""
2
+ from typing import Any
3
+ from fastapi import APIRouter, Depends
4
+ from sqlalchemy.orm import Session
5
+
6
+ from app.core.database import get_db
7
+ from app.core.deps import get_current_active_user
8
+ from app.models.user import User, UserRole
9
+ from app.models.ticket import Ticket, TicketStatus
10
+
11
+ router = APIRouter()
12
+
13
+
14
+ @router.get("")
15
+ def get_dashboard_stats(db: Session = Depends(get_db),
16
+ current_user: User = Depends(get_current_active_user)) -> Any:
17
+ """Dashboard stats - uses TICKETS not reminders"""
18
+
19
+ if current_user.is_superuser:
20
+ pending = db.query(Ticket).filter(Ticket.status == TicketStatus.PENDING).count()
21
+ in_progress = db.query(Ticket).filter(Ticket.status == TicketStatus.IN_PROGRESS).count()
22
+ open_tickets = db.query(Ticket).filter(Ticket.status == TicketStatus.OPEN).count()
23
+ total_clients = db.query(User).filter(User.role == UserRole.CLIENT).count()
24
+ else:
25
+ pending = db.query(Ticket).filter(
26
+ Ticket.status == TicketStatus.PENDING,
27
+ (Ticket.created_by_id == current_user.id) | (Ticket.assigned_to_id == current_user.id)
28
+ ).count()
29
+ in_progress = db.query(Ticket).filter(
30
+ Ticket.status == TicketStatus.IN_PROGRESS,
31
+ (Ticket.created_by_id == current_user.id) | (Ticket.assigned_to_id == current_user.id)
32
+ ).count()
33
+ open_tickets = db.query(Ticket).filter(
34
+ Ticket.status == TicketStatus.OPEN,
35
+ (Ticket.created_by_id == current_user.id) | (Ticket.assigned_to_id == current_user.id)
36
+ ).count()
37
+ total_clients = db.query(User).filter(User.role == UserRole.CLIENT).count()
38
+
39
+ return {
40
+ "pending": pending,
41
+ "in_progress": in_progress,
42
+ "waiting": open_tickets,
43
+ "assigned": in_progress,
44
+ "total_clients": total_clients
45
+ }
app/api/v1/endpoints/documents.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Documents API - Fixed PDF download"""
2
+ import os, uuid
3
+ from typing import Any, Optional
4
+ from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, Request
5
+ from fastapi.responses import FileResponse, Response
6
+ from sqlalchemy.orm import Session
7
+
8
+ from app.core.database import get_db
9
+ from app.core.deps import get_current_active_user
10
+ from app.models.user import User, UserRole
11
+ from app.models.document import Document, DocumentStatus
12
+
13
+ router = APIRouter()
14
+ UPLOAD_DIR = "uploads/documents"
15
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
16
+ ALLOWED = {".pdf",".doc",".docx",".txt",".jpg",".jpeg",".png",".xlsx",".xls"}
17
+
18
+
19
+ def _int_or_none(val) -> Optional[int]:
20
+ if val is None or str(val).strip() == "":
21
+ return None
22
+ try:
23
+ return int(val)
24
+ except (ValueError, TypeError):
25
+ return None
26
+
27
+ def _d(doc: Document, db: Session) -> dict:
28
+ """Convert document to dict WITH uploader info"""
29
+ result = {k: (v.value if hasattr(v, "value") else (str(v) if hasattr(v, "isoformat") else v))
30
+ for k, v in doc.__dict__.items() if not k.startswith("_")}
31
+
32
+ uploader = db.query(User).filter(User.id == doc.uploaded_by_id).first()
33
+ result["owner_name"] = uploader.full_name_ar or uploader.full_name if uploader else "غير معروف"
34
+
35
+ if not result.get("file_extension") and doc.file_name:
36
+ result["file_extension"] = os.path.splitext(doc.file_name)[1].lower()
37
+
38
+ return result
39
+
40
+ @router.get("")
41
+ def list_documents(db: Session = Depends(get_db),
42
+ current_user: User = Depends(get_current_active_user)) -> Any:
43
+ query = db.query(Document)
44
+ if current_user.role == UserRole.CLIENT:
45
+ query = query.filter(Document.uploaded_by_id == current_user.id)
46
+
47
+ docs = query.order_by(Document.created_at.desc()).all()
48
+ return {"documents": [_d(d, db) for d in docs]}
49
+
50
+
51
+ @router.post("/upload", status_code=201)
52
+ async def upload_document(
53
+ file: UploadFile = File(...), title: str = Form(...), description: str = Form(""),
54
+ document_type: str = Form("other"), client_id: Optional[str] = Form(None),
55
+ case_id: Optional[str] = Form(None), is_confidential: Optional[str] = Form("false"),
56
+ db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)
57
+ ) -> Any:
58
+ client_id_int = _int_or_none(client_id)
59
+ case_id_int = _int_or_none(case_id)
60
+ confidential = str(is_confidential).lower() in ("true", "1", "yes", "on")
61
+
62
+ ext = os.path.splitext(file.filename or "")[1].lower()
63
+ if ext not in ALLOWED:
64
+ raise HTTPException(400, detail=f"نوع الملف غير مدعوم")
65
+
66
+ content = await file.read()
67
+ if len(content) > 50 * 1024 * 1024:
68
+ raise HTTPException(413, detail="حجم الملف أكبر من 50MB")
69
+
70
+ unique_name = f"{uuid.uuid4()}{ext}"
71
+ file_path = os.path.join(UPLOAD_DIR, unique_name)
72
+ with open(file_path, "wb") as f:
73
+ f.write(content)
74
+
75
+ try:
76
+ doc = Document(
77
+ title=title, description=description or None, document_type=document_type,
78
+ file_name=file.filename, file_path=file_path, file_size=len(content),
79
+ file_extension=ext, client_id=client_id_int, case_id=case_id_int,
80
+ is_confidential=confidential, uploaded_by_id=current_user.id,
81
+ status=DocumentStatus.APPROVED,
82
+ )
83
+ db.add(doc); db.commit(); db.refresh(doc)
84
+ return _d(doc, db)
85
+ except Exception as e:
86
+ if os.path.exists(file_path):
87
+ os.remove(file_path)
88
+ db.rollback()
89
+ raise HTTPException(500, detail=f"خطأ: {str(e)}")
90
+
91
+
92
+ @router.get("/{doc_id}")
93
+ def get_document(doc_id: int, db: Session = Depends(get_db),
94
+ current_user: User = Depends(get_current_active_user)) -> Any:
95
+ doc = db.query(Document).filter(Document.id == doc_id).first()
96
+ if not doc:
97
+ raise HTTPException(404, "المستند غير موجود")
98
+
99
+ if current_user.role == UserRole.CLIENT:
100
+ if doc.uploaded_by_id != current_user.id:
101
+ raise HTTPException(403, "غير مصرح")
102
+
103
+ return _d(doc, db)
104
+
105
+
106
+ @router.get("/{doc_id}/download")
107
+ async def download_document(doc_id: int, request: Request, db: Session = Depends(get_db),
108
+ current_user: User = Depends(get_current_active_user)) -> Any:
109
+ """
110
+ Download document - returns raw bytes for blob consumption
111
+ FIX: Proper content type and headers for PDFs
112
+ """
113
+ doc = db.query(Document).filter(Document.id == doc_id).first()
114
+ if not doc:
115
+ raise HTTPException(404, "المستند غير موجود")
116
+
117
+ if current_user.role == UserRole.CLIENT:
118
+ if doc.uploaded_by_id != current_user.id:
119
+ raise HTTPException(403, "غير مصرح")
120
+
121
+ if not os.path.exists(doc.file_path):
122
+ raise HTTPException(404, "الملف غير موجود")
123
+
124
+ # Determine MIME type
125
+ ext = doc.file_extension.lower() if doc.file_extension else ''
126
+ mime_types = {
127
+ '.pdf': 'application/pdf',
128
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
129
+ '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp',
130
+ '.txt': 'text/plain', '.md': 'text/markdown',
131
+ '.doc': 'application/msword',
132
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
133
+ '.xls': 'application/vnd.ms-excel',
134
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
135
+ }
136
+ media_type = mime_types.get(ext, 'application/octet-stream')
137
+
138
+ # Read file content
139
+ with open(doc.file_path, 'rb') as f:
140
+ content = f.read()
141
+
142
+ # Return with proper headers for blob consumption
143
+ return Response(
144
+ content=content,
145
+ media_type=media_type,
146
+ headers={
147
+ 'Content-Disposition': f'inline; filename="{doc.file_name}"',
148
+ 'Cache-Control': 'no-cache'
149
+ }
150
+ )
151
+
152
+
153
+ @router.delete("/{doc_id}")
154
+ def delete_document(doc_id: int, db: Session = Depends(get_db),
155
+ current_user: User = Depends(get_current_active_user)) -> Any:
156
+ doc = db.query(Document).filter(Document.id == doc_id).first()
157
+ if not doc:
158
+ raise HTTPException(404, "المستند غير موجود")
159
+
160
+ if not current_user.is_superuser and doc.uploaded_by_id != current_user.id:
161
+ raise HTTPException(403, "فقط من رفع الملف يمكنه حذفه")
162
+
163
+ if os.path.exists(doc.file_path):
164
+ os.remove(doc.file_path)
165
+ db.delete(doc); db.commit()
166
+ return {"message": "تم الحذف", "id": doc_id}
app/api/v1/endpoints/financial.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Financial API endpoints - Placeholder"""
2
+ from typing import Any
3
+ from fastapi import APIRouter, Depends
4
+ from sqlalchemy.orm import Session
5
+
6
+ from app.core.database import get_db
7
+ from app.core.deps import get_current_active_user
8
+ from app.models.user import User
9
+
10
+ router = APIRouter()
11
+
12
+
13
+ @router.get("/overview")
14
+ def get_financial_overview(db: Session = Depends(get_db),
15
+ current_user: User = Depends(get_current_active_user)) -> Any:
16
+ return {"total_revenue": 0, "pending_payments": 0, "paid_invoices": 0}
17
+
18
+
19
+ @router.get("/invoices")
20
+ def list_invoices(db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
21
+ return {"total": 0, "invoices": []}
22
+
23
+
24
+ @router.get("/payments")
25
+ def list_payments(db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
26
+ return {"total": 0, "payments": []}
app/api/v1/endpoints/lawyers.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lawyers API endpoints"""
2
+ from typing import Any
3
+ from fastapi import APIRouter, Depends, HTTPException
4
+ from sqlalchemy.orm import Session
5
+ from pydantic import BaseModel
6
+
7
+ from app.core.database import get_db
8
+ from app.core.deps import get_current_active_user # FIX: was from security
9
+ from app.models.user import User, UserRole # FIX: was from app.models
10
+
11
+ router = APIRouter()
12
+
13
+
14
+ class LawyerUpdateIn(BaseModel):
15
+ full_name: str = None
16
+ full_name_ar: str = None
17
+ phone: str = None
18
+ license_number: str = None
19
+ specialization: str = None
20
+ bio: str = None
21
+
22
+
23
+ def _d(u: User) -> dict:
24
+ return {"id": u.id, "email": u.email, "full_name": u.full_name,
25
+ "full_name_ar": u.full_name_ar, "phone": u.phone,
26
+ "license_number": u.license_number, "specialization": u.specialization,
27
+ "bio": u.bio, "is_active": u.is_active, "created_at": str(u.created_at)}
28
+
29
+
30
+ @router.get("") # FIX: no trailing slash
31
+ def list_lawyers(skip: int = 0, limit: int = 100, db: Session = Depends(get_db),
32
+ current_user: User = Depends(get_current_active_user)) -> Any:
33
+ lawyers = db.query(User).filter(User.role == UserRole.LAWYER).offset(skip).limit(limit).all()
34
+ return {"total": len(lawyers), "lawyers": [_d(l) for l in lawyers]}
35
+
36
+
37
+ @router.get("/{lawyer_id}")
38
+ def get_lawyer(lawyer_id: int, db: Session = Depends(get_db),
39
+ current_user: User = Depends(get_current_active_user)) -> Any:
40
+ l = db.query(User).filter(User.id == lawyer_id, User.role == UserRole.LAWYER).first()
41
+ if not l: raise HTTPException(404, "المحامي غير موجود")
42
+ return _d(l)
43
+
44
+
45
+ @router.put("/{lawyer_id}") # FIX: was "/{id}" with trailing slash, raw dict
46
+ def update_lawyer(lawyer_id: int, lawyer_in: LawyerUpdateIn, db: Session = Depends(get_db),
47
+ current_user: User = Depends(get_current_active_user)) -> Any:
48
+ l = db.query(User).filter(User.id == lawyer_id, User.role == UserRole.LAWYER).first()
49
+ if not l: raise HTTPException(404, "المحامي غير موجود")
50
+ for k, v in lawyer_in.model_dump(exclude_unset=True, exclude_none=True).items():
51
+ setattr(l, k, v)
52
+ db.commit(); db.refresh(l)
53
+ return _d(l)
54
+
55
+
56
+ @router.get("/{lawyer_id}/cases")
57
+ def get_lawyer_cases(lawyer_id: int, db: Session = Depends(get_db),
58
+ current_user: User = Depends(get_current_active_user)) -> Any:
59
+ l = db.query(User).filter(User.id == lawyer_id, User.role == UserRole.LAWYER).first()
60
+ if not l: raise HTTPException(404, "المحامي غير موجود")
61
+ try:
62
+ from app.models.case import Case # FIX: Case from case.py not client.py
63
+ cases = db.query(Case).filter(Case.lawyer_id == lawyer_id).all()
64
+ return [{"id": c.id, "case_number": c.case_number, "title": c.title,
65
+ "status": c.status.value if hasattr(c.status, "value") else str(c.status)}
66
+ for c in cases]
67
+ except Exception:
68
+ return []
69
+
70
+
71
+ @router.get("/{lawyer_id}/statistics")
72
+ def lawyer_statistics(lawyer_id: int, db: Session = Depends(get_db),
73
+ current_user: User = Depends(get_current_active_user)) -> Any:
74
+ l = db.query(User).filter(User.id == lawyer_id, User.role == UserRole.LAWYER).first()
75
+ if not l: raise HTTPException(404, "المحامي غير موجود")
76
+ try:
77
+ from app.models.case import Case, CaseStatus # FIX: correct module
78
+ total = db.query(Case).filter(Case.lawyer_id == lawyer_id).count()
79
+ active = db.query(Case).filter(Case.lawyer_id == lawyer_id, Case.status == CaseStatus.ACTIVE).count()
80
+ closed = db.query(Case).filter(Case.lawyer_id == lawyer_id, Case.status == CaseStatus.CLOSED).count()
81
+ except Exception:
82
+ total, active, closed = 0, 0, 0
83
+ return {"lawyer_id": lawyer_id, "lawyer_name": l.full_name,
84
+ "total_cases": total, "active_cases": active, "closed_cases": closed}
app/api/v1/endpoints/llm - original.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ llm.py — Saudi Law RAG · Query & Answer Endpoint
3
+ ====================================================
4
+ Optimizations applied:
5
+ 1. Sliding Window History — last 3 turns full, older → 150-token summary
6
+ 2. Prompt Compression — lean system prompt injected per-request
7
+ 3. Semantic Cache — vector similarity ≥ 0.85 → skip the model entirely
8
+ 4. Smart Router — lightweight classifier decides local vs fallback
9
+ 5. Memory stability — Embedding/Reranker on CPU, Ollama on GPU
10
+ 6. Hot-swap provider — live .env reload between requests
11
+ """
12
+
13
+ import os
14
+ import re
15
+ import time
16
+ import logging
17
+ import threading
18
+ import traceback
19
+ import gc
20
+ from typing import List, Optional, Tuple
21
+ from dataclasses import dataclass, field
22
+
23
+ import numpy as np
24
+ from fastapi import APIRouter, HTTPException, Query
25
+ from pydantic import BaseModel
26
+ from qdrant_client import QdrantClient
27
+ from sentence_transformers import SentenceTransformer, CrossEncoder
28
+ from dotenv import load_dotenv
29
+
30
+ load_dotenv(override=True)
31
+ logger = logging.getLogger("app.api.v1.endpoints.llm")
32
+
33
+ # ══════════════════════════════════════════════════════════════════════════════
34
+ # Config
35
+ # ══════════════════════════════════════════════════════════════════════════════
36
+
37
+ COLLECTION_NAME = "saudi_law_data"
38
+ QDRANT_HOST = os.getenv("QDRANT_HOST", "localhost")
39
+ QDRANT_PORT = int(os.getenv("QDRANT_PORT", "6333"))
40
+ PRIMARY_EMBED = os.getenv("PRIMARY_EMBED", "Omartificial-Intelligence-Space/Arabic-Triplet-Matryoshka-V2")
41
+ RERANKER_MODEL = os.getenv("RERANKER_MODEL", "Omartificial-Intelligence-Space/ARA-Reranker-V1")
42
+
43
+ # ── Optimization knobs ────────────────────────────────────────────────────────
44
+ CACHE_SIMILARITY_THRESHOLD = float(os.getenv("CACHE_SIMILARITY_THRESHOLD", "0.85"))
45
+ HISTORY_FULL_TURNS = int(os.getenv("HISTORY_FULL_TURNS", "3")) # turns kept verbatim
46
+ HISTORY_SUMMARY_TOKENS = int(os.getenv("HISTORY_SUMMARY_TOKENS", "150"))
47
+ ROUTING_COMPLEX_THRESHOLD = float(os.getenv("ROUTING_COMPLEX_THRESHOLD", "0.7"))
48
+
49
+ # Compressed system prompt (was 2,800 tokens — now ~120 tokens)
50
+ SYSTEM_PROMPT = (
51
+ "أنت مساعد قانوني سعودي متخصص. "
52
+ "أجب بناءً على السياق المرفق فقط. "
53
+ "إذا لم يكن الجواب في السياق، قل ذلك صراحةً. "
54
+ "أجب بإيجاز ودقة."
55
+ )
56
+
57
+ # ══════════════════════════════════════════════════════════════════════════════
58
+ # Language Sanitizer — strips non-Arabic foreign text from model output
59
+ # ══════════════════════════════════════════════════════════════════════════════
60
+
61
+ # Unicode ranges that are NOT Arabic/Latin punctuation/numbers → foreign script
62
+ _FOREIGN_SCRIPT_RE = re.compile(
63
+ r"["
64
+ r"一-鿿" # CJK Unified (Chinese/Japanese/Korean)
65
+ r" -〿" # CJK Symbols & Punctuation
66
+ r"぀-ゟ" # Hiragana
67
+ r"゠-ヿ" # Katakana
68
+ r"가-힯" # Korean Hangul
69
+ r"Ѐ-ӿ" # Cyrillic
70
+ r"ऀ-ॿ" # Devanagari
71
+ r"]+"
72
+ )
73
+
74
+ def sanitize_arabic(text: str) -> str:
75
+ """
76
+ Remove any sentence/segment that contains foreign-script characters.
77
+ Keeps Arabic, English (for legal terms), numbers, and punctuation.
78
+ Logs a warning whenever it strips something so you can monitor the model.
79
+ """
80
+ # Split on Arabic sentence boundaries and newlines
81
+ segments = re.split(r"(\n+|[،؛\.!?]+)", text)
82
+ clean = []
83
+ removed = []
84
+ for seg in segments:
85
+ if _FOREIGN_SCRIPT_RE.search(seg):
86
+ removed.append(seg.strip())
87
+ else:
88
+ clean.append(seg)
89
+ if removed:
90
+ logger.warning(f"[Sanitizer] Stripped foreign-script segments: {removed}")
91
+ result = "".join(clean).strip()
92
+ # Collapse multiple blank lines left after removal
93
+ result = re.sub(r"\n{3,}", "\n\n", result)
94
+ return result if result else "عذراً، لم أتمكن من توليد إجابة واضحة. يرجى إعادة صياغة السؤال."
95
+
96
+
97
+ # ══════════════════════════════════════════════════════════════════════════════
98
+ # Semantic Cache
99
+ # ═════════���════════════════════════════════════════════════════════════════════
100
+
101
+ @dataclass
102
+ class _CacheEntry:
103
+ query_vec: np.ndarray
104
+ answer: str
105
+ sources: List[dict]
106
+ provider: str
107
+ ts: float = field(default_factory=time.time)
108
+
109
+ class SemanticCache:
110
+ """
111
+ In-memory semantic cache.
112
+ Stores query embeddings and returns a cached answer when
113
+ cosine similarity to a new query exceeds the threshold.
114
+ """
115
+
116
+ def __init__(self, threshold: float = CACHE_SIMILARITY_THRESHOLD, max_size: int = 2000):
117
+ self.threshold = threshold
118
+ self.max_size = max_size
119
+ self._entries: List[_CacheEntry] = []
120
+ self._lock = threading.Lock()
121
+
122
+ def lookup(self, vec: np.ndarray) -> Optional[_CacheEntry]:
123
+ with self._lock:
124
+ if not self._entries:
125
+ return None
126
+ matrix = np.stack([e.query_vec for e in self._entries]) # (N, D)
127
+ sims = matrix @ vec # cosine similarity (vecs are normalised)
128
+ best = int(np.argmax(sims))
129
+ if sims[best] >= self.threshold:
130
+ logger.info(f"[Cache HIT] similarity={sims[best]:.3f}")
131
+ return self._entries[best]
132
+ return None
133
+
134
+ def store(self, vec: np.ndarray, answer: str, sources: List[dict], provider: str):
135
+ with self._lock:
136
+ if len(self._entries) >= self.max_size:
137
+ self._entries.pop(0) # evict oldest
138
+ self._entries.append(_CacheEntry(vec, answer, sources, provider))
139
+
140
+ @property
141
+ def size(self) -> int:
142
+ return len(self._entries)
143
+
144
+
145
+ _cache = SemanticCache()
146
+
147
+ # ══════════════════════════════════════════════════════════════════════════════
148
+ # Conversation History — Sliding Window
149
+ # ══════════════════════════════════════════════════════════════════════════════
150
+
151
+ def build_history_context(history: List[dict]) -> str:
152
+ """
153
+ Keep the last HISTORY_FULL_TURNS turns verbatim.
154
+ Older turns are collapsed into a brief summary placeholder.
155
+ In production, replace the summary stub with an actual summarisation call.
156
+ """
157
+ if not history:
158
+ return ""
159
+
160
+ recent = history[-HISTORY_FULL_TURNS * 2:] # each turn = user + assistant msg
161
+ older = history[:-(HISTORY_FULL_TURNS * 2)]
162
+
163
+ parts = []
164
+ if older:
165
+ # In production: summarise `older` with a cheap local model call.
166
+ # For now we emit a compact JSON summary stub.
167
+ older_text = " | ".join(
168
+ f"{m['role']}: {m['content'][:60]}…" for m in older[-4:]
169
+ )
170
+ parts.append(f"[ملخص المحادثة السابقة — {len(older)} رسالة]: {older_text}")
171
+
172
+ for msg in recent:
173
+ role_ar = "المستخدم" if msg["role"] == "user" else "المساعد"
174
+ parts.append(f"{role_ar}: {msg['content']}")
175
+
176
+ return "\n".join(parts)
177
+
178
+
179
+ # ══════════════════════════════════════════════════════════════════════════════
180
+ # Smart Router — lightweight complexity classifier
181
+ # ══════════════════════════════════════════════════════════════════════════════
182
+
183
+ # Keywords that signal simple / sensitive queries → route to local model
184
+ _LOCAL_PATTERNS = re.compile(
185
+ r"(ما هو|ما هي|تعريف|معنى|كم|متى|أين|هل يجوز|عقوبة|غرامة|مادة \d+|نظام \w+)",
186
+ re.IGNORECASE,
187
+ )
188
+
189
+ # Keywords that suggest complex reasoning → allow fallback
190
+ _COMPLEX_PATTERNS = re.compile(
191
+ r"(قارن|حلل|استنتج|ما الفرق|هل يمكن|ما مدى|استثناء|تعارض|تفسير|نقض|طعن)",
192
+ re.IGNORECASE,
193
+ )
194
+
195
+ def classify_query(query: str) -> str:
196
+ """
197
+ Returns 'local' or 'fallback'.
198
+ Heuristic takes ~0ms; swap with an actual mini-classifier if accuracy matters.
199
+ Priority: sensitive / simple → always local.
200
+ """
201
+ if _LOCAL_PATTERNS.search(query):
202
+ return "local"
203
+ if _COMPLEX_PATTERNS.search(query):
204
+ return "fallback"
205
+ # Default: local (private data stays on-premise)
206
+ return "local"
207
+
208
+
209
+ # ══════════════════════════════════════════════════════════════════════════════
210
+ # LLM Backends
211
+ # ══════════════════════════════════════════════════════════════════════════════
212
+
213
+ class _OllamaBackend:
214
+ def __init__(self):
215
+ from langchain_ollama import OllamaLLM
216
+ model = os.getenv("OLLAMA_MODEL", "qwen2.5:7b")
217
+ url = os.getenv("OLLAMA_URL", "http://127.0.0.1:11434")
218
+ self.llm = OllamaLLM(model=model, base_url=url, temperature=0.0)
219
+ logger.info(f"✅ Ollama Active: {model}")
220
+
221
+ def invoke(self, query: str, context: str, history_ctx: str = "") -> str:
222
+ history_block = f"\nسياق المحادثة:\n{history_ctx}\n" if history_ctx else ""
223
+ prompt = (
224
+ f"{SYSTEM_PROMPT}\n"
225
+ f"{history_block}"
226
+ f"السياق القانوني:\n{context}\n\n"
227
+ f"السؤال: {query}"
228
+ )
229
+ return self.llm.invoke(prompt)
230
+
231
+ def cleanup(self):
232
+ if hasattr(self, "llm"):
233
+ del self.llm
234
+ gc.collect()
235
+
236
+
237
+ class _GeminiBackend:
238
+ def __init__(self):
239
+ import google.generativeai as genai
240
+ api_key = os.getenv("GEMINI_API_KEY")
241
+ model = os.getenv("GEMINI_MODEL", "models/gemini-2.0-flash")
242
+ if not api_key:
243
+ raise ValueError("GEMINI_API_KEY is missing")
244
+ genai.configure(api_key=api_key)
245
+ self.model = genai.GenerativeModel(model_name=model)
246
+ logger.info(f"✅ Gemini Active: {model}")
247
+
248
+ def invoke(self, query: str, context: str, history_ctx: str = "") -> str:
249
+ history_block = f"\nسياق المحادثة:\n{history_ctx}\n" if history_ctx else ""
250
+ prompt = (
251
+ f"{SYSTEM_PROMPT}\n"
252
+ f"{history_block}"
253
+ f"الأنظمة السعودية:\n{context}\n\n"
254
+ f"السؤال: {query}"
255
+ )
256
+ return self.model.generate_content(prompt).text
257
+
258
+ def cleanup(self):
259
+ if hasattr(self, "model"):
260
+ del self.model
261
+
262
+
263
+ def _build_backend(provider: str):
264
+ if provider == "ollama":
265
+ return _OllamaBackend()
266
+ return _GeminiBackend()
267
+
268
+
269
+ # ══════════════════════════════════════════════════════════════════════════════
270
+ # Engine
271
+ # ══════════════════════════════════════════════════════════════════════════════
272
+
273
+ class _Engine:
274
+ def __init__(self):
275
+ self.embed_model = None
276
+ self.reranker = None
277
+ self.qdrant = None
278
+ self.llm_backend = None
279
+ self.current_provider = None
280
+ self.is_ready = False
281
+ self.error = ""
282
+ self._lock = threading.Lock()
283
+
284
+ _engine = _Engine()
285
+
286
+ def _load_engine_task():
287
+ try:
288
+ logger.info("Loading embedding model on CPU…")
289
+ _engine.embed_model = SentenceTransformer(PRIMARY_EMBED, device="cpu")
290
+
291
+ logger.info("Loading reranker on CPU…")
292
+ _engine.reranker = CrossEncoder(RERANKER_MODEL, device="cpu")
293
+
294
+ p = os.getenv("LLM_PROVIDER", "ollama").lower().strip()
295
+ _engine.llm_backend = _build_backend(p)
296
+ _engine.current_provider = p
297
+
298
+ _engine.qdrant = QdrantClient(host=QDRANT_HOST, port=QDRANT_PORT)
299
+ _engine.is_ready = True
300
+ logger.info(f"🟢 Legal Engine Ready | Provider: {p.upper()}")
301
+ except Exception:
302
+ _engine.error = traceback.format_exc()
303
+ logger.error(f"Engine failed:\n{_engine.error}")
304
+
305
+ threading.Thread(target=_load_engine_task, daemon=True).start()
306
+
307
+
308
+ # ══════════════════════════════════════════════════════════════════════════════
309
+ # API
310
+ # ══════════════════════════════════════════════════════════════════════════════
311
+
312
+ class SourceDetail(BaseModel):
313
+ file: str
314
+ score: float
315
+
316
+ class ChatRequest(BaseModel):
317
+ query: str = ""
318
+ history: List[dict] = [] # [{"role": "user"|"assistant", "content": "..."}]
319
+
320
+ class ChatResponse(BaseModel):
321
+ answer: str
322
+ sources_detail: List[SourceDetail]
323
+ provider: str
324
+ cache_hit: bool = False
325
+ routed_to: str = "local"
326
+
327
+ router = APIRouter(tags=["AI"])
328
+
329
+ @router.post("/chat", response_model=ChatResponse)
330
+ async def chat(
331
+ req: Optional[ChatRequest] = None,
332
+ query: Optional[str] = Query(default=None),
333
+ ):
334
+ if not _engine.is_ready:
335
+ raise HTTPException(status_code=503, detail="Loading engine…")
336
+
337
+ # Support both ?query=... (original frontend) and {"query":...} JSON body
338
+ resolved = (req.query if req and req.query else None) or query or ""
339
+ if not resolved:
340
+ raise HTTPException(status_code=422, detail="query is required")
341
+ query = resolved.strip()
342
+ history = req.history if req else []
343
+
344
+ # ── Hot-swap provider ──────────────────────────────────────────────────
345
+ load_dotenv(override=True)
346
+ live_p = os.getenv("LLM_PROVIDER", "ollama").lower().strip()
347
+ if _engine.current_provider != live_p:
348
+ with _engine._lock:
349
+ if _engine.llm_backend:
350
+ _engine.llm_backend.cleanup()
351
+ gc.collect()
352
+ try:
353
+ import torch
354
+ if torch.cuda.is_available():
355
+ torch.cuda.empty_cache()
356
+ except Exception:
357
+ pass
358
+ _engine.llm_backend = _build_backend(live_p)
359
+ _engine.current_provider = live_p
360
+
361
+ # ── Embed query ────────────────────────────────────────────────────────
362
+ q_vec = _engine.embed_model.encode(query, normalize_embeddings=True)
363
+
364
+ # ── Semantic cache lookup ──────────────────────────────────────────────
365
+ cached = _cache.lookup(q_vec)
366
+ if cached:
367
+ return ChatResponse(
368
+ answer = cached.answer,
369
+ sources_detail = [SourceDetail(**s) for s in cached.sources],
370
+ provider = cached.provider,
371
+ cache_hit = True,
372
+ routed_to = "cache",
373
+ )
374
+
375
+ # ── Qdrant search ──────────────────────────────────────────────────────
376
+ hits = _engine.qdrant.search(
377
+ collection_name=COLLECTION_NAME,
378
+ query_vector=q_vec.tolist(),
379
+ limit=5,
380
+ )
381
+ if not hits:
382
+ return ChatResponse(
383
+ answer="لا توجد نتائج قانونية ذات صلة.",
384
+ sources_detail=[],
385
+ provider=live_p,
386
+ )
387
+
388
+ # ── Rerank ─────────────────────────────────────────────────────────────
389
+ pairs = [(query, h.payload["text"]) for h in hits]
390
+ scores = _engine.reranker.predict(pairs)
391
+ ranked = sorted(zip(hits, scores), key=lambda x: x[1], reverse=True)[:3]
392
+
393
+ ctx = "\n\n".join(
394
+ f"[{h.payload.get('file_name', '')}] {h.payload.get('text', '')}"
395
+ for h, _ in ranked
396
+ )
397
+
398
+ # ── Sliding-window history ─────────────────────────────────────────────
399
+ history_ctx = build_history_context(history)
400
+
401
+ # ── Smart routing ──────────────────────────────────────────────────────
402
+ route = classify_query(query)
403
+
404
+ if route == "fallback" and live_p != "ollama":
405
+ # Use whatever the configured provider is (e.g. Gemini)
406
+ backend = _engine.llm_backend
407
+ routed_to = live_p
408
+ else:
409
+ # Always fall back to Ollama for local/sensitive queries
410
+ backend = _engine.llm_backend if live_p == "ollama" else _OllamaBackend()
411
+ routed_to = "local"
412
+
413
+ # ── Generate ───────────────────────────────────────────────────────────
414
+ answer = sanitize_arabic(backend.invoke(query, ctx, history_ctx).strip())
415
+
416
+ # ── Cache store ────────────────────────────────────────────────────────
417
+ sources_list = [
418
+ {"file": h.payload.get("file_name", ""), "score": float(s)}
419
+ for h, s in ranked
420
+ ]
421
+ _cache.store(q_vec, answer, sources_list, routed_to)
422
+ logger.info(f"[Cache] stored · size={_cache.size}")
423
+
424
+ return ChatResponse(
425
+ answer = answer,
426
+ sources_detail = [SourceDetail(**s) for s in sources_list],
427
+ provider = live_p,
428
+ cache_hit = False,
429
+ routed_to = routed_to,
430
+ )
431
+
432
+
433
+ # ── Optional: cache stats endpoint ────────────────────────────────────────────
434
+ @router.get("/cache/stats")
435
+ async def cache_stats():
436
+ return {"entries": _cache.size, "threshold": _cache.threshold}
437
+
438
+ @router.delete("/cache")
439
+ async def clear_cache():
440
+ _cache._entries.clear()
441
+ return {"status": "cleared"}
app/api/v1/endpoints/llm.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ llm.py — Saudi Law RAG · Query & Answer Endpoint
3
+ ====================================================
4
+ Optimizations applied:
5
+ 1. Sliding Window History — last 3 turns full, older → 150-token summary
6
+ 2. Prompt Compression — lean system prompt injected per-request
7
+ 3. Semantic Cache — vector similarity ≥ 0.85 → skip the model entirely
8
+ 4. Smart Router — lightweight classifier decides local vs fallback
9
+ 5. Memory stability — Embedding/Reranker on CPU
10
+ 6. Hot-swap provider — live .env reload between requests
11
+ """
12
+
13
+ import os
14
+ import re
15
+ import time
16
+ import logging
17
+ import threading
18
+ import traceback
19
+ import gc
20
+ from typing import List, Optional, Tuple
21
+ from dataclasses import dataclass, field
22
+
23
+ import numpy as np
24
+ from fastapi import APIRouter, HTTPException, Query
25
+ from pydantic import BaseModel
26
+ from qdrant_client import QdrantClient
27
+ from sentence_transformers import SentenceTransformer, CrossEncoder
28
+ from dotenv import load_dotenv
29
+
30
+ load_dotenv(override=True)
31
+ logger = logging.getLogger("app.api.v1.endpoints.llm")
32
+
33
+ # ══════════════════════════════════════════════════════════════════════════════
34
+ # Config
35
+ # ══════════════════════════════════════════════════════════════════════════════
36
+
37
+ COLLECTION_NAME = "saudi_law_data"
38
+ QDRANT_URL = os.getenv("QDRANT_URL")
39
+ QDRANT_API_KEY = os.getenv("QDRANT_API_KEY")
40
+ QDRANT_HOST = os.getenv("QDRANT_HOST", "localhost")
41
+ QDRANT_PORT = int(os.getenv("QDRANT_PORT", "6333"))
42
+ PRIMARY_EMBED = os.getenv("PRIMARY_EMBED", "Omartificial-Intelligence-Space/Arabic-Triplet-Matryoshka-V2")
43
+ RERANKER_MODEL = os.getenv("RERANKER_MODEL", "Omartificial-Intelligence-Space/ARA-Reranker-V1")
44
+
45
+ # ── Optimization knobs ────────────────────────────────────────────────────────
46
+ CACHE_SIMILARITY_THRESHOLD = float(os.getenv("CACHE_SIMILARITY_THRESHOLD", "0.85"))
47
+ HISTORY_FULL_TURNS = int(os.getenv("HISTORY_FULL_TURNS", "3")) # turns kept verbatim
48
+ HISTORY_SUMMARY_TOKENS = int(os.getenv("HISTORY_SUMMARY_TOKENS", "150"))
49
+ ROUTING_COMPLEX_THRESHOLD = float(os.getenv("ROUTING_COMPLEX_THRESHOLD", "0.7"))
50
+
51
+ # Compressed system prompt (was 2,800 tokens — now ~120 tokens)
52
+ SYSTEM_PROMPT = (
53
+ "أنت مساعد قانوني سعودي متخصص. "
54
+ "أجب بناءً على السياق المرفق فقط. "
55
+ "إذا لم يكن الجواب في السياق، قل ذلك صراحةً. "
56
+ "أجب بإيجاز ودقة."
57
+ )
58
+
59
+ # ══════════════════════════════════════════════════════════════════════════════
60
+ # Language Sanitizer — strips non-Arabic foreign text from model output
61
+ # ══════════════════════════════════════════════════════════════════════════════
62
+
63
+ # Unicode ranges that are NOT Arabic/Latin punctuation/numbers → foreign script
64
+ _FOREIGN_SCRIPT_RE = re.compile(
65
+ r"["
66
+ r"一-鿿" # CJK Unified (Chinese/Japanese/Korean)
67
+ r" -〿" # CJK Symbols & Punctuation
68
+ r"぀-ゟ" # Hiragana
69
+ r"゠-ヿ" # Katakana
70
+ r"가-힯" # Korean Hangul
71
+ r"Ѐ-ӿ" # Cyrillic
72
+ r"ऀ-ॿ" # Devanagari
73
+ r"]+"
74
+ )
75
+
76
+ def sanitize_arabic(text: str) -> str:
77
+ """
78
+ Remove any sentence/segment that contains foreign-script characters.
79
+ Keeps Arabic, English (for legal terms), numbers, and punctuation.
80
+ Logs a warning whenever it strips something so you can monitor the model.
81
+ """
82
+ # Split on Arabic sentence boundaries and newlines
83
+ segments = re.split(r"(\n+|[،؛\.!?]+)", text)
84
+ clean = []
85
+ removed = []
86
+ for seg in segments:
87
+ if _FOREIGN_SCRIPT_RE.search(seg):
88
+ removed.append(seg.strip())
89
+ else:
90
+ clean.append(seg)
91
+ if removed:
92
+ logger.warning(f"[Sanitizer] Stripped foreign-script segments: {removed}")
93
+ result = "".join(clean).strip()
94
+ # Collapse multiple blank lines left after removal
95
+ result = re.sub(r"\n{3,}", "\n\n", result)
96
+ return result if result else "عذراً، لم أتمكن من توليد إجابة واضحة. يرجى إعادة صياغة السؤال."
97
+
98
+
99
+ # ══════════════════════════════════════════════════════════════════════��═══════
100
+ # Semantic Cache
101
+ # ══════════════════════════════════════════════════════════════════════════════
102
+
103
+ @dataclass
104
+ class _CacheEntry:
105
+ query_vec: np.ndarray
106
+ answer: str
107
+ sources: List[dict]
108
+ provider: str
109
+ ts: float = field(default_factory=time.time)
110
+
111
+ class SemanticCache:
112
+ """
113
+ In-memory semantic cache.
114
+ Stores query embeddings and returns a cached answer when
115
+ cosine similarity to a new query exceeds the threshold.
116
+ """
117
+
118
+ def __init__(self, threshold: float = CACHE_SIMILARITY_THRESHOLD, max_size: int = 2000):
119
+ self.threshold = threshold
120
+ self.max_size = max_size
121
+ self._entries: List[_CacheEntry] = []
122
+ self._lock = threading.Lock()
123
+
124
+ def lookup(self, vec: np.ndarray) -> Optional[_CacheEntry]:
125
+ with self._lock:
126
+ if not self._entries:
127
+ return None
128
+ matrix = np.stack([e.query_vec for e in self._entries]) # (N, D)
129
+ sims = matrix @ vec # cosine similarity (vecs are normalised)
130
+ best = int(np.argmax(sims))
131
+ if sims[best] >= self.threshold:
132
+ logger.info(f"[Cache HIT] similarity={sims[best]:.3f}")
133
+ return self._entries[best]
134
+ return None
135
+
136
+ def store(self, vec: np.ndarray, answer: str, sources: List[dict], provider: str):
137
+ with self._lock:
138
+ if len(self._entries) >= self.max_size:
139
+ self._entries.pop(0) # evict oldest
140
+ self._entries.append(_CacheEntry(vec, answer, sources, provider))
141
+
142
+ @property
143
+ def size(self) -> int:
144
+ return len(self._entries)
145
+
146
+
147
+ _cache = SemanticCache()
148
+
149
+ # ══════════════════════════════════════════════════════════════════════════════
150
+ # Conversation History — Sliding Window
151
+ # ══════════════════════════════════════════════════════════════════════════════
152
+
153
+ def build_history_context(history: List[dict]) -> str:
154
+ """
155
+ Keep the last HISTORY_FULL_TURNS turns verbatim.
156
+ Older turns are collapsed into a brief summary placeholder.
157
+ In production, replace the summary stub with an actual summarisation call.
158
+ """
159
+ if not history:
160
+ return ""
161
+
162
+ recent = history[-HISTORY_FULL_TURNS * 2:] # each turn = user + assistant msg
163
+ older = history[:-(HISTORY_FULL_TURNS * 2)]
164
+
165
+ parts = []
166
+ if older:
167
+ # In production: summarise `older` with a cheap local model call.
168
+ # For now we emit a compact JSON summary stub.
169
+ older_text = " | ".join(
170
+ f"{m['role']}: {m['content'][:60]}…" for m in older[-4:]
171
+ )
172
+ parts.append(f"[ملخص المحادثة السابقة — {len(older)} رسالة]: {older_text}")
173
+
174
+ for msg in recent:
175
+ role_ar = "المستخدم" if msg["role"] == "user" else "المساعد"
176
+ parts.append(f"{role_ar}: {msg['content']}")
177
+
178
+ return "\n".join(parts)
179
+
180
+
181
+ # ══════════════════════════════════════════════════════════════════════════════
182
+ # Smart Router — lightweight complexity classifier
183
+ # ══════════════════════════════════════════════════════════════════════════════
184
+
185
+ # Keywords that signal simple / sensitive queries → route to local model
186
+ _LOCAL_PATTERNS = re.compile(
187
+ r"(ما هو|ما هي|تعريف|معنى|كم|متى|أين|هل يجوز|عقوبة|غرامة|مادة \d+|نظام \w+)",
188
+ re.IGNORECASE,
189
+ )
190
+
191
+ # Keywords that suggest complex reasoning → allow fallback
192
+ _COMPLEX_PATTERNS = re.compile(
193
+ r"(قارن|حلل|استنتج|ما الفرق|هل يمكن|ما مدى|استثناء|تعارض|تفسير|نقض|طعن)",
194
+ re.IGNORECASE,
195
+ )
196
+
197
+ def classify_query(query: str) -> str:
198
+ """
199
+ Returns 'local' or 'fallback'.
200
+ Heuristic takes ~0ms; swap with an actual mini-classifier if accuracy matters.
201
+ Priority: sensitive / simple → always local.
202
+ """
203
+ if _LOCAL_PATTERNS.search(query):
204
+ return "local"
205
+ if _COMPLEX_PATTERNS.search(query):
206
+ return "fallback"
207
+ # Default: local (private data stays on-premise)
208
+ return "local"
209
+
210
+
211
+ # ════════════════════════════════════════════════════════════════════��═════════
212
+ # LLM Backends
213
+ # ══════════════════════════════════════════════════════════════════════════════
214
+
215
+ class _OllamaBackend:
216
+ def __init__(self):
217
+ from langchain_ollama import OllamaLLM
218
+ model = os.getenv("OLLAMA_MODEL", "qwen2.5:7b")
219
+ url = os.getenv("OLLAMA_URL", "http://127.0.0.1:11434")
220
+ self.llm = OllamaLLM(model=model, base_url=url, temperature=0.0)
221
+ logger.info(f"✅ Ollama Active: {model}")
222
+
223
+ def invoke(self, query: str, context: str, history_ctx: str = "") -> str:
224
+ history_block = f"\nسياق المحادثة:\n{history_ctx}\n" if history_ctx else ""
225
+ prompt = (
226
+ f"{SYSTEM_PROMPT}\n"
227
+ f"{history_block}"
228
+ f"السياق القانوني:\n{context}\n\n"
229
+ f"السؤال: {query}"
230
+ )
231
+ return self.llm.invoke(prompt)
232
+
233
+ def cleanup(self):
234
+ if hasattr(self, "llm"):
235
+ del self.llm
236
+ gc.collect()
237
+
238
+
239
+ class _GeminiBackend:
240
+ def __init__(self):
241
+ import google.generativeai as genai
242
+ api_key = os.getenv("GEMINI_API_KEY")
243
+ model = os.getenv("GEMINI_MODEL", "models/gemini-2.0-flash")
244
+ if not api_key:
245
+ raise ValueError("GEMINI_API_KEY is missing")
246
+ genai.configure(api_key=api_key)
247
+ self.model = genai.GenerativeModel(model_name=model)
248
+ logger.info(f"✅ Gemini Active: {model}")
249
+
250
+ def invoke(self, query: str, context: str, history_ctx: str = "") -> str:
251
+ history_block = f"\nسياق المحادثة:\n{history_ctx}\n" if history_ctx else ""
252
+ prompt = (
253
+ f"{SYSTEM_PROMPT}\n"
254
+ f"{history_block}"
255
+ f"الأنظمة السعودية:\n{context}\n\n"
256
+ f"السؤال: {query}"
257
+ )
258
+ return self.model.generate_content(prompt).text
259
+
260
+ def cleanup(self):
261
+ if hasattr(self, "model"):
262
+ del self.model
263
+
264
+
265
+ def _build_backend(provider: str):
266
+ if provider == "ollama":
267
+ return _OllamaBackend()
268
+ return _GeminiBackend()
269
+
270
+
271
+ # ══════════════════════════════════════════════════════════════════════════════
272
+ # Engine
273
+ # ══════════════════════════════════════════════════════════════════════════════
274
+
275
+ class _Engine:
276
+ def __init__(self):
277
+ self.embed_model = None
278
+ self.reranker = None
279
+ self.qdrant = None
280
+ self.llm_backend = None
281
+ self.current_provider = None
282
+ self.is_ready = False
283
+ self.error = ""
284
+ self._lock = threading.Lock()
285
+
286
+ _engine = _Engine()
287
+
288
+
289
+ def _make_qdrant() -> QdrantClient:
290
+ """Qdrant Cloud when QDRANT_URL is set, otherwise a local Qdrant server."""
291
+ if QDRANT_URL:
292
+ logger.info(f"Qdrant: cloud → {QDRANT_URL}")
293
+ return QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY, timeout=30)
294
+ logger.info(f"Qdrant: local → {QDRANT_HOST}:{QDRANT_PORT}")
295
+ return QdrantClient(host=QDRANT_HOST, port=QDRANT_PORT)
296
+
297
+
298
+ def _qdrant_search(vec: list, limit: int = 5):
299
+ """Works with old (search) and new (query_points) qdrant-client versions."""
300
+ client = _engine.qdrant
301
+ if hasattr(client, "query_points"):
302
+ return client.query_points(
303
+ collection_name=COLLECTION_NAME, query=vec, limit=limit, with_payload=True
304
+ ).points
305
+ return client.search(collection_name=COLLECTION_NAME, query_vector=vec, limit=limit)
306
+
307
+ def _load_engine_task():
308
+ try:
309
+ logger.info("Loading embedding model on CPU…")
310
+ _engine.embed_model = SentenceTransformer(PRIMARY_EMBED, device="cpu")
311
+
312
+ logger.info("Loading reranker on CPU…")
313
+ _engine.reranker = CrossEncoder(RERANKER_MODEL, device="cpu")
314
+
315
+ p = os.getenv("LLM_PROVIDER", "gemini").lower().strip()
316
+ _engine.llm_backend = _build_backend(p)
317
+ _engine.current_provider = p
318
+
319
+ _engine.qdrant = _make_qdrant()
320
+ _engine.is_ready = True
321
+ logger.info(f"🟢 Legal Engine Ready | Provider: {p.upper()}")
322
+ except Exception:
323
+ _engine.error = traceback.format_exc()
324
+ logger.error(f"Engine failed:\n{_engine.error}")
325
+
326
+ threading.Thread(target=_load_engine_task, daemon=True).start()
327
+
328
+
329
+ # ══════════════════════════════════════════════════════════════════════════════
330
+ # API
331
+ # ══════════════════════════════════════════════════════════════════════════════
332
+
333
+ class SourceDetail(BaseModel):
334
+ file: str
335
+ score: float
336
+
337
+ class ChatRequest(BaseModel):
338
+ query: str = ""
339
+ history: List[dict] = [] # [{"role": "user"|"assistant", "content": "..."}]
340
+
341
+ class ChatResponse(BaseModel):
342
+ answer: str
343
+ sources_detail: List[SourceDetail]
344
+ provider: str
345
+ cache_hit: bool = False
346
+ routed_to: str = "local"
347
+
348
+ router = APIRouter(tags=["AI"])
349
+
350
+ @router.post("/chat", response_model=ChatResponse)
351
+ def chat(
352
+ req: Optional[ChatRequest] = None,
353
+ query: Optional[str] = Query(default=None),
354
+ ):
355
+ if not _engine.is_ready:
356
+ raise HTTPException(
357
+ status_code=503,
358
+ detail=("Engine failed: " + _engine.error[-600:]) if _engine.error else "Loading engine…",
359
+ )
360
+
361
+ # Support both ?query=... (original frontend) and {"query":...} JSON body
362
+ resolved = (req.query if req and req.query else None) or query or ""
363
+ if not resolved:
364
+ raise HTTPException(status_code=422, detail="query is required")
365
+ query = resolved.strip()
366
+ history = req.history if req else []
367
+
368
+ # ── Hot-swap provider ──────────────────────────────────────────────────
369
+ load_dotenv(override=True)
370
+ live_p = os.getenv("LLM_PROVIDER", "gemini").lower().strip()
371
+ if _engine.current_provider != live_p:
372
+ with _engine._lock:
373
+ if _engine.llm_backend:
374
+ _engine.llm_backend.cleanup()
375
+ gc.collect()
376
+ try:
377
+ import torch
378
+ if torch.cuda.is_available():
379
+ torch.cuda.empty_cache()
380
+ except Exception:
381
+ pass
382
+ _engine.llm_backend = _build_backend(live_p)
383
+ _engine.current_provider = live_p
384
+
385
+ # ── Embed query ────────────────────────────────────────────────────────
386
+ q_vec = _engine.embed_model.encode(query, normalize_embeddings=True)
387
+
388
+ # ── Semantic cache lookup ──────────────────────────────────────────────
389
+ cached = _cache.lookup(q_vec)
390
+ if cached:
391
+ return ChatResponse(
392
+ answer = cached.answer,
393
+ sources_detail = [SourceDetail(**s) for s in cached.sources],
394
+ provider = cached.provider,
395
+ cache_hit = True,
396
+ routed_to = "cache",
397
+ )
398
+
399
+ # ── Qdrant search ──────────────────────────────────────────────────────
400
+ try:
401
+ hits = _qdrant_search(q_vec.tolist(), limit=5)
402
+ except Exception as e:
403
+ logger.error(f"Qdrant search failed: {e}")
404
+ raise HTTPException(status_code=502, detail=f"Vector search failed: {e}")
405
+ if not hits:
406
+ return ChatResponse(
407
+ answer="لا توجد نتائج قانونية ذات صلة.",
408
+ sources_detail=[],
409
+ provider=live_p,
410
+ )
411
+
412
+ # ── Rerank ─────────────────────────────────────────────────────────────
413
+ pairs = [(query, h.payload["text"]) for h in hits]
414
+ scores = _engine.reranker.predict(pairs)
415
+ ranked = sorted(zip(hits, scores), key=lambda x: x[1], reverse=True)[:3]
416
+
417
+ ctx = "\n\n".join(
418
+ f"[{h.payload.get('file_name', '')}] {h.payload.get('text', '')}"
419
+ for h, _ in ranked
420
+ )
421
+
422
+ # ── Sliding-window history ─────────────────────────────────────────────
423
+ history_ctx = build_history_context(history)
424
+
425
+ # ── Smart routing ──────────────────────────────────────────────────────
426
+ route = classify_query(query)
427
+ backend = _engine.llm_backend
428
+ routed_to = live_p
429
+
430
+ # ── Generate ───────────────────────────────────────────────────────────
431
+ try:
432
+ raw_answer = backend.invoke(query, ctx, history_ctx)
433
+ except Exception as e:
434
+ logger.error(f"LLM call failed ({live_p}): {e}")
435
+ raise HTTPException(status_code=502, detail=f"LLM error ({live_p}): {e}")
436
+ answer = sanitize_arabic(raw_answer.strip())
437
+
438
+ # ── Cache store ─────────────────────────────────���──────────────────────
439
+ sources_list = [
440
+ {"file": h.payload.get("file_name", ""), "score": float(s)}
441
+ for h, s in ranked
442
+ ]
443
+ _cache.store(q_vec, answer, sources_list, routed_to)
444
+ logger.info(f"[Cache] stored · size={_cache.size}")
445
+
446
+ return ChatResponse(
447
+ answer = answer,
448
+ sources_detail = [SourceDetail(**s) for s in sources_list],
449
+ provider = live_p,
450
+ cache_hit = False,
451
+ routed_to = routed_to,
452
+ )
453
+
454
+
455
+ # ── Optional: cache stats endpoint ────────────────────────────────────────────
456
+ @router.get("/cache/stats")
457
+ async def cache_stats():
458
+ return {"entries": _cache.size, "threshold": _cache.threshold}
459
+
460
+ @router.delete("/cache")
461
+ async def clear_cache():
462
+ _cache._entries.clear()
463
+ return {"status": "cleared"}
app/api/v1/endpoints/notifications.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Notifications API - user's own only"""
2
+ from typing import Any
3
+ from fastapi import APIRouter, Depends, HTTPException
4
+ from sqlalchemy.orm import Session
5
+ from datetime import datetime
6
+
7
+ from app.core.database import get_db
8
+ from app.core.deps import get_current_active_user
9
+ from app.models.user import User
10
+ from app.models.notification import Notification
11
+
12
+ router = APIRouter()
13
+
14
+
15
+ def _d(n: Notification) -> dict:
16
+ return {k: (v.value if hasattr(v, "value") else (str(v) if hasattr(v, "isoformat") else v))
17
+ for k, v in n.__dict__.items() if not k.startswith("_")}
18
+
19
+
20
+ @router.get("")
21
+ def list_notifications(skip: int = 0, limit: int = 50, unread_only: bool = False,
22
+ db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
23
+ q = db.query(Notification).filter(Notification.user_id == current_user.id)
24
+ if unread_only:
25
+ q = q.filter(Notification.is_read == False)
26
+ notifs = q.order_by(Notification.created_at.desc()).offset(skip).limit(limit).all()
27
+ unread_count = db.query(Notification).filter(
28
+ Notification.user_id == current_user.id, Notification.is_read == False
29
+ ).count()
30
+ return {"total": q.count(), "unread_count": unread_count, "notifications": [_d(n) for n in notifs]}
31
+
32
+
33
+ @router.get("/{notification_id}")
34
+ def get_notification(notification_id: int, db: Session = Depends(get_db),
35
+ current_user: User = Depends(get_current_active_user)) -> Any:
36
+ n = db.query(Notification).filter(
37
+ Notification.id == notification_id, Notification.user_id == current_user.id
38
+ ).first()
39
+ if not n: raise HTTPException(404, "الإشعار غير موجود")
40
+ return _d(n)
41
+
42
+
43
+ @router.post("/{notification_id}/read")
44
+ def mark_read(notification_id: int, db: Session = Depends(get_db),
45
+ current_user: User = Depends(get_current_active_user)) -> Any:
46
+ n = db.query(Notification).filter(
47
+ Notification.id == notification_id, Notification.user_id == current_user.id
48
+ ).first()
49
+ if not n: raise HTTPException(404, "الإشعار غير موجود")
50
+ n.is_read = True; n.read_at = datetime.utcnow()
51
+ db.commit()
52
+ return {"message": "تم التحديد كمقروء", "id": notification_id}
53
+
54
+
55
+ @router.post("/read-all")
56
+ def mark_all_read(db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
57
+ count = db.query(Notification).filter(
58
+ Notification.user_id == current_user.id, Notification.is_read == False
59
+ ).update({"is_read": True, "read_at": datetime.utcnow()})
60
+ db.commit()
61
+ return {"message": f"تم تحديد {count} إشعار كمقروء", "updated": count}
62
+
63
+
64
+ @router.delete("/{notification_id}")
65
+ def delete_notification(notification_id: int, db: Session = Depends(get_db),
66
+ current_user: User = Depends(get_current_active_user)) -> Any:
67
+ n = db.query(Notification).filter(
68
+ Notification.id == notification_id, Notification.user_id == current_user.id
69
+ ).first()
70
+ if not n: raise HTTPException(404, "الإشعار غير موجود")
71
+ db.delete(n); db.commit()
72
+ return {"message": "تم الحذف", "id": notification_id}
app/api/v1/endpoints/reminders.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reminders API - with permissions"""
2
+ from typing import Any, Optional
3
+ from fastapi import APIRouter, Depends, HTTPException
4
+ from sqlalchemy.orm import Session
5
+ from datetime import datetime
6
+ from pydantic import BaseModel
7
+
8
+ from app.core.database import get_db
9
+ from app.core.deps import get_current_active_user
10
+ from app.models.user import User
11
+ from app.models.reminder import Reminder, ReminderStatus, ReminderPriority
12
+
13
+ router = APIRouter()
14
+
15
+
16
+ class ReminderIn(BaseModel):
17
+ title: str
18
+ title_ar: Optional[str] = None
19
+ description: Optional[str] = None
20
+ due_date: Optional[str] = None
21
+ priority: Optional[str] = "normal"
22
+ assigned_to_id: Optional[int] = None
23
+ client_id: Optional[int] = None
24
+
25
+
26
+ def _d(r: Reminder) -> dict:
27
+ return {k: (v.value if hasattr(v, "value") else (str(v) if hasattr(v, "isoformat") else v))
28
+ for k, v in r.__dict__.items() if not k.startswith("_")}
29
+
30
+
31
+ def _parse_priority(p: str):
32
+ try: return ReminderPriority(p)
33
+ except: return ReminderPriority.NORMAL
34
+
35
+
36
+ @router.get("")
37
+ def list_reminders(
38
+ skip: int = 0,
39
+ limit: int = 50,
40
+ status_filter: Optional[str] = None,
41
+ db: Session = Depends(get_db),
42
+ current_user: User = Depends(get_current_active_user)
43
+ ) -> Any:
44
+ """Admin sees all, regular user sees only their own"""
45
+ q = db.query(Reminder)
46
+
47
+ # FIX: Permissions
48
+ if not current_user.is_superuser:
49
+ q = q.filter(
50
+ (Reminder.created_by_id == current_user.id) |
51
+ (Reminder.assigned_to_id == current_user.id)
52
+ )
53
+
54
+ if status_filter:
55
+ try: q = q.filter(Reminder.status == ReminderStatus(status_filter))
56
+ except ValueError: pass
57
+
58
+ reminders = q.order_by(Reminder.due_date.asc()).offset(skip).limit(limit).all()
59
+ return {"total": q.count(), "reminders": [_d(r) for r in reminders]}
60
+
61
+
62
+ @router.post("", status_code=201)
63
+ def create_reminder(reminder_in: ReminderIn, db: Session = Depends(get_db),
64
+ current_user: User = Depends(get_current_active_user)) -> Any:
65
+ due = None
66
+ if reminder_in.due_date:
67
+ try: due = datetime.fromisoformat(reminder_in.due_date.replace("Z", "+00:00"))
68
+ except:
69
+ try: due = datetime.strptime(reminder_in.due_date, "%Y-%m-%d")
70
+ except: pass
71
+ try:
72
+ r = Reminder(
73
+ title=reminder_in.title, title_ar=reminder_in.title_ar,
74
+ description=reminder_in.description, due_date=due,
75
+ priority=_parse_priority(reminder_in.priority or "normal"),
76
+ status=ReminderStatus.PENDING,
77
+ created_by_id=current_user.id,
78
+ assigned_to_id=reminder_in.assigned_to_id,
79
+ client_id=reminder_in.client_id
80
+ )
81
+ db.add(r); db.commit(); db.refresh(r)
82
+ return _d(r)
83
+ except Exception as e:
84
+ db.rollback(); raise HTTPException(500, str(e))
85
+
86
+
87
+ @router.get("/{reminder_id}")
88
+ def get_reminder(reminder_id: int, db: Session = Depends(get_db),
89
+ current_user: User = Depends(get_current_active_user)) -> Any:
90
+ r = db.query(Reminder).filter(Reminder.id == reminder_id).first()
91
+ if not r: raise HTTPException(404, "التذكير غير موجود")
92
+
93
+ # FIX: Permission check
94
+ if not current_user.is_superuser:
95
+ if r.created_by_id != current_user.id and r.assigned_to_id != current_user.id:
96
+ raise HTTPException(403, "غير مصرح")
97
+
98
+ return _d(r)
99
+
100
+
101
+ @router.put("/{reminder_id}")
102
+ def update_reminder(reminder_id: int, reminder_in: ReminderIn, db: Session = Depends(get_db),
103
+ current_user: User = Depends(get_current_active_user)) -> Any:
104
+ r = db.query(Reminder).filter(Reminder.id == reminder_id).first()
105
+ if not r: raise HTTPException(404, "التذكير غير موجود")
106
+
107
+ # FIX: Permission check
108
+ if not current_user.is_superuser:
109
+ if r.created_by_id != current_user.id and r.assigned_to_id != current_user.id:
110
+ raise HTTPException(403, "غير مصرح")
111
+
112
+ for k, v in reminder_in.model_dump(exclude_unset=True).items():
113
+ if k == "priority": setattr(r, k, _parse_priority(v))
114
+ elif k == "due_date" and v:
115
+ try: setattr(r, k, datetime.fromisoformat(v))
116
+ except: pass
117
+ else: setattr(r, k, v)
118
+ db.commit(); db.refresh(r)
119
+ return _d(r)
120
+
121
+
122
+ @router.post("/{reminder_id}/complete")
123
+ def complete_reminder(reminder_id: int, db: Session = Depends(get_db),
124
+ current_user: User = Depends(get_current_active_user)) -> Any:
125
+ r = db.query(Reminder).filter(Reminder.id == reminder_id).first()
126
+ if not r: raise HTTPException(404, "التذكير غير موجود")
127
+
128
+ # FIX: Permission check
129
+ if not current_user.is_superuser:
130
+ if r.created_by_id != current_user.id and r.assigned_to_id != current_user.id:
131
+ raise HTTPException(403, "غير مصرح")
132
+
133
+ r.status = ReminderStatus.COMPLETED
134
+ db.commit()
135
+ return {"message": "تم الإكمال", "id": reminder_id}
136
+
137
+
138
+ @router.delete("/{reminder_id}")
139
+ def delete_reminder(reminder_id: int, db: Session = Depends(get_db),
140
+ current_user: User = Depends(get_current_active_user)) -> Any:
141
+ r = db.query(Reminder).filter(Reminder.id == reminder_id).first()
142
+ if not r: raise HTTPException(404, "التذكير غير موجود")
143
+
144
+ # Only creator or admin can delete
145
+ if not current_user.is_superuser and r.created_by_id != current_user.id:
146
+ raise HTTPException(403, "فقط منشئ التذكير يمكنه حذفه")
147
+
148
+ db.delete(r); db.commit()
149
+ return {"message": "تم الحذف", "id": reminder_id}
app/api/v1/endpoints/tickets.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tickets API - With type filter for lawyers"""
2
+ from typing import Any, Optional
3
+ from fastapi import APIRouter, Depends, HTTPException
4
+ from sqlalchemy.orm import Session
5
+ from datetime import datetime
6
+ from pydantic import BaseModel
7
+
8
+ from app.core.database import get_db
9
+ from app.core.deps import get_current_active_user
10
+ from app.models.user import User, UserRole
11
+ from app.models.ticket import Ticket, TicketStatus, TicketType, TicketMessage
12
+
13
+ router = APIRouter()
14
+
15
+
16
+ class TicketIn(BaseModel):
17
+ title: Optional[str] = None
18
+ description: Optional[str] = None
19
+ ticket_type: Optional[str] = None
20
+ priority: Optional[str] = None
21
+ status: Optional[str] = None
22
+ assigned_to_id: Optional[int] = None
23
+
24
+
25
+ class MessageIn(BaseModel):
26
+ message: str
27
+
28
+
29
+ def _next_num(db: Session) -> str:
30
+ last = db.query(Ticket).order_by(Ticket.id.desc()).first()
31
+ return f"TKT-{(last.id + 1 if last else 1):06d}"
32
+
33
+
34
+ def _d(t: Ticket) -> dict:
35
+ return {k: (v.value if hasattr(v, "value") else (str(v) if hasattr(v, "isoformat") else v))
36
+ for k, v in t.__dict__.items() if not k.startswith("_")}
37
+
38
+
39
+ @router.get("")
40
+ def list_tickets(
41
+ skip: int = 0,
42
+ limit: int = 50,
43
+ status_filter: Optional[str] = None,
44
+ type_filter: Optional[str] = None, # NEW: Filter by ticket type
45
+ db: Session = Depends(get_db),
46
+ current_user: User = Depends(get_current_active_user)
47
+ ) -> Any:
48
+ """
49
+ List tickets with filters:
50
+ - status_filter: pending, in_progress, open, closed, resolved
51
+ - type_filter: inquiry, support, complaint, request (استفسار، دعم فني، شكوى، طلب)
52
+
53
+ Permissions:
54
+ - Admin: sees ALL
55
+ - Lawyer/Employee: sees ONLY assigned to them
56
+ - Client: sees ONLY their own
57
+ """
58
+ q = db.query(Ticket)
59
+
60
+ # Permission filtering
61
+ if current_user.is_superuser:
62
+ pass # Admin sees all
63
+ elif current_user.role in [UserRole.LAWYER, UserRole.EMPLOYEE]:
64
+ q = q.filter(
65
+ (Ticket.assigned_to_id == current_user.id) |
66
+ (Ticket.created_by_id == current_user.id)
67
+ )
68
+ else:
69
+ q = q.filter(Ticket.created_by_id == current_user.id)
70
+
71
+ # Status filter
72
+ if status_filter:
73
+ status_map = {
74
+ 'pending': TicketStatus.PENDING,
75
+ 'in_progress': TicketStatus.IN_PROGRESS,
76
+ 'open': TicketStatus.OPEN,
77
+ 'closed': TicketStatus.CLOSED,
78
+ 'resolved': TicketStatus.RESOLVED
79
+ }
80
+ if status_filter.lower() in status_map:
81
+ q = q.filter(Ticket.status == status_map[status_filter.lower()])
82
+
83
+ # Type filter - NEW
84
+ if type_filter:
85
+ type_map = {
86
+ 'inquiry': TicketType.INQUIRY, # استفسار
87
+ 'support': TicketType.SUPPORT, # دعم فني
88
+ 'complaint': TicketType.COMPLAINT, # شكوى
89
+ 'request': TicketType.REQUEST # طلب
90
+ }
91
+ if type_filter.lower() in type_map:
92
+ q = q.filter(Ticket.ticket_type == type_map[type_filter.lower()])
93
+
94
+ tickets = q.order_by(Ticket.created_at.desc()).offset(skip).limit(limit).all()
95
+ return {"total": q.count(), "tickets": [_d(t) for t in tickets]}
96
+
97
+
98
+ @router.post("", status_code=201)
99
+ def create_ticket(ticket_in: TicketIn, db: Session = Depends(get_db),
100
+ current_user: User = Depends(get_current_active_user)) -> Any:
101
+ try:
102
+ ttype = TicketType(ticket_in.ticket_type) if ticket_in.ticket_type else TicketType.SUPPORT
103
+ except ValueError:
104
+ ttype = TicketType.SUPPORT
105
+
106
+ t = Ticket(
107
+ ticket_number=_next_num(db), title=ticket_in.title, description=ticket_in.description,
108
+ ticket_type=ttype, status=TicketStatus.OPEN, priority=ticket_in.priority or "normal",
109
+ created_by_id=current_user.id, assigned_to_id=ticket_in.assigned_to_id, messages_count=0
110
+ )
111
+ db.add(t); db.commit(); db.refresh(t)
112
+ return _d(t)
113
+
114
+
115
+ @router.get("/{ticket_id}")
116
+ def get_ticket(ticket_id: int, db: Session = Depends(get_db),
117
+ current_user: User = Depends(get_current_active_user)) -> Any:
118
+ t = db.query(Ticket).filter(Ticket.id == ticket_id).first()
119
+ if not t: raise HTTPException(404, "غير موجودة")
120
+
121
+ # Permission check
122
+ if not current_user.is_superuser:
123
+ if current_user.role in [UserRole.LAWYER, UserRole.EMPLOYEE]:
124
+ if t.assigned_to_id != current_user.id and t.created_by_id != current_user.id:
125
+ raise HTTPException(403, "غير مصرح")
126
+ else:
127
+ if t.created_by_id != current_user.id:
128
+ raise HTTPException(403, "غير مصرح")
129
+
130
+ result = _d(t)
131
+ result["messages"] = [
132
+ {"id": m.id, "message": m.content, "user_id": m.user_id, "created_at": str(m.created_at)}
133
+ for m in db.query(TicketMessage).filter(TicketMessage.ticket_id == ticket_id).all()
134
+ ]
135
+ return result
136
+
137
+
138
+ @router.put("/{ticket_id}")
139
+ def update_ticket(ticket_id: int, ticket_in: TicketIn, db: Session = Depends(get_db),
140
+ current_user: User = Depends(get_current_active_user)) -> Any:
141
+ t = db.query(Ticket).filter(Ticket.id == ticket_id).first()
142
+ if not t: raise HTTPException(404, "غير موجودة")
143
+
144
+ if not current_user.is_superuser:
145
+ if current_user.role in [UserRole.LAWYER, UserRole.EMPLOYEE]:
146
+ if t.assigned_to_id != current_user.id and t.created_by_id != current_user.id:
147
+ raise HTTPException(403, "غير مصرح")
148
+ else:
149
+ if t.created_by_id != current_user.id:
150
+ raise HTTPException(403, "غير مصرح")
151
+
152
+ for field, value in ticket_in.model_dump(exclude_unset=True, exclude_none=True).items():
153
+ if field == "status" and value:
154
+ status_map = {
155
+ "in_progress": TicketStatus.IN_PROGRESS, "resolved": TicketStatus.RESOLVED,
156
+ "open": TicketStatus.OPEN, "closed": TicketStatus.CLOSED, "pending": TicketStatus.PENDING
157
+ }
158
+ t.status = status_map.get(value.lower(), TicketStatus.OPEN)
159
+ elif field == "ticket_type" and value:
160
+ try: t.ticket_type = TicketType(value)
161
+ except: pass
162
+ else:
163
+ setattr(t, field, value)
164
+
165
+ db.commit(); db.refresh(t)
166
+ return _d(t)
167
+
168
+
169
+ @router.post("/{ticket_id}/close")
170
+ def close_ticket(ticket_id: int, db: Session = Depends(get_db),
171
+ current_user: User = Depends(get_current_active_user)) -> Any:
172
+ t = db.query(Ticket).filter(Ticket.id == ticket_id).first()
173
+ if not t: raise HTTPException(404, "غير موجودة")
174
+
175
+ if not current_user.is_superuser:
176
+ if current_user.role in [UserRole.LAWYER, UserRole.EMPLOYEE]:
177
+ if t.assigned_to_id != current_user.id and t.created_by_id != current_user.id:
178
+ raise HTTPException(403, "غير مصرح")
179
+ else:
180
+ if t.created_by_id != current_user.id:
181
+ raise HTTPException(403, "غير مصرح")
182
+
183
+ t.status = TicketStatus.CLOSED; t.closed_at = datetime.utcnow()
184
+ db.commit()
185
+ return {"message": "تم", "id": ticket_id}
186
+
187
+
188
+ @router.post("/{ticket_id}/messages", status_code=201)
189
+ def add_message(ticket_id: int, msg_in: MessageIn, db: Session = Depends(get_db),
190
+ current_user: User = Depends(get_current_active_user)) -> Any:
191
+ t = db.query(Ticket).filter(Ticket.id == ticket_id).first()
192
+ if not t: raise HTTPException(404, "غير موجودة")
193
+
194
+ if not current_user.is_superuser:
195
+ if current_user.role in [UserRole.LAWYER, UserRole.EMPLOYEE]:
196
+ if t.assigned_to_id != current_user.id and t.created_by_id != current_user.id:
197
+ raise HTTPException(403, "غير مصرح")
198
+ else:
199
+ if t.created_by_id != current_user.id:
200
+ raise HTTPException(403, "غير مصرح")
201
+
202
+ msg = TicketMessage(ticket_id=ticket_id, user_id=current_user.id, content=msg_in.message)
203
+ db.add(msg); t.messages_count = (t.messages_count or 0) + 1
204
+ db.commit(); db.refresh(msg)
205
+ return {"id": msg.id, "message": msg.content, "user_id": msg.user_id}
206
+
207
+
208
+ @router.delete("/{ticket_id}")
209
+ def delete_ticket(ticket_id: int, db: Session = Depends(get_db),
210
+ current_user: User = Depends(get_current_active_user)) -> Any:
211
+ t = db.query(Ticket).filter(Ticket.id == ticket_id).first()
212
+ if not t: raise HTTPException(404, "غير موجودة")
213
+
214
+ if not current_user.is_superuser and t.created_by_id != current_user.id:
215
+ raise HTTPException(403, "فقط المنشئ")
216
+
217
+ db.delete(t); db.commit()
218
+ return {"message": "تم الحذف", "id": ticket_id}
app/api/v1/endpoints/users.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Users API endpoints - FIXED with password and permissions"""
2
+ from typing import Any, Optional
3
+ from fastapi import APIRouter, Depends, HTTPException
4
+ from sqlalchemy.orm import Session
5
+ from pydantic import BaseModel, EmailStr
6
+
7
+ from app.core.database import get_db
8
+ from app.core.deps import get_current_active_user
9
+ from app.core.security import get_password_hash, verify_password
10
+ from app.models.user import User, UserRole
11
+
12
+ router = APIRouter()
13
+
14
+
15
+ class UserCreateIn(BaseModel):
16
+ email: EmailStr
17
+ password: str # FIX: was missing - NOW REQUIRED
18
+ full_name: str
19
+ full_name_ar: Optional[str] = None
20
+ phone: Optional[str] = None
21
+ role: Optional[str] = "client"
22
+ is_active: bool = True
23
+
24
+
25
+ class UserUpdateIn(BaseModel):
26
+ full_name: Optional[str] = None
27
+ full_name_ar: Optional[str] = None
28
+ phone: Optional[str] = None
29
+ license_number: Optional[str] = None
30
+ specialization: Optional[str] = None
31
+ bio: Optional[str] = None
32
+ role: Optional[str] = None
33
+ is_active: Optional[bool] = None
34
+
35
+
36
+ class PasswordChangeIn(BaseModel):
37
+ current_password: str
38
+ new_password: str
39
+
40
+
41
+ def _d(u: User) -> dict:
42
+ return {"id": u.id, "email": u.email, "full_name": u.full_name,
43
+ "full_name_ar": u.full_name_ar, "phone": u.phone,
44
+ "role": u.role.value if hasattr(u.role, "value") else str(u.role),
45
+ "is_active": u.is_active, "is_superuser": u.is_superuser,
46
+ "license_number": u.license_number, "specialization": u.specialization,
47
+ "created_at": str(u.created_at), "last_login": str(u.last_login) if u.last_login else None}
48
+
49
+
50
+ @router.get("")
51
+ def list_users(skip: int = 0, limit: int = 100, role: Optional[str] = None,
52
+ db: Session = Depends(get_db), current_user: User = Depends(get_current_active_user)) -> Any:
53
+ """List users - only admins can see all users"""
54
+ if not current_user.is_superuser:
55
+ raise HTTPException(403, "فقط المسؤول يمكنه رؤية جميع المستخدمين")
56
+ q = db.query(User)
57
+ if role:
58
+ try: q = q.filter(User.role == UserRole(role))
59
+ except ValueError: pass
60
+ return {"total": q.count(), "users": [_d(u) for u in q.offset(skip).limit(limit).all()]}
61
+
62
+
63
+ @router.post("", status_code=201)
64
+ def create_user(user_in: UserCreateIn, db: Session = Depends(get_db),
65
+ current_user: User = Depends(get_current_active_user)) -> Any:
66
+ """Create user - only admins"""
67
+ if not current_user.is_superuser:
68
+ raise HTTPException(403, "فقط المسؤول يمكنه إنشاء مستخدمين")
69
+ if db.query(User).filter(User.email == user_in.email).first():
70
+ raise HTTPException(409, "البريد الإلكتروني مسجل بالفعل")
71
+ try: role = UserRole(user_in.role)
72
+ except: role = UserRole.CLIENT
73
+
74
+ # FIX: hash the password before saving
75
+ u = User(
76
+ email=user_in.email,
77
+ full_name=user_in.full_name,
78
+ full_name_ar=user_in.full_name_ar,
79
+ phone=user_in.phone,
80
+ hashed_password=get_password_hash(user_in.password), # FIX: was missing
81
+ role=role,
82
+ is_active=user_in.is_active
83
+ )
84
+ db.add(u); db.commit(); db.refresh(u)
85
+ return _d(u)
86
+
87
+
88
+ @router.get("/profile")
89
+ def get_profile(current_user: User = Depends(get_current_active_user)) -> Any:
90
+ """Get own profile - any user"""
91
+ return _d(current_user)
92
+
93
+
94
+ @router.put("/profile")
95
+ def update_profile(user_in: UserUpdateIn, db: Session = Depends(get_db),
96
+ current_user: User = Depends(get_current_active_user)) -> Any:
97
+ """Update own profile - any user"""
98
+ for k, v in user_in.model_dump(exclude_unset=True, exclude_none=True).items():
99
+ if k == "role" and not current_user.is_superuser:
100
+ continue # Only admin can change role
101
+ if k == "role":
102
+ try: setattr(current_user, k, UserRole(v))
103
+ except: pass
104
+ else:
105
+ setattr(current_user, k, v)
106
+ db.commit(); db.refresh(current_user)
107
+ return _d(current_user)
108
+
109
+
110
+ @router.post("/profile/change-password")
111
+ def change_password(pwd_in: PasswordChangeIn, db: Session = Depends(get_db),
112
+ current_user: User = Depends(get_current_active_user)) -> Any:
113
+ """Change own password"""
114
+ if not verify_password(pwd_in.current_password, current_user.hashed_password):
115
+ raise HTTPException(400, "كلمة المرور الحالية غير صحيحة")
116
+ current_user.hashed_password = get_password_hash(pwd_in.new_password)
117
+ db.commit()
118
+ return {"message": "تم تغيير كلمة المرور بنجاح"}
119
+
120
+
121
+ @router.get("/{user_id}")
122
+ def get_user(user_id: int, db: Session = Depends(get_db),
123
+ current_user: User = Depends(get_current_active_user)) -> Any:
124
+ """Get user by ID - admin or self"""
125
+ if not current_user.is_superuser and current_user.id != user_id:
126
+ raise HTTPException(403, "غير مصرح")
127
+ u = db.query(User).filter(User.id == user_id).first()
128
+ if not u: raise HTTPException(404, "المستخدم غير موجود")
129
+ return _d(u)
130
+
131
+
132
+ @router.put("/{user_id}")
133
+ def update_user(user_id: int, user_in: UserUpdateIn, db: Session = Depends(get_db),
134
+ current_user: User = Depends(get_current_active_user)) -> Any:
135
+ """Update user - admin or self (limited)"""
136
+ if not current_user.is_superuser and current_user.id != user_id:
137
+ raise HTTPException(403, "غير مصرح")
138
+ u = db.query(User).filter(User.id == user_id).first()
139
+ if not u: raise HTTPException(404, "المستخدم غير موجود")
140
+
141
+ for k, v in user_in.model_dump(exclude_unset=True, exclude_none=True).items():
142
+ # Only admin can change role and is_active
143
+ if k in ("role", "is_active") and not current_user.is_superuser:
144
+ continue
145
+ if k == "role":
146
+ try: setattr(u, k, UserRole(v))
147
+ except: pass
148
+ else:
149
+ setattr(u, k, v)
150
+ db.commit(); db.refresh(u)
151
+ return _d(u)
152
+
153
+
154
+ @router.delete("/{user_id}")
155
+ def delete_user(user_id: int, db: Session = Depends(get_db),
156
+ current_user: User = Depends(get_current_active_user)) -> Any:
157
+ """Delete user - admin only"""
158
+ if not current_user.is_superuser:
159
+ raise HTTPException(403, "فقط المسؤول يمكنه حذف المستخدمين")
160
+ u = db.query(User).filter(User.id == user_id).first()
161
+ if not u: raise HTTPException(404, "المستخدم غير موجود")
162
+ if u.id == current_user.id:
163
+ raise HTTPException(400, "لا يمكنك حذف حسابك الخاص")
164
+ db.delete(u); db.commit()
165
+ return {"message": "تم الحذف", "id": user_id}
app/core/__init__.py ADDED
File without changes