diff --git a/CLAUDE.md b/CLAUDE.md index 29fdbe1..4d7ab42 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,4 +38,4 @@ Estándar: producción militar, determinismo matemático (SHA-256), seguridad LS 2. **No-Fault Quota Deduction**: - Nunca cobrar doble ni perder créditos por reintentos de red. 3. **Verificación Obligatoria**: - - `python run_tests.py` debe pasar al 100 % (239/239) antes de cualquier `fly deploy`. + - `python run_tests.py` debe pasar al 100 % (244/244) antes de cualquier `fly deploy`. diff --git a/app/application/services/trial_nurture.py b/app/application/services/trial_nurture.py new file mode 100644 index 0000000..975990c --- /dev/null +++ b/app/application/services/trial_nurture.py @@ -0,0 +1,111 @@ +"""Seguimiento de la licencia de prueba de Flint: correos en los días 1, 3 y 7 tras el alta. + +Scope: Community licenses with metadata.trial (never demo, never upgraded: a purchase turns the +license into another tier and it leaves the query). One email per pass and license: if the gateway +was down, only the latest step due is sent and older ones are recorded as skipped. Every email +carries a one-click unsubscribe (LSSI art. 21.2); an opt-out stops every later step. +Runs from the hourly maintenance loop; NURTURE_EMAIL_ENABLED turns it off. +""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +import hashlib +import hmac +import json +import logging +from typing import Any, Optional +from urllib.parse import urlencode + +from app.config import get_settings + +logger = logging.getLogger("keyflint.nurture") + +EVENT_SENT = "trial_nurture_email" +EVENT_OPT_OUT = "marketing_opt_out" +STEPS = (1, 3, 7) +_MAX_AGE_DAYS = STEPS[-1] + 2 # a step older than this is never sent late + + +def unsubscribe_token(license_id: str) -> str: + key = get_settings().SECRET_KEY.encode() + return hmac.new(key, f"unsubscribe:{license_id}".encode(), hashlib.sha256).hexdigest()[:32] + + +def unsubscribe_url(license_id: str) -> str: + base = get_settings().NURTURE_UNSUBSCRIBE_BASE.rstrip("/") + return f"{base}/api/v1/billing/unsubscribe?" + urlencode({"l": license_id, "t": unsubscribe_token(license_id)}) + + +def verify_unsubscribe(license_id: str, token: str) -> bool: + return bool(license_id) and hmac.compare_digest(unsubscribe_token(license_id), token or "") + + +def record_opt_out(conn: Any, license_id: str) -> bool: + """Idempotent. Returns False when the license does not exist.""" + if conn.execute("SELECT 1 FROM licenses WHERE id = ?", (license_id,)).fetchone() is None: + return False + if conn.execute("SELECT 1 FROM license_events WHERE license_id = ? AND event_type = ?", + (license_id, EVENT_OPT_OUT)).fetchone() is None: + conn.execute("INSERT INTO license_events (id, license_id, event_type, details_json) " + "VALUES (lower(hex(randomblob(16))), ?, ?, '{}')", (license_id, EVENT_OPT_OUT)) + conn.commit() + return True + + +def _parse(ts: Any) -> datetime: + d = datetime.fromisoformat(str(ts).replace(" ", "T").replace("Z", "+00:00")) + return d if d.tzinfo else d.replace(tzinfo=timezone.utc) + + +def run_trial_nurture(conn: Any, email_sender: Any, now: Optional[datetime] = None) -> dict[str, int]: + """Sends the due step to each trial license. Returns counters. Never raises per license.""" + stats = {"sent": 0, "skipped": 0, "failed": 0} + if not get_settings().NURTURE_EMAIL_ENABLED: + return stats + now = now or datetime.now(timezone.utc) + since = (now - timedelta(days=_MAX_AGE_DAYS)).strftime("%Y-%m-%d %H:%M:%S") + rows = conn.execute( + """SELECT l.id, l.license_key, l.metadata_json, l.created_at, c.email, + COALESCE(q.consumed, 0) AS consumed, COALESCE(q.balance, 0) AS balance + FROM licenses l JOIN customers c ON c.id = l.customer_id + LEFT JOIN quotas q ON q.license_id = l.id + WHERE l.tier = 'community' AND l.status = 'active' AND l.created_at >= ?""", + (since,), + ).fetchall() + for r in rows: + try: + meta = json.loads(r["metadata_json"] or "{}") + if not meta.get("trial") or meta.get("demo") or meta.get("lang") == "en" or not r["email"]: # emails are Spanish-only + continue + events = conn.execute( + "SELECT event_type, details_json FROM license_events WHERE license_id = ? AND event_type IN (?, ?)", + (r["id"], EVENT_SENT, EVENT_OPT_OUT), + ).fetchall() + if any(e["event_type"] == EVENT_OPT_OUT for e in events): + continue + done = {int(json.loads(e["details_json"] or "{}").get("step", 0)) for e in events} + age = (now - _parse(r["created_at"])).total_seconds() / 86400 + due = [s for s in STEPS if s <= age and s not in done] + if not due: + continue + step = due[-1] + for s in due[:-1]: + conn.execute("INSERT INTO license_events (id, license_id, event_type, details_json) " + "VALUES (lower(hex(randomblob(16))), ?, ?, ?)", + (r["id"], EVENT_SENT, json.dumps({"step": s, "skipped": True}))) + stats["skipped"] += 1 + # Record before sending: a crash never sends the same step twice. + conn.execute("INSERT INTO license_events (id, license_id, event_type, details_json) " + "VALUES (lower(hex(randomblob(16))), ?, ?, ?)", + (r["id"], EVENT_SENT, json.dumps({"step": step, "consumed": int(r["consumed"])}))) + conn.commit() + ok = email_sender.send_trial_nurture( + r["email"], step=step, consumed=int(r["consumed"]), balance=int(r["balance"]), + unsubscribe_url=unsubscribe_url(r["id"]), + ) + stats["sent" if ok else "failed"] += 1 + except Exception: + logger.exception("trial nurture failed for license %s", r["id"]) + stats["failed"] += 1 + return stats diff --git a/app/config.py b/app/config.py index 9c45937..32a3c1a 100644 --- a/app/config.py +++ b/app/config.py @@ -108,6 +108,8 @@ class Settings(BaseSettings): DEPLETION_EMAIL_ENABLED: bool = True DEPLETION_EMAIL_COOLDOWN_DAYS: int = 25 # same episode (no credits added) never re-sends before this DEPLETION_EMAIL_TOPUP_EUR: int = 5 # amount preselected by the email's one-click link + NURTURE_EMAIL_ENABLED: bool = True # trial follow-up emails on days 1, 3 and 7 (each with unsubscribe) + NURTURE_UNSUBSCRIBE_BASE: str = "https://licenses.keyflint.dev" # Backup verification: restore the Litestream replica to a temp file and compare row counts. BACKUP_CHECK_INTERVAL_SECONDS: int = 3600 # 0 disables it diff --git a/app/infrastructure/email/transactional_email_service.py b/app/infrastructure/email/transactional_email_service.py index 78b92bd..fb3ba03 100644 --- a/app/infrastructure/email/transactional_email_service.py +++ b/app/infrastructure/email/transactional_email_service.py @@ -242,6 +242,66 @@ def send_credits_depleted(self, recipient_email: str, license_key: str, *, trial """ return self._dispatch(recipient=recipient_email, subject=subject, text_body=text_body, html_body=html_body) + def send_trial_nurture(self, recipient_email: str, *, step: int, consumed: int, balance: int, + unsubscribe_url: str) -> bool: + """Follow-up of the free trial (days 1, 3 and 7). Spanish, one action per email, unsubscribe link.""" + hub = "https://mcp.keyflint.dev" + if step == 1 and consumed == 0: + subject = "Tu primer extracto con Flint, en 1 minuto" + title = "Prueba Flint con un extracto real" + paras = ["Tu licencia de prueba aún no ha procesado nada. La forma más rápida de verlo:", + "Abre el procesador, arrastra un extracto Norma 43 (.n43 o .c43) que hayas descargado del banco " + "y pega tu licencia. En segundos tienes movimientos, saldos comprobados y un resumen para Excel.", + "No hay que instalar nada. Si el fichero falla, no se cobra."] + cta, url = "Abrir el procesador", f"{hub}/lote/" + elif step == 1: + subject = "Siguiente paso: que los extractos se procesen solos" + title = "Deja una carpeta vigilada" + paras = [f"Ya has usado {consumed} créditos. Para no repetirlo cada mes:", + "Con un comando, Flint crea la carpeta «Flint Extractos». Cada extracto que dejes en la " + "subcarpeta de un cliente se procesa solo y genera su informe y su resumen para Excel, " + "también después de reiniciar el ordenador."] + cta, url = "Activar la carpeta vigilada", f"{hub}/asesorias/#alta" + elif step == 3: + subject = "Norma 43 directo a A3, Sage o ContaSol" + title = "Del extracto al programa contable, sin picar" + paras = ["Además de leer y conciliar, Flint convierte el extracto en un fichero que importas en tu " + "programa de contabilidad. Los importes y las fechas salen del fichero del banco: Flint nunca " + "se los inventa, y lo que no encaja se marca para revisarlo.", + "Con la instalación local, los ficheros de tus clientes no salen del despacho. " + f"Te lo explicamos en {hub}/confianza/."] + cta, url = "Ver la conversión a ContaSol", f"{hub}/norma43-a-contasol/" + else: + subject = "Plan Despacho: una cuota fija para todo el despacho" + title = "Cuando quieras pasar del piloto al día a día" + paras = [f"Te quedan {balance} créditos de prueba.", + "El Plan Despacho Básico cuesta 49 €/mes y trae 2.500 créditos cada mes: unos 625 extractos " + "leídos y conciliados, 3 puestos y factura con NIF. Sin permanencia.", + "Si contratas con este mismo correo, tu licencia actual se convierte en la del plan: " + "no tienes que cambiar nada en tu ordenador."] + cta, url = "Ver el Plan Despacho", f"{hub}/precios/#despacho" + text_body = (f"Hola,\n\n" + "\n\n".join(paras) + f"\n\n{cta}: {url}\n\n" + "Dudas: responde a este correo o escribe a support@keyflint.dev\n\n" + f"--\nRecibes este correo porque pediste una licencia de prueba de Flint. " + f"Darte de baja: {unsubscribe_url}\n") + esc = html.escape + body = "".join(f'

{esc(x)}

' + for x in paras) + html_body = f""" + +{esc(subject)} + +
+
+
Flint
+

{esc(title)}

+{body} +{esc(cta)} +

¿Dudas? Responde a este correo o escribe a support@keyflint.dev.
+Recibes este correo porque pediste una licencia de prueba de Flint. Darme de baja

+
""" + return self._dispatch(recipient=recipient_email, subject=subject, text_body=text_body, html_body=html_body) + def send_ops_alert(self, recipient_email: str, subject: str, text_body: str) -> bool: """Plain-text operator alert (billing incidents). Never raises.""" safe = html.escape(text_body) diff --git a/app/main.py b/app/main.py index d68a078..d2353ee 100644 --- a/app/main.py +++ b/app/main.py @@ -76,13 +76,24 @@ def _maintenance_once() -> dict: from app.infrastructure.database.connection import create_connection from app.infrastructure.maintenance import litestream_active, run_maintenance + from app.application.services.trial_nurture import run_trial_nurture + from app.infrastructure.email.transactional_email_service import TransactionalEmailService + conn = create_connection() try: - return run_maintenance( + summary = run_maintenance( conn, retention_days=get_settings().USAGE_EVENTS_RETENTION_DAYS, checkpoint=not litestream_active(LITESTREAM_CONFIG), ) + try: + nurture = run_trial_nurture(conn, TransactionalEmailService()) + if any(nurture.values()): + summary["trial_nurture"] = nurture + logger.info(f"Trial nurture: {nurture}") + except Exception as exc: # follow-up emails must never stop maintenance + logger.error(f"Trial nurture failed: {exc}") + return summary finally: conn.close() diff --git a/app/presentation/api/v1/billing.py b/app/presentation/api/v1/billing.py index 1afb60d..9bcc554 100644 --- a/app/presentation/api/v1/billing.py +++ b/app/presentation/api/v1/billing.py @@ -20,6 +20,7 @@ from pydantic import BaseModel, Field from app.presentation.dependencies import ( + get_db, build_response_metadata, get_billing_service, require_admin_access, @@ -319,3 +320,21 @@ def retry_failed_license_emails( "data": billing_service.retry_failed_license_emails(), "metadata": build_response_metadata(http_request), } + + +@router.get("/unsubscribe", include_in_schema=False) +def unsubscribe(l: str = Query("", max_length=64), t: str = Query("", max_length=64), conn=Depends(get_db)): + """One-click opt-out from trial follow-up emails (link in every email). Idempotent.""" + from fastapi.responses import HTMLResponse + + from app.application.services.trial_nurture import record_opt_out, verify_unsubscribe + + ok = verify_unsubscribe(l, t) and record_opt_out(conn, l) + msg = ("Listo: no te enviaremos más correos de seguimiento. Tu licencia sigue funcionando igual." + if ok else "Este enlace de baja no es válido. Escríbenos a support@keyflint.dev y te damos de baja.") + return HTMLResponse( + f'' + f'Baja · Flint

{msg}

', + status_code=200 if ok else 400, + ) diff --git a/tests/tier1_features/test_trial_nurture.py b/tests/tier1_features/test_trial_nurture.py new file mode 100644 index 0000000..aba780e --- /dev/null +++ b/tests/tier1_features/test_trial_nurture.py @@ -0,0 +1,122 @@ +"""Tier 1: trial follow-up emails (days 1, 3, 7): once per step, catch-up sends only the latest, opt-out stops all.""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +from unittest import mock +from urllib.parse import parse_qs, urlparse + +from app.application.services.trial_nurture import run_trial_nurture +from app.config import get_settings +from app.infrastructure.database.connection import create_connection +from app.presentation.middlewares import rate_limiter +from tests.conftest import BaseKeyFlintTestCase + +SVC = "app.infrastructure.email.transactional_email_service.TransactionalEmailService" + + +class FakeSender: + def __init__(self) -> None: + self.calls: list[dict] = [] + + def send_trial_nurture(self, email, **kw): + self.calls.append({"email": email, **kw}) + return True + + +class TestTrialNurture(BaseKeyFlintTestCase): + def setUp(self) -> None: + super().setUp() + s = get_settings() + self._prev = (s.TRIAL_ENABLED, s.TRIAL_DAILY_CAP, s.NURTURE_EMAIL_ENABLED) + s.TRIAL_ENABLED, s.TRIAL_DAILY_CAP, s.NURTURE_EMAIL_ENABLED = True, 100, True + rate_limiter.reset() + + def tearDown(self) -> None: + s = get_settings() + s.TRIAL_ENABLED, s.TRIAL_DAILY_CAP, s.NURTURE_EMAIL_ENABLED = self._prev + super().tearDown() + + def _trial(self, email: str) -> str: + with mock.patch(f"{SVC}.send_license_issued", return_value=True) as send: + res = self.client.post("/api/v1/billing/trial", json={"email": email, "source": "mcp-hub"}) + self.assertEqual(res.status_code, 200, res.text) + return send.call_args.args[0].license_key + + def _run(self, days: float, sender: FakeSender): + conn = create_connection() + try: + return run_trial_nurture(conn, sender, now=datetime.now(timezone.utc) + timedelta(days=days)) + finally: + conn.close() + + def test_steps_once_each_and_tailored_to_usage(self): + self.require_app() + self._trial("nurture@gestoria.es") + s = FakeSender() + self.assertEqual(self._run(0.5, s)["sent"], 0) + self._run(1.1, s) + self._run(1.2, s) # same step: not repeated + self.assertEqual([c["step"] for c in s.calls], [1]) + self.assertEqual(s.calls[0]["consumed"], 0) + self._run(3.1, s) + self._run(7.1, s) + self._run(8.0, s) + self.assertEqual([c["step"] for c in s.calls], [1, 3, 7]) + self.assertTrue(all("/api/v1/billing/unsubscribe?" in c["unsubscribe_url"] for c in s.calls)) + + def test_catch_up_sends_only_latest_step(self): + self.require_app() + self._trial("late@gestoria.es") + s = FakeSender() + stats = self._run(7.5, s) + self.assertEqual([c["step"] for c in s.calls], [7]) + self.assertEqual(stats["skipped"], 2) + + def test_unsubscribe_stops_everything_and_bad_token_fails(self): + self.require_app() + self._trial("baja@gestoria.es") + s = FakeSender() + self._run(1.1, s) + url = urlparse(s.calls[0]["unsubscribe_url"]) + q = parse_qs(url.query) + bad = self.client.get(f"{url.path}?l={q['l'][0]}&t=deadbeef") + self.assertEqual(bad.status_code, 400) + ok = self.client.get(f"{url.path}?{url.query}") + self.assertEqual(ok.status_code, 200, ok.text) + self.assertIn("no te enviaremos", ok.text) + self.assertEqual(self.client.get(f"{url.path}?{url.query}").status_code, 200) # idempotent + self._run(3.1, s) + self._run(7.1, s) + self.assertEqual(len(s.calls), 1) + + def test_disabled_and_real_template_renders(self): + self.require_app() + self._trial("off@gestoria.es") + get_settings().NURTURE_EMAIL_ENABLED = False + s = FakeSender() + self._run(1.1, s) + self.assertEqual(s.calls, []) + from app.infrastructure.email.transactional_email_service import TransactionalEmailService + svc = TransactionalEmailService() + for step, consumed in ((1, 0), (1, 5), (3, 5), (7, 5)): + with mock.patch.object(svc, "_dispatch", return_value=True) as d: + self.assertTrue(svc.send_trial_nurture("x@y.es", step=step, consumed=consumed, balance=20, + unsubscribe_url="https://u/x?l=1&t=2")) + kw = d.call_args.kwargs + self.assertIn("Darme de baja", kw["html_body"]) + self.assertIn("https://u/x?l=1&t=2", kw["text_body"]) + self.assertIn("mcp.keyflint.dev", kw["text_body"]) + + def test_english_trials_are_skipped(self): + self.require_app() + key = self._trial("en@company.com") + conn = create_connection() + try: + conn.execute("UPDATE licenses SET metadata_json = json_set(metadata_json, '$.lang', 'en') WHERE license_key = ?", (key,)) + conn.commit() + finally: + conn.close() + s = FakeSender() + self._run(1.1, s) + self.assertEqual(s.calls, [])