Mobile-App-API / main.py
Binrushd-Medical-Center's picture
Update main.py
3527e92 verified
Raw History Blame Contribute Delete
69.3 kB
# main.py from fastapi import FastAPI, Form, HTTPException, Depends, Header, Form, Query from fastapi.security import OAuth2PasswordBearer from pydantic import BaseModel, EmailStr import typing from typing import Any, Dict, Optional import os, requests, random, string, jwt from datetime import datetime, timedelta, timezone from passlib.context import CryptContext from pathlib import Path import json from typing import Optional from fastapi import Query from datetime import date # ====== Config ====== SUPA_URL = os.getenv("SUPABASE_URL", "https://hirmgvjpdifudkiugtyr.supabase.co").rstrip("/") SUPA_KEY = os.getenv("SUPABASE_ANON_KEY", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imhpcm1ndmpwZGlmdWRraXVndHlyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjA0ODE0NDksImV4cCI6MjA3NjA1NzQ0OX0.Ti4u1FyzorR80Fz1LzLFRHKu_RD2_rp-C8wzf47hOe4") GAS_URL = os.getenv("GAS_MAIL_URL","https://script.google.com/macros/s/AKfycbxzj7vfMpkzAissmvXjazWZMRTvhB2tBG3xodYeq8wYQzraBekA5NupIbeJLaGUh3l85g/exec") GAS_SECRET = os.getenv("GAS_SECRET", "CHANGE_ME_STRONG_SECRET") JWT_SECRET = os.getenv("JWT_SECRET", "change_me") JWT_ALG = os.getenv("JWT_ALG", "HS256") HEADERS = { "apikey": SUPA_KEY, "Authorization": f"Bearer {SUPA_KEY}", "Content-Type": "application/json", "Accept": "application/json", } pwd = CryptContext(schemes=["bcrypt_sha256"], deprecated="auto") oauth2 = OAuth2PasswordBearer(tokenUrl="/api/auth/login") app = FastAPI(title="BinRushd Auth (Supabase REST)") BASE_DIR = Path(__file__).resolve().parent # ====== Helpers ====== def now_utc() -> datetime: return datetime.now(timezone.utc) def iso(dt: datetime) -> str: return dt.astimezone(timezone.utc).isoformat() def parse_iso_utc(value: str) -> datetime: """ يحوّل أي نص ISO إلى datetime ب timezone=UTC. لو السلسلة بدون timezone، نعتبرها UTC. يقبل قيم زي: '2025-10-16T05:21:00', '...Z', '...+00:00' """ if not value: return now_utc() s = value.strip() if s.endswith("Z"): s = s[:-1] + "+00:00" try: dt = datetime.fromisoformat(s) except Exception: # لو فورمات مش متوقع: رجّع وقت قديم قوي علشان نعتبره منتهي return now_utc() - timedelta(days=3650) if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) return dt.astimezone(timezone.utc) def create_access_token(sub: str, scopes=None, minutes=60) -> str: now = now_utc() payload = {"sub": sub, "scopes": scopes or [], "iat": int(now.timestamp()), "exp": int((now + timedelta(minutes=minutes)).timestamp())} return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALG) def decode_token(tok: str): return jwt.decode(tok, JWT_SECRET, algorithms=[JWT_ALG]) def eq(col, val): return {col: f"eq.{val}"} def supa_select(table: str, params: dict): url = f"{SUPA_URL}/rest/v1/{table}" try: r = requests.get(url, headers=HEADERS, params=params, timeout=30) # ✅ LOG print( f"[supa_select] table={table} status={r.status_code} " f"url={r.url} " f"resp_len={len(r.text) if r.text else 0}" ) # لو فيه خطأ اطبع محتوى الرد if r.status_code >= 400: print(f"[supa_select] ERROR body={r.text}") r.raise_for_status() data = r.json() # ✅ LOG: count + sample ids لو موجودة if isinstance(data, list): ids = [x.get("id") for x in data if isinstance(x, dict) and "id" in x] print(f"[supa_select] table={table} rows={len(data)} ids_sample={ids[:10]}") else: print(f"[supa_select] table={table} non_list_json_type={type(data)}") return data except Exception as e: print(f"[supa_select] EXC table={table} err={e}") raise def supa_insert(table: str, obj: dict): r = requests.post(f"{SUPA_URL}/rest/v1/{table}", headers={**HEADERS,"Prefer":"return=representation"}, json=obj, timeout=30) r.raise_for_status(); return r.json()[0] def supa_insert_safe(table: str, obj: dict): try: r = requests.post( f"{SUPA_URL}/rest/v1/{table}", headers={**HEADERS, "Prefer": "return=representation"}, json=obj, timeout=30 ) if r.status_code >= 400: # اطبع الرسالة للتشخيص واحفظها في اللوجات print(f"[supa_insert_safe] {table} -> {r.status_code} {r.text}") return None data = r.json() return data[0] if isinstance(data, list) and data else data except Exception as e: print(f"[supa_insert_safe] EXC {table}: {e}") return None def supa_update(table: str, filters: dict, obj: dict): r = requests.patch(f"{SUPA_URL}/rest/v1/{table}", headers={**HEADERS,"Prefer":"return=representation"}, params=filters, json=obj, timeout=30) r.raise_for_status(); return r.json() def supa_delete(table: str, filters: dict): r = requests.delete(f"{SUPA_URL}/rest/v1/{table}", headers=HEADERS, params=filters, timeout=30) r.raise_for_status(); return True def send_otp_email(email: str, otp: str, purpose: str, name: typing.Optional[str] = None): payload = { "key": GAS_SECRET, # ← المهم "email": email, "otp": otp, "purpose": purpose, # "verify" أو "reset" "name": name or "عميلنا الكريم", } try: r = requests.post(GAS_URL, json=payload, timeout=30) r.raise_for_status() supa_insert_safe("email_logs", { "user_id": None, "recipient": email, "template": f"{purpose}_otp", "status": "sent", "payload": payload, "created_at": iso(now_utc()) }) except Exception as e: print("[send_otp_email] send fail:", e) supa_insert_safe("email_logs", { "user_id": None, "recipient": email, "template": f"{purpose}_otp", "status": "failed", "payload": payload, "error": str(e), "created_at": iso(now_utc()) }) def require_scopes(scopes_required=None): scopes_required = scopes_required or [] def _dep(token: str = Depends(oauth2)): try: payload = decode_token(token) except Exception: raise HTTPException(401, "Invalid token") token_scopes = payload.get("scopes", []) if any(s not in token_scopes for s in scopes_required): raise HTTPException(403, "Insufficient scope") return payload return _dep def latest_valid_otp(user_id: int, purpose: str): rows = supa_select("user_otps", {**eq("user_id", user_id), **eq("purpose", purpose), "order":"created_at.desc", "limit":"1"}) return rows[0] if rows else None def rotate_refresh(user_id: int, device: Optional[str], ua: Optional[str]): raw = ''.join(random.choices(string.ascii_letters + string.digits, k=64)) hashed = pwd.hash(raw) rec = supa_insert("user_sessions", { "user_id": user_id, "refresh_token_hash": hashed, "device_name": device, "user_agent": ua, "expires_at": iso(now_utc() + timedelta(days=14)), "created_at": iso(now_utc()) }) return raw, rec # ====== Permanent Token helpers (testing-only) ====== def create_permanent_token_for_email(email: str, scopes=None, note: Optional[str] = None): """ ينشئ JWT بدون exp، ويخزّن هاشه في user_permanent_tokens. يرجّع (token, rec) حيث rec هو الريكورد المُدخل. """ scopes = scopes or ["user"] # هات المستخدم rows = supa_select("users", {**eq("email", email), "select": "id", "limit": "1"}) if not rows: raise HTTPException(404, "User not found") uid = rows[0]["id"] # أنشئ توكن بدون exp now = now_utc() payload = { "sub": email, "scopes": scopes, "iat": int(now.timestamp()), # بدون exp } token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALG) # خزّن الهاش فقط rec = supa_insert("user_permanent_tokens", { "user_id": uid, "token_hash": pwd.hash(token), "scopes": scopes, "note": note, "issued_by": "api", "created_at": iso(now), }) return token, rec def revoke_permanent_token_by_id(token_id: int): """ يعلّم التوكن كـ revoked. """ return supa_update("user_permanent_tokens", eq("id", token_id), { "revoked_at": iso(now_utc()) }) # ====== Schemas ====== class LoginIn(BaseModel): email: EmailStr password: str class EmailOTP(BaseModel): email: EmailStr otp: str class ResetPasswordIn(BaseModel): password: str password_confirmation: str class AvatarIn(BaseModel): avatar_url: Optional[str] = None # URL كامل أو None # ====== Endpoints ====== @app.post("/api/auth/register") def register( email: EmailStr = Form(...), password: str = Form(...), password_confirmation: str = Form(...), fname: Optional[str] = Form(None), lname: Optional[str] = Form(None), mobile: Optional[str] = Form(None), ): if password != password_confirmation: raise HTTPException(422, "Passwords do not match") existed = supa_select("users", {**eq("email", email), "select":"id", "limit":"1"}) if existed: raise HTTPException(422, "Email already exists") user = supa_insert("users", { "email": email, "password": pwd.hash(password), "fname": fname, "lname": lname, "mobile": mobile, "role": "client", "is_active": True, "created_at": iso(now_utc()) }) otp = f"{random.randint(100000, 999999)}" supa_insert("user_otps", { "user_id": user["id"], "purpose": "verify", "code_hash": pwd.hash(otp), "expires_at": iso(now_utc() + timedelta(minutes=3)), "attempts": 0, "created_at": iso(now_utc()) }) send_otp_email(email, otp, "verify", user.get("fname")) token = create_access_token(sub=str(email), scopes=["verifyAccount"], minutes=7) return {"access_token": token, "token_type": "bearer"} @app.post("/api/auth/register_test") def register_test( email: EmailStr = Form(...), password: str = Form(...), password_confirmation: str = Form(...), fname: Optional[str] = Form(None), lname: Optional[str] = Form(None), mobile: Optional[str] = Form(None), ): """ نسخة اختبار من التسجيل — ترجع كود الـ OTP في الـ response. ⚠️ لا تُستخدم في الإنتاج لأنها تكشف كود التحقق. """ if password != password_confirmation: raise HTTPException(422, "Passwords do not match") existed = supa_select("users", {**eq("email", email), "select": "id", "limit": "1"}) if existed: raise HTTPException(422, "Email already exists") user = supa_insert("users", { "email": email, "password": pwd.hash(password), "fname": fname, "lname": lname, "mobile": mobile, "role": "client", "is_active": True, "created_at": iso(now_utc()) }) otp = f"{random.randint(100000, 999999)}" supa_insert("user_otps", { "user_id": user["id"], "purpose": "verify", "code_hash": pwd.hash(otp), "expires_at": iso(now_utc() + timedelta(minutes=3)), "attempts": 0, "created_at": iso(now_utc()) }) send_otp_email(email, otp, "verify", user.get("fname")) token = create_access_token(sub=str(email), scopes=["verifyAccount"], minutes=7) return { "access_token": token, "token_type": "bearer", "message": "تم إرسال كود OTP على بريدك الإلكتروني", "otp": otp # ← للـ testing فقط } @app.post("/api/auth/resend_otp") def resend_otp(payload=Depends(require_scopes(["verifyAccount"]))): email = payload["sub"] u = supa_select("users", {**eq("email", email), "select":"id,fname", "limit":"1"}) if not u: raise HTTPException(404, "User not found") user = u[0] otp = f"{random.randint(100000, 999999)}" supa_insert("user_otps", { "user_id": user["id"], "purpose":"verify", "code_hash": pwd.hash(otp), "expires_at": iso(now_utc() + timedelta(minutes=3)), "attempts": 0, "created_at": iso(now_utc()) }) send_otp_email(email, otp, "verify", user.get("fname")) return {"message":"OTP sent"} @app.post("/api/auth/check_otp") def check_otp(body: EmailOTP, payload=Depends(require_scopes(["verifyAccount"]))): try: # تحقق من أن البريد في التوكن يطابق البريد المُرسل if body.email.lower() != payload["sub"].lower(): return {"status": 400, "message": "التوكن غير صالح"} # جلب المستخدم u = supa_select("users", { **eq("email", body.email), "select": "id,email,fname,lname,mobile,role,email_verified_at", "limit": "1" }) if not u: return {"status": 400, "message": "المستخدم غير موجود"} user = u[0] rec = latest_valid_otp(user["id"], "verify") # تحقق من الكود if not rec: return {"status": 400, "message": "كود التحقق غير موجود"} if rec.get("consumed_at"): return {"status": 400, "message": "تم استخدام الكود من قبل"} if parse_iso_utc(rec["expires_at"]) < now_utc(): return {"status": 400, "message": "انتهت صلاحية الكود"} if not pwd.verify(body.otp, rec["code_hash"]): supa_update("user_otps", eq("id", rec["id"]), { "attempts": (rec.get("attempts") or 0) + 1 }) return {"status": 400, "message": "كود التحقق غير صحيح"} # ✅ لو الكود صحيح supa_update("user_otps", eq("id", rec["id"]), { "consumed_at": iso(now_utc()) }) supa_update("users", eq("id", user["id"]), { "email_verified_at": iso(now_utc()) }) access = create_access_token(sub=user["email"], scopes=["user"], minutes=60*24) refresh, _ = rotate_refresh(user["id"], device="mobile", ua=None) return { "status": 200, "message": "تم تفعيل حسابك بنجاح!", "access_token": access, "refresh_token": refresh, "user": user } except Exception as e: print("[check_otp] ERROR:", e) return {"status": 400, "message": "رمز التحقق غير صحيح، يُرجى المحاولة مرة أخرى."} @app.post("/api/auth/login") def login(body: LoginIn): rows = supa_select( "users", {**eq("email", body.email), "select": "id,email,password,email_verified_at,fname,lname,mobile,role", "limit": "1"} ) # أي فشل => رسالة عامة (محمية ضد enumeration) if not rows: return {"is_verified": False, "message": "بيانات الدخول غير صحيحة"} user = rows[0] # تحقق من الباسورد والإيميل المفعل if not pwd.verify(body.password, user["password"]): return {"is_verified": False, "message": "بيانات الدخول غير صحيحة"} if not user.get("email_verified_at"): return {"is_verified": False, "message": "بيانات الدخول غير صحيحة"} # ناجح → أنشئ توكنات وأعد البيانات access = create_access_token(sub=user["email"], scopes=["user"], minutes=60*24) refresh, _ = rotate_refresh(user["id"], device="mobile", ua=None) return { "is_verified": True, "message": "تم تسجيل الدخول بنجاح", "access_token": access, "refresh_token": refresh, "user": user } @app.post("/api/auth/login_never_expire") def login_never_expire(body: LoginIn): """ يسجّل دخول ويرجع توكن دائم (بدون exp). - status: 200 عند النجاح، 400 عند الفشل. - يوضّح نوع الخطأ (إيميل أو كلمة سر). """ # 🔹 تحقق من وجود المستخدم rows = supa_select( "users", { **eq("email", body.email), "select": "id,email,password,email_verified_at,fname,lname,mobile,role", "limit": "1", }, ) if not rows: return { "status": 400, "is_verified": False, "message": "البريد الإلكتروني غير صحيح" } user = rows[0] # 🔹 تحقق من كلمة السر if not pwd.verify(body.password, user["password"]): return { "status": 400, "is_verified": False, "message": "كلمة المرور غير صحيحة" } # 🔹 تحقق من تفعيل البريد if not user.get("email_verified_at"): return { "status": 400, "is_verified": False, "message": "الحساب غير مفعل، يُرجى التحقق من البريد الإلكتروني" } # ✅ نجاح → إنشاء توكن دائم بدون exp token, rec = create_permanent_token_for_email( email=user["email"], scopes=["user"], note="login_never_expire_success" ) return { "status": 200, "is_verified": True, "message": "تم تسجيل الدخول بنجاح", "access_token": token, # ← دائم (no exp) "token_type": "bearer", "expires": "never", "permanent_token_id": rec["id"], "issued_at": rec.get("created_at"), "user": user } @app.post("/api/auth/never_expire") def never_expire(payload=Depends(require_scopes(["user"])), note: Optional[str] = Form(None)): """ ينشئ access token دائم (بدون exp) ويُخزّن هاشه في user_permanent_tokens. ⚠️ للتجارب فقط. """ token, rec = create_permanent_token_for_email(payload["sub"], scopes=["user"], note=note) return { "access_token": token, "token_type": "bearer", "expires": "never", "id": rec["id"], "issued_at": rec.get("created_at"), "note": rec.get("note"), } @app.post("/api/auth/permanent/revoke") def permanent_revoke(token_id: int = Form(...), payload=Depends(require_scopes(["user"]))): """ إلغاء (revocation) توكن دائم محدّد بـ id. """ # (اختياري) تتأكد إن الـ token_id يخص نفس المستخدم: row = supa_select("user_permanent_tokens", {**eq("id", token_id), "select": "id,user_id,revoked_at", "limit": "1"}) if not row: raise HTTPException(404, "Token not found") # جيب user_id الخاص بصاحب الطلب me = supa_select("users", {**eq("email", payload["sub"]), "select": "id", "limit": "1"}) if not me: raise HTTPException(404, "User not found") if row[0]["user_id"] != me[0]["id"]: raise HTTPException(403, "Not your token") if row[0].get("revoked_at"): return {"message": "Already revoked"} revoke_permanent_token_by_id(token_id) return {"message": "Revoked"} @app.post("/api/auth/token/refresh") def token_refresh(refresh_token: str = Form(...)): sessions = supa_select("user_sessions", {"select":"id,user_id,refresh_token_hash,expires_at,revoked_at", "order":"created_at.desc"}) matched = None for s in sessions: try: if s.get("revoked_at"): continue if parse_iso_utc(s["expires_at"]) < now_utc(): continue if pwd.verify(refresh_token, s["refresh_token_hash"]): matched = s; break except Exception: continue if not matched: raise HTTPException(401, "Invalid refresh token") u = supa_select("users", {**eq("id", matched["user_id"]), "select":"email", "limit":"1"})[0] access = create_access_token(sub=u["email"], scopes=["user"], minutes=60*24) supa_update("user_sessions", eq("id", matched["id"]), {"revoked_at": iso(now_utc())}) new_refresh, _ = rotate_refresh(matched["user_id"], device="mobile", ua=None) return {"access_token": access, "refresh_token": new_refresh} @app.post("/api/auth/profile") def profile(payload=Depends(require_scopes(["user"]))): u = supa_select("users", {**eq("email", payload["sub"]), "select":"id,email,fname,lname,mobile,role,email_verified_at,avatar_url", "limit":"1"}) if not u: raise HTTPException(404, "User not found") return {"user": u[0]} @app.post("/api/user/avatar/set") def set_avatar(avatar_url: str = Form(...), payload=Depends(require_scopes(["user"]))): me = supa_select("users", {**eq("email", payload["sub"]), "select":"id", "limit":"1"}) if not me: raise HTTPException(404, "User not found") supa_update("users", eq("id", me[0]["id"]), {"avatar_url": avatar_url, "updated_at": iso(now_utc())}) return {"message": "Avatar updated", "avatar_url": avatar_url} @app.post("/api/user/avatar/remove") def remove_avatar(payload=Depends(require_scopes(["user"]))): me = supa_select("users", {**eq("email", payload["sub"]), "select":"id", "limit":"1"}) if not me: raise HTTPException(404, "User not found") supa_update("users", eq("id", me[0]["id"]), {"avatar_url": None, "updated_at": iso(now_utc())}) return {"message": "Avatar removed"} @app.post("/api/auth/logout") def logout(payload=Depends(require_scopes(["user"]))): return {"message": "Logout Successfully"} @app.post("/api/auth/logout-all") def logout_all(payload=Depends(require_scopes(["user"]))): u = supa_select("users", {**eq("email", payload["sub"]), "select":"id", "limit":"1"})[0] supa_delete("user_sessions", eq("user_id", u["id"])) return {"message":"All sessions revoked"} @app.post("/api/auth/forget_password") def forget_password(email: EmailStr = Form(...)): u = supa_select("users", {**eq("email", email), "select":"id,fname", "limit":"1"}) if not u: raise HTTPException(404, "User not found") user = u[0] otp = f"{random.randint(100000, 999999)}" supa_insert("user_otps", { "user_id": user["id"], "purpose":"reset", "code_hash": pwd.hash(otp), "expires_at": iso(now_utc() + timedelta(minutes=3)), "attempts": 0, "created_at": iso(now_utc()) }) send_otp_email(email, otp, "reset", user.get("fname")) return {"message":"Please check your email"} @app.post("/api/auth/check_forget_password") def check_forget_password(body: EmailOTP): u = supa_select("users", {**eq("email", body.email), "select":"id", "limit":"1"}) if not u: raise HTTPException(404, "User not found") user = u[0] rec = latest_valid_otp(user["id"], "reset") if not rec: raise HTTPException(400, "OTP not found") if rec.get("consumed_at"): raise HTTPException(400, "OTP already used") if parse_iso_utc(rec["expires_at"]) < now_utc(): raise HTTPException(400, "OTP expired") if not pwd.verify(body.otp, rec["code_hash"]): supa_update("user_otps", eq("id", rec["id"]), {"attempts": (rec.get("attempts") or 0) + 1}) raise HTTPException(400, "Wrong OTP") supa_update("user_otps", eq("id", rec["id"]), {"consumed_at": iso(now_utc())}) token = create_access_token(sub=body.email, scopes=["reset_password"], minutes=30) return {"token": token, "message": "Use this token to reset your password"} @app.post("/api/auth/reset_password") def reset_password(body: ResetPasswordIn, authorization: str = Header(None)): if not authorization or not authorization.lower().startswith("bearer "): raise HTTPException(401, "Missing token") payload = decode_token(authorization.split(" ",1)[1]) if "reset_password" not in payload.get("scopes", []): raise HTTPException(403, "Insufficient scope") if body.password != body.password_confirmation: raise HTTPException(422, "Passwords do not match") u = supa_select("users", {**eq("email", payload["sub"]), "select":"id", "limit":"1"})[0] supa_update("users", eq("id", u["id"]), {"password": pwd.hash(body.password)}) supa_delete("user_sessions", eq("user_id", u["id"])) return {"message":"password changed successfully!"} # ====== Doctors ====== @app.get("/api/doctors") def list_doctors(limit: int = 100, offset: int = 0, order: str = "id.asc"): req_id = "".join(random.choices(string.ascii_lowercase + string.digits, k=8)) t0 = datetime.now(timezone.utc) print(f"[doctors] START req_id={req_id} at={iso(t0)} limit={limit} offset={offset} order={order}") params = { "select": "id,fname,lname,brief,image,created_at", "limit": str(limit), "offset": str(offset), "order": order, } try: rows = supa_select("doctors", params) ids = [r.get("id") for r in rows if isinstance(r, dict)] print( f"[doctors] OK req_id={req_id} rows={len(rows)} " f"min_id={min(ids) if ids else None} max_id={max(ids) if ids else None} " f"ids_tail={ids[-10:] if ids else []}" ) dt_ms = int((datetime.now(timezone.utc) - t0).total_seconds() * 1000) print(f"[doctors] END req_id={req_id} took_ms={dt_ms}") return {"count": len(rows), "data": rows} except Exception as e: dt_ms = int((datetime.now(timezone.utc) - t0).total_seconds() * 1000) print(f"[doctors] FAIL req_id={req_id} took_ms={dt_ms} err={e}") raise HTTPException(500, "Failed to fetch doctors") @app.get("/api/doctors/debug") def doctors_debug(): """ تشخيص سريع: - يجيب count الكلي - يجيب ids محددة (اللي ضفناها) ويقول لقاهم ولا لأ """ new_ids = [18,19,21,22,23,24,25,26,27,28,29,30,32,33] # 1) total count total = supa_select("doctors", {"select": "id", "limit": "10000", "order": "id.asc"}) total_ids = [x.get("id") for x in total if isinstance(x, dict)] # 2) fetch only new ids using in.(...) ids_csv = ",".join(str(i) for i in new_ids) fetched = supa_select("doctors", { "select": "id,fname,lname", "id": f"in.({ids_csv})", "limit": str(len(new_ids)), "order": "id.asc" }) fetched_ids = [x.get("id") for x in fetched if isinstance(x, dict)] missing = [i for i in new_ids if i not in set(fetched_ids)] print(f"[doctors_debug] total_rows={len(total_ids)} fetched_new={fetched_ids} missing_new={missing}") return { "total_count": len(total_ids), "new_ids_expected": new_ids, "new_ids_found": fetched_ids, "missing_new_ids": missing } @app.get("/api/doctors/with-favorites") def list_doctors_with_favorites( payload=Depends(require_scopes(["user"])), limit: int = 100, offset: int = 0, order: str = "id.asc", client_email: Optional[str] = None, client_mobile: Optional[str] = None, only_favorites: bool = False, # اختياري: رجّع المفضلة فقط ): """ يرجّع قائمة الدكاترة + is_favorite لكل دكتور بحسب مفضّلات العميل. تحديد العميل: - افتراضيًا: من التوكن (payload["sub"]) كـ client_email - أو صراحةً عبر client_email / client_mobile (اختياري) """ # 1) هات الدكاترة docs_params = { "select": "id,fname,lname,brief,image,created_at", "limit": str(limit), "offset": str(offset), "order": order, } doctors = supa_select("doctors", docs_params) # 2) حدّد العميل client_email = (client_email or "").strip() or payload.get("sub") client_mobile = (client_mobile or "").strip() or None if not client_email and not client_mobile: raise HTTPException(400, "لم يتم تحديد العميل: استخدم التوكن أو أرسل client_email/client_mobile") # 3) هات المفضّلات (doctor_id فقط) fav_params = {"select": "doctor_id", "limit": "10000", "order": "created_at.desc"} if client_email: fav_params["client_email"] = f"eq.{client_email}" if client_mobile: fav_params["client_mobile"] = f"eq.{client_mobile}" favorites = supa_select("favorites", fav_params) fav_ids = {row.get("doctor_id") for row in favorites if row.get("doctor_id") is not None} # 4) شكّل الخرج بالشكل المطلوب + فلتر اختياري shaped = [] for d in doctors: item = { "id": d.get("id"), "fname": d.get("fname"), "lname": d.get("lname"), "brief": d.get("brief"), "image": d.get("image"), "created_at": d.get("created_at"), "is_favorite": d.get("id") in fav_ids, } if only_favorites and not item["is_favorite"]: continue shaped.append(item) return {"count": len(shaped), "data": shaped} @app.get("/api/doctors/{doctor_id}/details") def doctor_details(doctor_id: int, payload=Depends(require_scopes(["user"]))): """ يرجّع تفاصيل الطبيب + الصورة والاسم الكامل و is_favorite اعتمادًا فقط على التوكن (email من payload['sub']). """ client_email = payload.get("sub") if not client_email: raise HTTPException(401, "Missing client identity") # 1) تفاصيل الطبيب (من جدول doctor_details) det_rows = supa_select("doctor_details", { **eq("doctor_id", doctor_id), "select": 'doctor_id,gender,qualifications,experience,"Speciality","Degree",phone,email,highligthed,branches,created_at', "limit": "1", }) if not det_rows: raise HTTPException(404, "Doctor details not found") details = det_rows[0] # 2) بيانات الطبيب الأساسية + الصورة لتجهيز full_name/image doc_rows = supa_select("doctors", { **eq("id", doctor_id), "select": "id,fname,lname,image", "limit": "1", }) if not doc_rows: raise HTTPException(404, "Doctor not found") doc = doc_rows[0] full_name = f"{(doc.get('fname') or '').strip()} {(doc.get('lname') or '').strip()}".strip() image = doc.get("image") # 3) هل مفضّل لهذا العميل؟ (من جدول favorites) fav_rows = supa_select("favorites", { **eq("client_email", client_email), **eq("doctor_id", doctor_id), "select": "id", "limit": "1", }) is_favorite = bool(fav_rows) # 4) دمج وإرجاع return { **details, "image": image, "full_name": full_name, "is_favorite": is_favorite, } @app.get("/api/branches/{branch_id}/doctors") def branch_doctors_min(branch_id: int): """ يرجّع JSON مختصر لفرع معيّن من branches_details.json: { "id": <branch_id>, "name": <branch_name or fallback>, "doctors": [ {id, name}, ... ] } يعتمد فقط على ملف branches_details.json. """ path = BASE_DIR / "branches_details.json" if not path.exists(): raise HTTPException(500, "branches_details.json not found") try: info = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, "branches_details.json contains invalid JSON") # قد يكون الشكل {"message": "...", "data": [ ... ]} أو مباشرة [ ... ] items = info.get("data", info) branch = None if isinstance(items, list): for it in items: if it.get("id") == branch_id: branch = it break elif isinstance(items, dict): # في حال كانت مفاتيحها ids كنصوص branch = items.get(str(branch_id)) if not branch: raise HTTPException(404, f"Branch {branch_id} not found") # لو الاسم مش موجود في details نرجّع اسم افتراضي branch_name = branch.get("name") or f"فرع رقم {branch_id}" doctors = branch.get("doctors", []) # نرجّع فقط الحقول المطلوبة return { "message": "الأطباء المتاحون في هذا الفرع", "id": branch_id, "name": branch_name, "doctors": doctors } @app.get("/api/doctors/{doctor_id}/branches") def doctor_branches(doctor_id: int): """ يرجّع فروع الطبيب من جدول doctor_details (عمود jsonb اسمه branches). الاستعلام: doctor_id = <id> الخرج: { "message": "Doctor branches fetched successfully", "doctor_id": <int>, "count": <int>, "branches": [ { "id": ..., "name": ... , ... }, ... ] } """ rows = supa_select("doctor_details", { **eq("doctor_id", doctor_id), "select": "doctor_id,branches", "limit": "1" }) if not rows: raise HTTPException(404, "Doctor details not found") rec = rows[0] branches = rec.get("branches") or [] # تأكيد النوع لو الـ jsonb فاضي أو None if not isinstance(branches, list): try: # في حال اتت كنص JSON (نادر) branches = json.loads(branches) if isinstance(branches, str) else [] except Exception: branches = [] return { "message": "الفروع التي يعمل بها هذا الطبيب", "doctor_id": doctor_id, "count": len(branches), "branches": branches } # ====== DDepartments ====== @app.get("/api/departments") def list_departments(): """ يرجّع جميع الأقسام (البيانات المختصرة فقط). """ path = BASE_DIR / "departments.json" if not path.exists(): raise HTTPException(500, "departments.json not found") try: data = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, "departments.json contains invalid JSON") return { "count": len(data.get("data", [])) if isinstance(data, dict) else len(data), "data": data.get("data", data) } @app.get("/api/departments/{department_id}/details") def department_details(department_id: int): """ يرجّع تفاصيل قسم واحد من ملف departments_info.json. """ path = BASE_DIR / "departments_info.json" if not path.exists(): raise HTTPException(500, "departments_info.json not found") try: info = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, "departments_info.json contains invalid JSON") # يدعم الشكل {"departments": {"1": {...}, "2": {...}}} if isinstance(info, dict) and "departments" in info: data = info["departments"].get(str(department_id)) if not data: raise HTTPException(404, f"Department {department_id} not found") return data # يدعم لو كان info عبارة عن list if isinstance(info, list): for d in info: data_id = d.get("data", {}).get("id") if data_id == department_id: return d raise HTTPException(404, f"Department {department_id} not found") @app.get("/api/departments/{department_id}/field") def department_field(department_id: int, key: str): """ يرجّع قيمة حقل معيّن من داخل تفاصيل القسم. يدعم Dot-path (مثلاً branch.name أو branch.worktimes.sunday). """ path = BASE_DIR / "departments_info.json" if not path.exists(): raise HTTPException(500, "departments_info.json not found") info = json.loads(path.read_text(encoding="utf-8")) entry = None if isinstance(info, dict) and "departments" in info: entry = info["departments"].get(str(department_id)) elif isinstance(info, list): for d in info: if d.get("data", {}).get("id") == department_id: entry = d break if not entry: raise HTTPException(404, f"Department {department_id} not found") data = entry.get("data") if not data: raise HTTPException(500, f"Invalid structure for department {department_id}") # دعم الـ dot-path value = data for part in key.split("."): if isinstance(value, dict) and part in value: value = value[part] elif isinstance(value, list) and part.isdigit() and int(part) < len(value): value = value[int(part)] else: raise HTTPException(404, f"Field '{key}' not found") return {"id": department_id, "key": key, "value": value} # ====== Branches ====== @app.get("/api/branches") def list_branches_summary(): """ يرجّع ملخص الفروع من branches_summary.json (id, name, brief, image) """ path = BASE_DIR / "branches_summary.json" if not path.exists(): raise HTTPException(500, "branches_summary.json not found") try: data = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, "branches_summary.json contains invalid JSON") payload = data.get("data", data) return {"count": len(payload), "data": payload} @app.get("/api/branches/{branch_id}") def branch_details(branch_id: int): """ يرجّع تفاصيل فرع واحد من branches_details.json مع إلحاق صورة كل دكتور من جدول doctors (حقل image). """ path = BASE_DIR / "branches_details.json" if not path.exists(): raise HTTPException(500, "branches_details.json not found") try: info = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, "branches_details.json contains invalid JSON") items = info.get("data", info) branch = None if isinstance(items, list): for it in items: if it.get("id") == branch_id: branch = it break elif isinstance(items, dict): branch = items.get(str(branch_id)) if not branch: raise HTTPException(404, f"Branch {branch_id} not found") # ---- إلحاق الصور لكل دكتور ---- doctors_list = branch.get("doctors") or [] # بنقبل id أو doctor_id (للتماشي مع أي فورمات) doc_ids = [] for d in doctors_list: did = d.get("id") or d.get("doctor_id") if isinstance(did, int): doc_ids.append(did) doc_ids = sorted(set(doc_ids)) images_map = {} if doc_ids: # نجلب الصور دفعة واحدة ids_csv = ",".join(str(i) for i in doc_ids) try: rows = supa_select("doctors", { "select": "id,image", "id": f"in.({ids_csv})", "limit": str(len(doc_ids)) }) images_map = {r["id"]: r.get("image") for r in rows} except Exception as e: # لو حصل خطأ، نكمل بدون صور بدل ما نفشل كليًا print("[branch_details] fetch doctors images failed:", e) images_map = {} # نضيف image لكل عنصر في القائمة enriched_doctors = [] for d in doctors_list: did = d.get("id") or d.get("doctor_id") # نُبقي على نفس الشكل الأصلي + نلحق الـ image enriched = dict(d) if isinstance(did, int): enriched["image"] = images_map.get(did) else: enriched["image"] = None enriched_doctors.append(enriched) # نرجّع نفس الهيكل القديم، لكن مع doctors مُثرى بالصور result = dict(branch) result["doctors"] = enriched_doctors return {"message": "Branch Fetched Successfully", "data": result} # ====== Blog ====== @app.get("/api/blog") def list_blog_summary(): """ يرجّع ملخص التدوينات (العنوان، الصورة فقط) من Blog_summary.json """ path = BASE_DIR / "Blog_summary.json" if not path.exists(): raise HTTPException(500, "Blog_summary.json not found") try: data = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, "Blog_summary.json contains invalid JSON") payload = data.get("data", data) return {"count": len(payload), "data": payload} @app.get("/api/blog/{post_id}") def blog_post_details(post_id: int): """ يرجّع تفاصيل تدوينة واحدة (المحتوى فقط) من Blog_posts_details.json """ path = BASE_DIR / "Blog_posts_details.json" if not path.exists(): raise HTTPException(500, "Blog_posts_details.json not found") try: info = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, "Blog_posts_details.json contains invalid JSON") items = info.get("data", info) if isinstance(items, list): for it in items: if it.get("id") == post_id: return {"message": "Post Fetched Successfully", "data": it} elif isinstance(items, dict) and str(post_id) in items: return {"message": "Post Fetched Successfully", "data": items[str(post_id)]} raise HTTPException(404, f"Post {post_id} not found") # ====== Offers ====== @app.get("/api/offers") def list_offers(): """ يرجّع كل العروض (offers + campaigns) كما هي من ملف offers.json """ path = BASE_DIR / "offers.json" if not path.exists(): raise HTTPException(500, "offers.json not found") try: raw = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, "offers.json contains invalid JSON") # لو الملف بنفس البنية المرسلة (message + data) نرجّعه كما هو: if isinstance(raw, dict) and "data" in raw: return raw # fallback بسيط return {"message": "Offers Fetched Successfully", "data": raw} @app.get("/api/offers/{item_id}") def get_offer_by_id(item_id: int): """ يرجّع عنصر واحد بالـ id — يبحث أولاً في campaigns ثم في offers. """ path = BASE_DIR / "offers.json" if not path.exists(): raise HTTPException(500, "offers.json not found") try: raw = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, "offers.json contains invalid JSON") payload = raw.get("data", raw) if isinstance(raw, dict) else {} campaigns = payload.get("campaigns", []) if isinstance(payload, dict) else [] offers = payload.get("offers", []) if isinstance(payload, dict) else [] # دور في الـ campaigns for c in campaigns: if c.get("id") == item_id: return {"message": "Campaign Fetched Successfully", "data": c} # دور في الـ offers for o in offers: if o.get("id") == item_id: return {"message": "Offer Fetched Successfully", "data": o} raise HTTPException(404, f"Item with id={item_id} not found") # ====== Home ====== @app.get("/api/home") def get_home(): """ يرجّع بيانات الصفحة الرئيسية (العروض + عن المركز + الأقسام + الفروع + الأطباء) من ملف home.json """ path = BASE_DIR / "home.json" if not path.exists(): raise HTTPException(500, "home.json not found") try: data = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, "home.json contains invalid JSON") # تأكد من أن البنية تحتوي على message + data if isinstance(data, dict) and "data" in data: return data # fallback لو مش موجود message return {"message": "Home Fetched Successfully", "data": data} # ====== About Us ====== @app.get("/api/about") def get_about(): """ يرجّع بيانات صفحة 'من نحن' من ملف aboutus.json """ path = BASE_DIR / "about_us.json" if not path.exists(): raise HTTPException(500, "aboutus.json not found") try: data = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, "aboutus.json contains invalid JSON") # لو الملف فيه message + data زي باقي الملفات if isinstance(data, dict) and "data" in data: return data # fallback بسيط لو الملف عبارة عن كائن واحد return {"message": "About Fetched Successfully", "data": data} # ====== Reservations ====== # ====== Bookings Schemas ====== from pydantic import BaseModel from typing import Optional, Literal class BookingIn(BaseModel): # بيانات العميل client_name: Optional[str] = None client_mobile: Optional[str] = None client_email: Optional[str] = None # IDs doctor_id: int branch_id: int offer_id: Optional[int] = None # اختياري # التواريخ booking_date: Optional[date] = None # ← يوم فقط بصيغة YYYY-MM-DD appointment_iso: Optional[str] = None # ← اختياري (وقت محدد) # باقي الحقول notes: Optional[str] = None referral_source: Literal[ "google_search", "social_media", "friend_recommendation", "paid_ads", "clinic_walkin", "insurance_dir", "other" ] = "google_search" class BookingOut(BaseModel): id: int booking_code: str doctor_id: int branch_id: int offer_id: Optional[int] = None booking_date: Optional[date] = None appointment_iso: Optional[str] = None client_name: Optional[str] client_mobile: Optional[str] client_email: Optional[str] notes: Optional[str] referral_source: str status: str created_at: str class BookingCreateResponse(BaseModel): message: str data: Optional[BookingOut] = None # ====== Bookings Helpers ====== import random, string def _norm(s: Optional[str]) -> str: return (s or "").strip().lower() def find_doctor_id_by_name(name: str) -> Optional[int]: """ يحاول يلاقي الدكتور من Supabase بالاسم (fname/lname) باستخدام ilike. أمثلة مقبولة: "Abdelrahman", "Abdelrahman Coding", "د. Abdelrahman" """ q = name.strip() if not q: return None # نجرب نفصل الاسم، ونستخدم ilike مرن # or=(fname.ilike.*q*,lname.ilike.*q*) يلقط لو الاسم جزء من أي واحد rows = supa_select("doctors", { "select": "id,fname,lname", "or": f"(fname.ilike.*{q}*,lname.ilike.*{q}*)", "limit": "5", "order": "id.asc" }) if not rows: return None # لو الاسم مركّب، جرّب تطابق fname+lname كجملة واحدة qn = _norm(q).replace("د.", "").replace("د ", "") best = None for r in rows: full = _norm(f"{r.get('fname','')} {r.get('lname','')}") if qn and qn in full: best = r["id"]; break return best or rows[0]["id"] def find_branch_id_by_name(name: str) -> Optional[int]: path = BASE_DIR / "branches_summary.json" if not path.exists(): return None try: data = json.loads(path.read_text(encoding="utf-8")) items = data.get("data", data) or [] except Exception: return None target = _norm(name) if isinstance(items, list): for it in items: if _norm(it.get("name")) == target: return it.get("id") elif isinstance(items, dict): # keyed-by-id for k, it in items.items(): if _norm(it.get("name")) == target: return int(k) return None def find_offer_id_by_title(title: str) -> Optional[int]: path = BASE_DIR / "offers.json" if not path.exists(): return None try: raw = json.loads(path.read_text(encoding="utf-8")) payload = raw.get("data", raw) or {} except Exception: return None target = _norm(title) def match_title(x): return _norm(x.get("title")) == target if isinstance(payload, dict): for c in (payload.get("campaigns") or []): if match_title(c): return c.get("id") for o in (payload.get("offers") or []): if match_title(o): return o.get("id") elif isinstance(payload, list): for it in payload: if match_title(it): return it.get("id") return None def resolve_missing_ids_from_names(body: "BookingIn") -> "BookingIn": # doctor if body.doctor_id is None and body.doctor_name: did = find_doctor_id_by_name(body.doctor_name) if did is not None: body.doctor_id = did # branch if body.branch_id is None and body.branch_name: bid = find_branch_id_by_name(body.branch_name) if bid is not None: body.branch_id = bid # offer (اختياري) if body.offer_id is None and body.offer_title: oid = find_offer_id_by_title(body.offer_title) if oid is not None: body.offer_id = oid return body def gen_booking_code() -> str: # مثال: BR-250221-AB39 today = now_utc().strftime("%y%m%d") suffix = "".join(random.choices(string.ascii_uppercase + string.digits, k=4)) return f"BR-{today}-{suffix}" def get_user_by_email_or_404(email: str) -> Dict[str, Any]: rows = supa_select("users", {**eq("email", email), "select":"id,email", "limit":"1"}) if not rows: raise HTTPException(404, "User not found") return rows[0] # ====== Bookings Validation via JSON files ====== def _load_json(path: Path, not_found_msg: str): if not path.exists(): raise HTTPException(500, not_found_msg) try: return json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: raise HTTPException(500, f"{path.name} contains invalid JSON") def _branch_exists_in_json(branch_id: int) -> bool: path = BASE_DIR / "branches_summary.json" data = _load_json(path, "branches_summary.json not found") items = data.get("data", data) if isinstance(items, list): return any(it.get("id") == branch_id for it in items) if isinstance(items, dict): # في حالة تكون dict keyed-by-id return str(branch_id) in items return False def _offer_exists_in_json(offer_id: int) -> bool: path = BASE_DIR / "offers.json" data = _load_json(path, "offers.json not found") payload = data.get("data", data) # قد تكون العروض تحت campaigns أو offers if isinstance(payload, dict): campaigns = payload.get("campaigns", []) offers = payload.get("offers", []) return any(c.get("id") == offer_id for c in campaigns) or any(o.get("id") == offer_id for o in offers) # fallback لو كانت ليستة مباشرة if isinstance(payload, list): return any(it.get("id") == offer_id for it in payload) return False def validate_fk_or_400(doctor_id: int, branch_id: int, offer_id: Optional[int]): # 1) doctor من Supabase (مافيش ملف doctors) d = supa_select("doctors", {**eq("id", doctor_id), "select": "id", "limit": "1"}) if not d: raise HTTPException(400, "Invalid doctor_id") # 2) branch من ملف JSON if not _branch_exists_in_json(branch_id): raise HTTPException(400, "Invalid branch_id") # 3) offer (اختياري) من ملف JSON if offer_id is not None and not _offer_exists_in_json(offer_id): raise HTTPException(400, "Invalid offer_id") # ====== Create Booking ====== @app.post("/api/bookings", response_model=BookingCreateResponse) def create_booking(body: BookingIn, payload=Depends(require_scopes(["user"]))): _ = get_user_by_email_or_404(payload["sub"]) # لازم واحد على الأقل من booking_date أو appointment_iso if not body.booking_date and not body.appointment_iso: raise HTTPException(422, "أرسل booking_date أو appointment_iso على الأقل") # لو الاتنين موجودين، لازم التاريخين يطابقوا بعض if body.booking_date and body.appointment_iso: appt_date = parse_iso_utc(body.appointment_iso).date() if appt_date != body.booking_date: raise HTTPException(422, "booking_date لا يطابق تاريخ appointment_iso") # استنتاج booking_date لو ماتبعتش وكان فيه appointment_iso computed_booking_date = ( body.booking_date if body.booking_date else (parse_iso_utc(body.appointment_iso).date() if body.appointment_iso else None) ) rec = { "booking_code": gen_booking_code(), "doctor_id": body.doctor_id, "branch_id": body.branch_id, "offer_id": body.offer_id, "booking_date": computed_booking_date.isoformat() if computed_booking_date else None, # عمود date "appointment_iso": body.appointment_iso, # لو حابب تحتفظ بالوقت كمان "notes": body.notes, "referral_source": body.referral_source, "status": "pending", "client_name": body.client_name, "client_mobile": body.client_mobile, "client_email": body.client_email, "created_at": iso(now_utc()), } try: saved = supa_insert("bookings", rec) return { "message": "تم تسجيل طلبك بنجاح. سيقوم أحد ممثلي خدمة العملاء بالتواصل معك هاتفياً لتحديد موعد", "data": saved } except Exception as e: print("[create_booking] insert failed:", e) raise HTTPException(status_code=400, detail="تعذر التسجيل. يرجى المحاولة مره أخرى") # ====== My Bookings ====== from typing import Optional def _ensure_op(val: Optional[str]) -> Optional[str]: """لو القيمة مافيها معامل PostgREST (eq./ilike./in./…)، نزود eq.""" if not val: return val ops = ("eq.", "neq.", "gt.", "gte.", "lt.", "lte.", "like.", "ilike.", "is.", "in.", "cs.", "cd.", "sl.", "sr.", "nxr.", "nxl.", "adj.", "ov.", "fts(", "plfts(", "phfts(", "wfts(") v = val.strip() if v.startswith(ops): return v return "eq." + v @app.get("/api/bookings/my_bookings") def my_bookings(payload=Depends(require_scopes(["user"]))): """ يرجّع جميع الحجوزات الخاصة بالمستخدم الحالي (من التوكن فقط). """ client_email = payload.get("sub") if not client_email: raise HTTPException(401, "Missing client identity") # إعداد باراميترات الاستعلام params = { "select": "*", "client_email": f"eq.{client_email}", "order": "created_at.desc", "limit": "100", } try: rows = supa_select("bookings", params) return { "message": "تم جلب حجوزات المستخدم بنجاح", "count": len(rows), "data": rows, } except Exception as e: print("[my_bookings] fetch failed:", e) raise HTTPException(400, "تعذر جلب الحجوزات، يرجى المحاولة لاحقاً") # ====== Referral Sources (static list) ====== @app.get("/api/referral-sources") def referral_sources(): data = [ {"code": "google_search", "label_ar": "بحث على جوجل"}, {"code": "social_media", "label_ar": "منصات التواصل الاجتماعي"}, {"code": "friend_recommendation", "label_ar": "ترشيح صديق/أهل"}, {"code": "paid_ads", "label_ar": "إعلان ممول"}, {"code": "clinic_walkin", "label_ar": "زيارة مباشرة للعيادة"}, {"code": "insurance_dir", "label_ar": "دليل شركة التأمين"}, {"code": "other", "label_ar": "أخرى"} ] return {"count": len(data), "data": data} # ====== Favorites (by full doctor name) ====== from pydantic import BaseModel from typing import Optional, Dict, Any class FavoriteByNameIn(BaseModel): doctor_full_name: str # الاسم الكامل كما يظهر للمستخدم (مثال: "محمد العتيبي") client_name: Optional[str] = None client_email: Optional[str] = None client_mobile: Optional[str] = None def _norm_spaces(s: str) -> str: # يزيل مسافات مضاعفة ويقص الطرفين return " ".join((s or "").strip().split()) def _split_full_name(full_name: str): """ يقسم الاسم الكامل لأول كلمة = fname والباقي = lname. أمثلة: "محمد العتيبي" -> ("محمد", "العتيبي") "عبدالرحمن بن خلف العلف" -> ("عبدالرحمن", "بن خلف العلف") """ full = _norm_spaces(full_name) parts = full.split(" ", 1) if len(parts) == 1: return parts[0], "" # لو حصل اسم واحد فقط return parts[0], parts[1] def _get_doctor_by_full_name_or_404(full_name: str) -> Dict[str, Any]: """ يبحث في جدول doctors بالمطابقة الدقيقة: fname == الجزء الأول lname == باقي الاسم لو ما لقاها، يحاول fallback بـ ilike على الاثنين معًا. """ f, l = _split_full_name(full_name) # 1) مطابقة دقيقة rows = supa_select("doctors", { "select": "id,fname,lname", "fname": f"eq.{f}", "lname": f"eq.{l}", "limit": "1" }) if rows: return rows[0] # 2) fallback مرن (يلتقط اختلافات بسيطة في المسافات/الصياغة) # - نجيب أعلى 10 أسماء قريبة بالـ ilike ثم نفلتر في البايثون بتطابق كامل بعد التطبيع candidates = supa_select("doctors", { "select": "id,fname,lname", "or": f"(fname.ilike.*{f}*,lname.ilike.*{l}*)", "order": "id.asc", "limit": "10" }) target = _norm_spaces(full_name) for r in candidates: composed = _norm_spaces(f"{r.get('fname','')} {r.get('lname','')}") if composed == target: return r raise HTTPException(404, "لم يتم العثور على الطبيب بالاسم الكامل المرسل") # ====== Favorites: toggle ====== from pydantic import BaseModel from typing import Optional class ToggleFavoriteIn(BaseModel): doctor_id: int # اختياري لو حابب نخزنها مع السجل الجديد client_name: Optional[str] = None client_mobile: Optional[str] = None @app.post("/api/favorites/toggle") def toggle_favorite(body: ToggleFavoriteIn, payload=Depends(require_scopes(["user"]))): """ يبدّل حالة المفضلة لطبيب معيّن للعميل (حسب التوكن). - لو السجل موجود (client_email + doctor_id) => نحذفه (is_favorite=false) - لو غير موجود => نضيفه (is_favorite=true) """ client_email = payload.get("sub") if not client_email: raise HTTPException(401, "Missing client identity") # 1) تحقّق من وجود الطبيب (وحضّر الاسم للتخزين) doc_rows = supa_select("doctors", {**eq("id", body.doctor_id), "select": "id,fname,lname", "limit": "1"}) if not doc_rows: raise HTTPException(404, "Doctor not found") doc = doc_rows[0] doc_full_name = f"{doc.get('fname','').strip()} {doc.get('lname','').strip()}".strip() or None # 2) هل المفضلة موجودة؟ exists = supa_select("favorites", { "select": "id", **eq("client_email", client_email), **eq("doctor_id", body.doctor_id), "limit": "1" }) if exists: # 3a) احذف = إلغاء المفضلة fav_id = exists[0]["id"] supa_delete("favorites", eq("id", fav_id)) return { "message": "تم حذف الطبيب من المفضلة", "doctor_id": body.doctor_id, "is_favorite": False } # 3b) أضِف = تفعيل المفضلة rec = { "client_name": (body.client_name or "").strip() or None, "client_email": client_email, "client_mobile": (body.client_mobile or "").strip() or None, "doctor_id": body.doctor_id, "doctor_name": doc_full_name, "created_at": iso(now_utc()), } try: supa_insert("favorites", rec) return { "message": "تمت إضافة الطبيب إلى المفضلة", "doctor_id": body.doctor_id, "is_favorite": True } except Exception as e: print("[favorites:toggle] insert failed:", e) raise HTTPException(400, "تعذر تعديل حالة المفضلة") @app.post("/api/favorites/add-by-name") def add_favorite_by_doctor_full_name(body: FavoriteByNameIn, payload=Depends(require_scopes(["user"]))): """ يستقبل الاسم الكامل للطبيب فقط من الموبايل، ويضيفه للمفضلة: - يعمل lookup في جدول doctors (fname/lname) ويجيب id - يسجل في جدول favorites: client_* + doctor_id + doctor_name (نفس الاسم الكامل المرسل) """ if not body.doctor_full_name or not _norm_spaces(body.doctor_full_name): raise HTTPException(422, "أرسل doctor_full_name") # 1) هات الدكتور بالاسم الكامل d = _get_doctor_by_full_name_or_404(body.doctor_full_name) # 2) إدراج المفضلة rec = { "client_name": (body.client_name or "").strip() or None, "client_email": (body.client_email or "").strip() or None, "client_mobile": (body.client_mobile or "").strip() or None, "doctor_id": d["id"], "doctor_name": _norm_spaces(body.doctor_full_name), "created_at": iso(now_utc()), } try: saved = supa_insert("favorites", rec) return {"message": "تمت الإضافة إلى المفضلة", "data": saved} except Exception as e: print("[favorites:add-by-name] insert failed:", e) raise HTTPException(400, "تعذر إضافة المفضلة") @app.get("/api/favorites/by-contact") def favorites_by_contact( payload=Depends(require_scopes(["user"])), select: str = "*", client_mobile: Optional[str] = None, client_email: Optional[str] = None, order: str = "created_at.desc", limit: int = 100, offset: int = 0, ): """ يرجّع مفضلات عميل بالموبايل/الإيميل. يدعم تمثيل معاملات PostgREST: ?client_mobile=eq.+9665... ?client_email=ilike.*@gmail.com ولو تبعت القيمة بدون معامل هنضيف eq. تلقائيًا. """ if not client_mobile and not client_email: raise HTTPException(400, "أرسل client_mobile أو client_email على الأقل") def _ensure_op(v: Optional[str]) -> Optional[str]: if not v: return v ops = ("eq.","neq.","gt.","gte.","lt.","lte.","like.","ilike.","is.","in.", "cs.","cd.","sl.","sr.","nxr.","nxl.","adj.","ov.","fts(","plfts(","phfts(","wfts(") vv = v.strip() return vv if vv.startswith(ops) else "eq." + vv params = { "select": select, "order": order, "limit": str(limit), "offset": str(offset), } if client_mobile: params["client_mobile"] = _ensure_op(client_mobile) if client_email: params["client_email"] = _ensure_op(client_email) rows = supa_select("favorites", params) return {"message": "Favorites fetched successfully", "count": len(rows), "data": rows} # ====== Terms AR/EN ====== TERMS_AR = """ مقدمة مرحبًا بك في تطبيق Binrushd Medical Center، التطبيق الرسمي لمركز بن رشد التخصصي للعيون. باستخدامك لهذا التطبيق، فإنك توافق على الشروط والأحكام التالية، لذا يُرجى قراءتها بعناية قبل الاستخدام. 1. الهدف من التطبيق يتيح التطبيق للمستخدمين: التعرف على خدمات المركز وأقسامه الطبية. استعراض معلومات الأطباء والمواعيد المتاحة. حجز المواعيد وإرسال طلبات الحجز إلكترونيًا. 2. الاستخدام المسموح يلتزم المستخدم باستخدام التطبيق لأغراض شخصية فقط. يُمنع استخدام التطبيق لأي غرض تجاري أو دعائي أو غير قانوني. يجب تقديم معلومات صحيحة ودقيقة عند التسجيل أو الحجز. 3. الخصوصية وحماية البيانات يلتزم مركز بن رشد بالحفاظ على سرية بيانات المستخدم وعدم مشاركتها مع أي طرف ثالث إلا عند الضرورة لتقديم الخدمة أو بناءً على المتطلبات القانونية. يحتفظ المركز بحق استخدام بيانات الاستخدام لتحسين الخدمات وتجربة المستخدم. 4. المواعيد والخدمات الطبية تأكيد الحجز لا يُعدّ تشخيصًا طبيًا ولا يضمن توافر الطبيب في جميع الأوقات. يحتفظ المركز بحق تعديل أو إلغاء المواعيد عند الضرورة مع إخطار المستخدم. 5. حقوق الملكية الفكرية جميع محتويات التطبيق (النصوص، الصور، الشعارات، التصميمات) مملوكة لمركز بن رشد ولا يجوز نسخها أو استخدامها دون إذن خطي مسبق. 6. التعديلات يحق لمركز بن رشد تعديل هذه الشروط في أي وقت، وتعتبر النسخة المنشورة في التطبيق هي السارية وقت الاستخدام. 7. التواصل للاستفسارات أو الدعم الفني، يمكن التواصل عبر البريد الإلكتروني: info@binrushd.net """ TERMS_EN = """ Introduction Welcome to the Binrushd Medical Center mobile application — the official app of Binrushd Eye Specialty Center. By using this application, you agree to the following terms and conditions. Please read them carefully before using the app. 1. Purpose of the Application This app allows users to: Learn more about the medical services and departments of the center. View doctors’ profiles and available appointment slots. Book appointments and send booking requests electronically. 2. Permitted Use The app is intended for personal, non-commercial use only. You may not use the app for any unlawful or unauthorized purpose. Users must provide accurate and truthful information when registering or booking. 3. Privacy and Data Protection Binrushd Medical Center is committed to protecting user data and will not share it with third parties except when required to provide services or comply with legal obligations. Usage data may be analyzed to improve the quality of services and user experience. 4. Appointments and Medical Services Appointment booking does not constitute a medical diagnosis and does not guarantee doctor availability at all times. The center reserves the right to modify or cancel appointments when necessary and will inform users accordingly. 5. Intellectual Property Rights All content in the app (texts, images, logos, and designs) is owned by Binrushd Medical Center and may not be copied or reused without prior written consent. 6. Modifications Binrushd Medical Center reserves the right to modify these terms at any time. The latest version published in the app shall be deemed the valid one. 7. Contact For inquiries or support, please contact: info@binrushd.net """ @app.get("/api/terms") def get_terms(lang: str = Query("ar", description="لغة الشروط: ar أو en")): if lang.lower() == "en": return {"language": "en", "title": "Terms and Conditions", "content": TERMS_EN.strip()} else: return {"language": "ar", "title": "الشروط والأحكام", "content": TERMS_AR.strip()}
# main.py
from fastapi import FastAPI, Form, HTTPException, Depends, Header, Form, Query
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel, EmailStr
import typing
from typing import Any, Dict, Optional
import os, requests, random, string, jwt
from datetime import datetime, timedelta, timezone
from passlib.context import CryptContext
from pathlib import Path
import json
from typing import Optional
from fastapi import Query
from datetime import date
# ====== Config ======
SUPA_URL = os.getenv("SUPABASE_URL", "https://hirmgvjpdifudkiugtyr.supabase.co").rstrip("/")
SUPA_KEY = os.getenv("SUPABASE_ANON_KEY", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imhpcm1ndmpwZGlmdWRraXVndHlyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjA0ODE0NDksImV4cCI6MjA3NjA1NzQ0OX0.Ti4u1FyzorR80Fz1LzLFRHKu_RD2_rp-C8wzf47hOe4")
GAS_URL = os.getenv("GAS_MAIL_URL","https://script.google.com/macros/s/AKfycbxzj7vfMpkzAissmvXjazWZMRTvhB2tBG3xodYeq8wYQzraBekA5NupIbeJLaGUh3l85g/exec")
GAS_SECRET = os.getenv("GAS_SECRET", "CHANGE_ME_STRONG_SECRET")
JWT_SECRET = os.getenv("JWT_SECRET", "change_me")
JWT_ALG = os.getenv("JWT_ALG", "HS256")
HEADERS = {
"apikey": SUPA_KEY,
"Authorization": f"Bearer {SUPA_KEY}",
"Content-Type": "application/json",
"Accept": "application/json",
}
pwd = CryptContext(schemes=["bcrypt_sha256"], deprecated="auto")
oauth2 = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
app = FastAPI(title="BinRushd Auth (Supabase REST)")
BASE_DIR = Path(__file__).resolve().parent
# ====== Helpers ======
def now_utc() -> datetime:
return datetime.now(timezone.utc)
def iso(dt: datetime) -> str:
return dt.astimezone(timezone.utc).isoformat()
def parse_iso_utc(value: str) -> datetime:
"""
يحوّل أي نص ISO إلى datetime ب timezone=UTC.
لو السلسلة بدون timezone، نعتبرها UTC.
يقبل قيم زي: '2025-10-16T05:21:00', '...Z', '...+00:00'
"""
if not value:
return now_utc()
s = value.strip()
if s.endswith("Z"):
s = s[:-1] + "+00:00"
try:
dt = datetime.fromisoformat(s)
except Exception:
# لو فورمات مش متوقع: رجّع وقت قديم قوي علشان نعتبره منتهي
return now_utc() - timedelta(days=3650)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def create_access_token(sub: str, scopes=None, minutes=60) -> str:
now = now_utc()
payload = {"sub": sub, "scopes": scopes or [], "iat": int(now.timestamp()), "exp": int((now + timedelta(minutes=minutes)).timestamp())}
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALG)
def decode_token(tok: str):
return jwt.decode(tok, JWT_SECRET, algorithms=[JWT_ALG])
def eq(col, val): return {col: f"eq.{val}"}
def supa_select(table: str, params: dict):
url = f"{SUPA_URL}/rest/v1/{table}"
try:
r = requests.get(url, headers=HEADERS, params=params, timeout=30)
# ✅ LOG
print(
f"[supa_select] table={table} status={r.status_code} "
f"url={r.url} "
f"resp_len={len(r.text) if r.text else 0}"
)
# لو فيه خطأ اطبع محتوى الرد
if r.status_code >= 400:
print(f"[supa_select] ERROR body={r.text}")
r.raise_for_status()
data = r.json()
# ✅ LOG: count + sample ids لو موجودة
if isinstance(data, list):
ids = [x.get("id") for x in data if isinstance(x, dict) and "id" in x]
print(f"[supa_select] table={table} rows={len(data)} ids_sample={ids[:10]}")
else:
print(f"[supa_select] table={table} non_list_json_type={type(data)}")