Spaces:
Runtime error
Runtime error
File size: 3,448 Bytes
1ffd0a4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | from typing import Dict, Any, List, Optional
from fastapi import HTTPException
from google.cloud.firestore import AsyncClient, SERVER_TIMESTAMP, ArrayUnion, FieldFilter
from backend.core.firebase import get_async_db
class FirestoreService:
@property
def db(self) -> AsyncClient:
return get_async_db()
async def get_user(self, cnic: str) -> Optional[Dict[str, Any]]:
doc_ref = self.db.collection("users").document(cnic)
doc = await doc_ref.get()
if doc.exists:
return doc.to_dict()
return None
async def create_user(self, data: Dict[str, Any]) -> Dict[str, Any]:
cnic = data.get("cnic")
if not cnic:
raise ValueError("CNIC is required to create a user.")
doc_ref = self.db.collection("users").document(cnic)
await doc_ref.set(data)
return data
async def update_user(self, cnic: str, data: Dict[str, Any]) -> Dict[str, Any]:
doc_ref = self.db.collection("users").document(cnic)
doc = await doc_ref.get()
if not doc.exists:
raise HTTPException(status_code=404, detail="User not found")
await doc_ref.update(data)
return {"cnic": cnic, **data}
async def create_crisis(self, data: Dict[str, Any]) -> Dict[str, Any]:
crisis_id = data.get("crisis_id")
if not crisis_id:
_, doc_ref = await self.db.collection("crises").add(data)
data["crisis_id"] = doc_ref.id
await doc_ref.update({"crisis_id": doc_ref.id})
else:
doc_ref = self.db.collection("crises").document(crisis_id)
await doc_ref.set(data)
return data
async def get_crisis(self, crisis_id: str) -> Optional[Dict[str, Any]]:
doc_ref = self.db.collection("crises").document(crisis_id)
doc = await doc_ref.get()
if doc.exists:
return doc.to_dict()
return None
async def update_crisis(self, crisis_id: str, data: Dict[str, Any]) -> Dict[str, Any]:
doc_ref = self.db.collection("crises").document(crisis_id)
doc = await doc_ref.get()
if not doc.exists:
raise HTTPException(status_code=404, detail="Crisis not found")
await doc_ref.update(data)
return {"crisis_id": crisis_id, **data}
async def get_ngos_for_area(self, area: str, crisis_type: str) -> List[Dict[str, Any]]:
ngos_ref = self.db.collection("ngos")
query = (
ngos_ref
.where(filter=FieldFilter("coverage_areas", "array_contains", area))
.where(filter=FieldFilter("active", "==", True))
)
results = []
async for doc in query.stream():
data = doc.to_dict()
if crisis_type in data.get("crisis_types", []):
results.append({"ngo_id": doc.id, **data})
return results
async def append_agent_log(self, crisis_id: str, step: Dict[str, Any]) -> bool:
log_ref = self.db.collection("agent_logs").document(crisis_id)
doc = await log_ref.get()
if not doc.exists:
await log_ref.set({
"crisis_id": crisis_id,
"steps": [step],
"created_at": SERVER_TIMESTAMP
})
else:
await log_ref.update({
"steps": ArrayUnion([step])
})
return True
firestore_service = FirestoreService()
|