Spaces:
Sleeping
Sleeping
Create firebase_service.py
Browse files- firebase_service.py +55 -0
firebase_service.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Datei: firebase_service.py
|
| 2 |
+
import firebase_admin
|
| 3 |
+
from firebase_admin import credentials
|
| 4 |
+
from firebase_admin import firestore
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# --- INITIALISIERUNG ---
|
| 8 |
+
# Lade den Pfad des Service Account Schlüssels aus Umgebungsvariablen (Beste Praxis)
|
| 9 |
+
SERVICE_ACCOUNT_PATH = os.environ.get("FIREBASE_SA_KEY_PATH", "sky-ai-key.json") # Default-Name
|
| 10 |
+
|
| 11 |
+
def initialize_firebase_db():
|
| 12 |
+
"""Initialisiert die Firebase Admin SDK Verbindung und gibt den Firestore-Client zurück."""
|
| 13 |
+
|
| 14 |
+
if firebase_admin._apps:
|
| 15 |
+
return firestore.client()
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
# Lade die Anmeldedaten
|
| 19 |
+
cred = credentials.Certificate(SERVICE_ACCOUNT_PATH)
|
| 20 |
+
|
| 21 |
+
# Initialisiere die Firebase App
|
| 22 |
+
firebase_admin.initialize_app(cred)
|
| 23 |
+
print("INFO: Firebase Admin SDK erfolgreich initialisiert.")
|
| 24 |
+
|
| 25 |
+
# Gebe den Firestore-Client zurück
|
| 26 |
+
return firestore.client()
|
| 27 |
+
|
| 28 |
+
except Exception as e:
|
| 29 |
+
print(f"FEHLER: Firebase-Initialisierung fehlgeschlagen. Fehler: {e}")
|
| 30 |
+
return None
|
| 31 |
+
|
| 32 |
+
# Globale Variable, die den initialisierten Datenbank-Client hält
|
| 33 |
+
FIRESTORE_DB = initialize_firebase_db()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# --- KERNFUNKTION FÜR DATENSPEICHERUNG ---
|
| 37 |
+
def track_and_attribute_revenue_to_db(transaction_data: dict) -> bool:
|
| 38 |
+
"""Speichert eine Transaktion in der Firestore-Datenbank (Kollektion: 'transactions')."""
|
| 39 |
+
if not FIRESTORE_DB:
|
| 40 |
+
print("FEHLER: Datenbank nicht verbunden.")
|
| 41 |
+
return False
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
# Die Transaktions-ID wird als Dokumenten-ID verwendet
|
| 45 |
+
doc_ref = FIRESTORE_DB.collection('transactions').document(transaction_data['transaction_id'])
|
| 46 |
+
|
| 47 |
+
doc_ref.set(transaction_data)
|
| 48 |
+
|
| 49 |
+
print(f"INFO: Transaktion {transaction_data['transaction_id']} erfolgreich in Firebase gespeichert.")
|
| 50 |
+
return True
|
| 51 |
+
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"FEHLER beim Speichern in Firebase: {e}")
|
| 54 |
+
return False
|
| 55 |
+
|