BuddyMath / generate_dotan_report.py
dotandru's picture
Fix: Quota logic for admins and updated firestore rules
3091d31
Raw
History Blame Contribute Delete
3.79 kB
# buddy_math_server/generate_dotan_report.py
import asyncio
import os
import sys
import logging
# environment setup
sys.path.append(os.getcwd())
os.environ["SENDGRID_API_KEY"] = "SG.mock_key" # Replace with real if testing live
from report_aggregator import report_aggregator
from report_generator import report_generator
from report_delivery_service import report_delivery_service
from firebase_manager import firebase_manager
from unittest.mock import MagicMock
# Force mock before any calls
firebase_manager.initialize = MagicMock()
firebase_manager.get_db = MagicMock(return_value=None)
async def generate_sample_report(uid, student_name, recipient_email):
print(f"📄 Generating Sample Report for {student_name} ({uid})...")
# 1. Aggregate Data
# For testing, we might need to mock the aggregator if Firestore is empty
summary = report_aggregator.get_summary_for_period(uid)
if not summary or summary["total_interactions"] == 0:
print("⚠️ No real data found. Using MOCK data for visibility.")
summary = {
"total_interactions": 15,
"completed_challenges": 4,
"avg_mastery": {
"אלגברה": 85.5,
"גיאומטריה": 92.0,
"פונקציות": 78.2,
"טריגונומטריה": 65.0
},
"teacher_notes": ["התלמיד שולט היטב בפתרון משוואות.", "יש לשים לב לדיוק בשרטוט גיאומטרי."]
}
# 2. AI Summary
print("🧠 Generating AI Summary...")
ai_summary = await report_generator.generate_ai_summary(summary, student_name)
print(f"Summary: {ai_summary}")
# 3. Radar Chart
print("📊 Generating Visuals...")
chart_url = report_generator.generate_radar_chart_url(summary["avg_mastery"])
# 4. Render HTML
print("🎨 Rendering Template...")
template_data = {
"student_name": student_name,
"total_interactions": summary["total_interactions"],
"completed_challenges": summary["completed_challenges"],
"avg_mastery_pct": sum(summary["avg_mastery"].values()) / len(summary["avg_mastery"]),
"ai_summary": ai_summary,
"chart_url": chart_url
}
html_content = report_delivery_service.render_html('report_template.html', template_data)
# 5. Generate PDF
pdf_path = f"/tmp/BuddyMath_Report_{student_name}.pdf"
print("🖨️ Generating PDF...")
success = report_delivery_service.generate_pdf(html_content, pdf_path)
if success:
print(f"✅ PDF Generated at: {pdf_path}")
else:
print("⚠️ PDF generation failed (likely xhtml2pdf missing). Saved as HTML.")
pdf_path = pdf_path.replace('.pdf', '.html')
# 6. Send Email (Mocked unless real key provided)
print(f"📧 Sending Email to {recipient_email}...")
subject = f"איך עבר השבוע של {student_name} ב-Buddy-Math? ✏️"
# If using mock key, it will log error but we consider logic verified
email_success = report_delivery_service.send_email_with_attachment(
recipient_email, subject, ai_summary, pdf_path, student_name
)
if email_success:
print("✅ Email sent successfully!")
else:
print("❌ Email delivery failed (verify SENDGRID_API_KEY).")
if __name__ == "__main__":
# Ensure Firebase is initialized for real data lookup if available
try:
firebase_manager.initialize()
except Exception as e:
print(f"⚠️ Firebase initialization failed: {e}. Proceeding with mock data.")
dotan_uid = "dotan_admin_uid" # Replace with actual if known
asyncio.run(generate_sample_report(dotan_uid, "דותן", "dotan@example.com"))