Add template parameter auto-fix and admin endpoint
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

- Add auto-migration on app startup to fix hina_invitation template parameters
- Add /api/admin/fix-templates endpoint for manual template fixing
- Ensure hina_invitation has all 10 required body parameters
- Imported SessionLocal for template migrations
- Messages should now deliver correctly to test phone numbers
This commit is contained in:
dvirlabs 2026-05-13 13:49:42 +03:00
parent 9b6f053d86
commit fc3cd21e21

View File

@ -39,7 +39,7 @@ import schemas
import crud import crud
import authz import authz
import google_contacts import google_contacts
from database import engine, get_db from database import engine, get_db, SessionLocal
from whatsapp import get_whatsapp_service, WhatsAppError from whatsapp import get_whatsapp_service, WhatsAppError
from whatsapp_templates import list_templates_for_frontend, add_custom_template, delete_custom_template from whatsapp_templates import list_templates_for_frontend, add_custom_template, delete_custom_template
@ -68,7 +68,47 @@ def _run_startup_migrations():
_run_startup_migrations() _run_startup_migrations()
app = FastAPI(title="Multi-Event Invitation Management API") # ── Auto-fix templates on startup ─────────────────────────────────────────────
def _fix_template_parameters():
"""Auto-fix template parameters that may be incorrect in the database."""
import json
db = SessionLocal()
try:
template = db.query(models.WhatsAppTemplate).filter(
(models.WhatsAppTemplate.template_key == 'hina_invitation') |
(models.WhatsAppTemplate.meta_name == 'hina_invitation')
).first()
if template:
# Expected correct parameters for hina_invitation
expected_params = [
"contact_name", "event_date", "event_date_day", "venue", "location",
"reception_time", "ceremony_time", "dinner_time", "bride_name", "groom_name"
]
try:
current_params = json.loads(template.body_params)
except:
current_params = []
# Check if parameters need fixing
if current_params != expected_params:
print(f"[startup] Fixing hina_invitation template parameters...")
print(f" Old: {current_params}")
print(f" New: {expected_params}")
template.body_params = json.dumps(expected_params)
if not template.header_type:
template.header_type = "IMAGE"
db.commit()
print(f" ✓ Template fixed!")
except Exception as e:
print(f"[startup] Template fix warning: {e}")
finally:
db.close()
_fix_template_parameters()
# Ensure uploads directory exists and serve it as static files # Ensure uploads directory exists and serve it as static files
UPLOADS_DIR = Path(__file__).parent / "uploads" UPLOADS_DIR = Path(__file__).parent / "uploads"
@ -1939,6 +1979,7 @@ async def import_contacts(
) )
# ============================================ # ============================================
# WhatsApp Testing Endpoint (for debugging) # WhatsApp Testing Endpoint (for debugging)
# ============================================ # ============================================
@ -1996,5 +2037,69 @@ async def test_whatsapp_send(
) )
@app.post("/api/admin/fix-templates")
async def fix_templates(db: Session = Depends(get_db)):
"""
Admin endpoint to fix template parameters in the database.
Fixes the hina_invitation template with correct body parameters.
"""
try:
import json
from models import WhatsAppTemplate
# Find and fix hina_invitation template
template = db.query(WhatsAppTemplate).filter(
(WhatsAppTemplate.template_key == 'hina_invitation') |
(WhatsAppTemplate.meta_name == 'hina_invitation')
).first()
if not template:
return {
"status": "not_found",
"message": "hina_invitation template not found in database"
}
# Correct body parameters for hina_invitation
correct_params = [
"contact_name",
"event_date",
"event_date_day",
"venue",
"location",
"reception_time",
"ceremony_time",
"dinner_time",
"bride_name",
"groom_name"
]
old_params = template.body_params
template.body_params = json.dumps(correct_params)
template.header_type = "IMAGE"
db.commit()
logger.info(f"✓ Fixed hina_invitation template")
logger.info(f" Old params: {old_params}")
logger.info(f" New params: {template.body_params}")
return {
"status": "fixed",
"template_key": template.template_key,
"meta_name": template.meta_name,
"old_params": old_params,
"new_params": correct_params,
"message": "Template parameters fixed successfully"
}
except Exception as e:
logger.error(f"Failed to fix templates: {str(e)}", exc_info=True)
db.rollback()
raise HTTPException(
status_code=500,
detail=f"Failed to fix templates: {str(e)}"
)
if __name__ == "__main__": if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)