156 lines
6.5 KiB
Python
156 lines
6.5 KiB
Python
"""
|
|
Two endpoints for the self-assess calculator, per CLAUDE_CALCULATOR.md §5
|
|
— adapted from that document's n8n-webhook design to Flask routes on this
|
|
site's own backend (Jason's direction, superseding that doc's original
|
|
transport choice; the payload contracts and the two-flow split are
|
|
unchanged). Neither endpoint receives or recomputes any calculator math:
|
|
`results` is already-computed label/value pairs read straight off the
|
|
page's own displayed results by the frontend (index.html's
|
|
buildCopyPayload()/buildContactPayload()) — this backend only turns that
|
|
into a PDF and sends an email. The weighted-rate model, tier sizing, and
|
|
every dollar figure live and stay entirely in the client-side JS.
|
|
|
|
Data flow:
|
|
POST /api/calculator/copy → PDF built → emailed to the visitor ONLY
|
|
POST /api/calculator/contact → PDF built → emailed to Config.SALES_EMAIL
|
|
with the visitor's contact details,
|
|
reply-to set to their address
|
|
Per CLAUDE_CALCULATOR.md §5a/§5b: a copy request is not consent to be
|
|
contacted (never notifies the studio); a contact-form submission does not
|
|
auto-email the visitor a copy (that's the separate, opt-in §5a flow). Kept
|
|
as two distinct endpoints rather than one branching endpoint so this
|
|
separation can never accidentally blur.
|
|
"""
|
|
|
|
import html
|
|
import logging
|
|
|
|
from flask import Blueprint, jsonify, request
|
|
|
|
from config import Config
|
|
from middleware.rate_limit import limiter
|
|
from services.email_service import send_email
|
|
from services.email_template_service import build_results_email_html
|
|
from services.pdf_service import build_pdf
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
calculator_bp = Blueprint("calculator", __name__)
|
|
|
|
_MAX_SHORT_TEXT = 200
|
|
_MAX_LONG_TEXT = 4000
|
|
_MAX_RESULT_ROWS = 20
|
|
|
|
|
|
def _is_valid_email(value: str) -> bool:
|
|
return bool(value) and "@" in value and "." in value.split("@")[-1]
|
|
|
|
|
|
def _extract_shared_fields(body: dict) -> dict:
|
|
# Common to both endpoints — everything needed to render the PDF,
|
|
# length-capped defensively since this is public, unauthenticated input
|
|
return {
|
|
"calculator": str(body.get("calculator") or "")[:50],
|
|
"title": str(body.get("title") or "Your Results")[:_MAX_SHORT_TEXT],
|
|
"summary_text": str(body.get("summary_text") or "")[:_MAX_LONG_TEXT],
|
|
"results": [
|
|
{
|
|
"label": str(row.get("label", ""))[:100],
|
|
"value": str(row.get("value", ""))[:100],
|
|
}
|
|
for row in (body.get("results") or [])
|
|
if isinstance(row, dict)
|
|
][:_MAX_RESULT_ROWS],
|
|
"basis_footnote": str(body.get("basis_footnote") or "")[:_MAX_LONG_TEXT],
|
|
"proactive_question": str(body.get("proactive_question") or "")[:1000],
|
|
"proactive_answer": str(body.get("proactive_answer") or "")[:_MAX_LONG_TEXT],
|
|
}
|
|
|
|
|
|
@calculator_bp.route("/api/calculator/copy", methods=["POST"])
|
|
@limiter.limit(lambda: f"{Config.RATELIMIT_PER_HOUR} per hour")
|
|
def calculator_copy():
|
|
"""
|
|
"Email me a copy" — CLAUDE_CALCULATOR.md §5a. Sends the PDF to the
|
|
visitor's own address only; never notifies Config.SALES_EMAIL.
|
|
"""
|
|
body = request.get_json(silent=True) or {}
|
|
recipient_email = str(body.get("recipient_email") or "").strip()[:_MAX_SHORT_TEXT]
|
|
|
|
if not _is_valid_email(recipient_email):
|
|
return jsonify({"error": "a valid recipient_email is required"}), 400
|
|
|
|
payload = _extract_shared_fields(body)
|
|
|
|
# Strips any stray newlines from the title before it reaches the
|
|
# subject line — this endpoint is public/unauthenticated, so nothing
|
|
# from the request body should ever flow into a header-like field unsanitized.
|
|
subject_title = payload["title"].replace("\r", " ").replace("\n", " ")
|
|
|
|
try:
|
|
pdf_bytes = build_pdf(payload)
|
|
send_email(
|
|
to=recipient_email,
|
|
subject=f"Your Bettersight Intelligence results — {subject_title}",
|
|
html_body=build_results_email_html(payload),
|
|
attachment_bytes=pdf_bytes,
|
|
attachment_filename="bettersight-results.pdf",
|
|
)
|
|
except Exception:
|
|
logger.exception("Failed to send calculator 'email me a copy' PDF")
|
|
return jsonify({"error": "Could not send your copy — please try again shortly."}), 502
|
|
|
|
return jsonify({"status": "sent"})
|
|
|
|
|
|
@calculator_bp.route("/api/calculator/contact", methods=["POST"])
|
|
@limiter.limit(lambda: f"{Config.RATELIMIT_PER_HOUR} per hour")
|
|
def calculator_contact():
|
|
"""
|
|
"Turn this into a plan" inline contact form — CLAUDE_CALCULATOR.md
|
|
§5b. Notifies Config.SALES_EMAIL with the visitor's contact details
|
|
and their results PDF attached; does NOT auto-email the visitor
|
|
(that's the separate §5a flow above, opt-in).
|
|
"""
|
|
body = request.get_json(silent=True) or {}
|
|
contact = body.get("contact") or {}
|
|
|
|
name = str(contact.get("name") or "").strip()[:_MAX_SHORT_TEXT]
|
|
email = str(contact.get("email") or "").strip()[:_MAX_SHORT_TEXT]
|
|
organization = str(contact.get("organization") or "").strip()[:_MAX_SHORT_TEXT]
|
|
phone = str(contact.get("phone") or "").strip()[:50]
|
|
sector = str(contact.get("sector") or "").strip()[:_MAX_SHORT_TEXT]
|
|
|
|
if not name or not _is_valid_email(email):
|
|
return jsonify({"error": "a valid name and email are required"}), 400
|
|
|
|
payload = _extract_shared_fields(body)
|
|
|
|
plaintext = str(body.get("email_body_plaintext") or "")[:8000]
|
|
if plaintext:
|
|
html_body = f"<pre style=\"font-family:inherit;white-space:pre-wrap;\">{html.escape(plaintext)}</pre>"
|
|
else:
|
|
html_body = (
|
|
f"<p><strong>Name:</strong> {html.escape(name)}</p>"
|
|
f"<p><strong>Email:</strong> {html.escape(email)}</p>"
|
|
f"<p><strong>Organization:</strong> {html.escape(organization)}</p>"
|
|
f"<p><strong>Phone:</strong> {html.escape(phone)}</p>"
|
|
f"<p><strong>Sector:</strong> {html.escape(sector)}</p>"
|
|
)
|
|
|
|
try:
|
|
pdf_bytes = build_pdf(payload)
|
|
send_email(
|
|
to=Config.SALES_EMAIL,
|
|
subject=f"Self-assess lead: {name} ({organization or 'no organization given'})",
|
|
html_body=html_body,
|
|
reply_to=email,
|
|
attachment_bytes=pdf_bytes,
|
|
attachment_filename="bettersight-results.pdf",
|
|
)
|
|
except Exception:
|
|
logger.exception("Failed to send calculator lead notification to the studio inbox")
|
|
return jsonify({"error": "Something went wrong — please try again or email us directly."}), 502
|
|
|
|
return jsonify({"status": "received"})
|