feat: self-serve 14-day free trial (activate from demo, embed snippet, scheduler pauses expired trials)
Browse files- app/demo_ui/index.html +53 -4
- app/models.py +6 -0
- app/routes/demo.py +74 -1
- app/scheduler.py +63 -0
- migrations/versions/0022_trial_ends_at.py +28 -0
app/demo_ui/index.html
CHANGED
|
@@ -138,10 +138,22 @@
|
|
| 138 |
</div>
|
| 139 |
<p class="hint">Esta demo se borra sola en 48 horas.</p>
|
| 140 |
<div class="ctablock">
|
| 141 |
-
<h3>
|
| 142 |
-
<p>
|
| 143 |
-
<
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
</div>
|
| 146 |
<div class="opine" id="opinar">
|
| 147 |
<h3>Deja tu opinión</h3>
|
|
@@ -399,8 +411,10 @@ function showExpired(){
|
|
| 399 |
document.getElementById("expired-note").hidden = false;
|
| 400 |
}
|
| 401 |
|
|
|
|
| 402 |
function showReady(slug){
|
| 403 |
show("state-c");
|
|
|
|
| 404 |
document.getElementById("share-url").value = location.origin + "/demo?d=" + slug;
|
| 405 |
if (!widgetMounted) {
|
| 406 |
widgetMounted = true;
|
|
@@ -444,6 +458,41 @@ document.getElementById("retry-btn").addEventListener("click", function(){
|
|
| 444 |
document.getElementById("url-input").focus();
|
| 445 |
});
|
| 446 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
document.getElementById("copy-btn").addEventListener("click", function(){
|
| 448 |
var i = document.getElementById("share-url");
|
| 449 |
i.select(); i.setSelectionRange(0, 99999);
|
|
|
|
| 138 |
</div>
|
| 139 |
<p class="hint">Esta demo se borra sola en 48 horas.</p>
|
| 140 |
<div class="ctablock">
|
| 141 |
+
<h3>Pruébalo gratis 14 días en tu web</h3>
|
| 142 |
+
<p>Sin tarjeta. Pega un código y tu bot atiende a tus clientes ya. A los 14 días, si te sirve, 29 € al mes sin permanencia; si no, se desactiva solo.</p>
|
| 143 |
+
<div id="activate-form" class="sharerow">
|
| 144 |
+
<input id="activate-email" type="email" inputmode="email" placeholder="tu@email.com" autocomplete="email" />
|
| 145 |
+
<button id="activate-btn" class="btn" type="button">Activar gratis 14 días</button>
|
| 146 |
+
</div>
|
| 147 |
+
<p id="activate-err" class="hint" style="color:#ffe0d6" hidden></p>
|
| 148 |
+
<div id="activated" hidden>
|
| 149 |
+
<p><b>Listo, tu bot está activo 14 días.</b> Pega este código en tu web, justo antes de </body>:</p>
|
| 150 |
+
<div class="sharerow">
|
| 151 |
+
<input id="embed-code" type="text" readonly />
|
| 152 |
+
<button id="copy-embed" class="btn small" type="button">Copiar</button>
|
| 153 |
+
</div>
|
| 154 |
+
<p class="more">Te lo hemos enviado también por email. Gestiona tu bot (textos, color, idiomas) en <a id="portal-link" href="https://atendyo.com/portal" target="_blank" rel="noopener">tu panel</a>.</p>
|
| 155 |
+
</div>
|
| 156 |
+
<span class="more"><a href="https://buy.stripe.com/eVq5kC5h6cQS9qa5ar5wI04">o paga ya 29 €/mes</a> · <a href="https://buy.stripe.com/5kQcN4bFu2ce31MfP55wI02">pago único 200 €</a></span>
|
| 157 |
</div>
|
| 158 |
<div class="opine" id="opinar">
|
| 159 |
<h3>Deja tu opinión</h3>
|
|
|
|
| 411 |
document.getElementById("expired-note").hidden = false;
|
| 412 |
}
|
| 413 |
|
| 414 |
+
var activeSlug = "";
|
| 415 |
function showReady(slug){
|
| 416 |
show("state-c");
|
| 417 |
+
activeSlug = slug;
|
| 418 |
document.getElementById("share-url").value = location.origin + "/demo?d=" + slug;
|
| 419 |
if (!widgetMounted) {
|
| 420 |
widgetMounted = true;
|
|
|
|
| 458 |
document.getElementById("url-input").focus();
|
| 459 |
});
|
| 460 |
|
| 461 |
+
// Self-serve free trial: activate the demo into a live 14-day trial, no card.
|
| 462 |
+
document.getElementById("activate-btn").addEventListener("click", function(){
|
| 463 |
+
var email = (document.getElementById("activate-email").value || "").trim();
|
| 464 |
+
var err = document.getElementById("activate-err");
|
| 465 |
+
err.hidden = true;
|
| 466 |
+
if (email.indexOf("@") < 0) { err.textContent = "Pon un email válido."; err.hidden = false; return; }
|
| 467 |
+
var btn = document.getElementById("activate-btn");
|
| 468 |
+
btn.disabled = true; btn.textContent = "Activando…";
|
| 469 |
+
fetch(API + "/demo/" + encodeURIComponent(activeSlug) + "/activate", {
|
| 470 |
+
method: "POST",
|
| 471 |
+
headers: {"Content-Type": "application/json"},
|
| 472 |
+
body: JSON.stringify({email: email})
|
| 473 |
+
})
|
| 474 |
+
.then(function(r){ return r.ok ? r.json() : r.json().then(function(j){ throw new Error(j.detail || "error"); }); })
|
| 475 |
+
.then(function(res){
|
| 476 |
+
document.getElementById("activate-form").hidden = true;
|
| 477 |
+
document.getElementById("embed-code").value = res.embed;
|
| 478 |
+
if (res.portal_url) document.getElementById("portal-link").href = res.portal_url;
|
| 479 |
+
document.getElementById("activated").hidden = false;
|
| 480 |
+
})
|
| 481 |
+
.catch(function(e){
|
| 482 |
+
err.textContent = (e && e.message) ? e.message : "No se pudo activar. Inténtalo de nuevo.";
|
| 483 |
+
err.hidden = false;
|
| 484 |
+
btn.disabled = false; btn.textContent = "Activar gratis 14 días";
|
| 485 |
+
});
|
| 486 |
+
});
|
| 487 |
+
|
| 488 |
+
document.getElementById("copy-embed").addEventListener("click", function(){
|
| 489 |
+
var i = document.getElementById("embed-code");
|
| 490 |
+
i.select(); i.setSelectionRange(0, 99999);
|
| 491 |
+
try { document.execCommand("copy"); } catch (e) {}
|
| 492 |
+
var b = document.getElementById("copy-embed");
|
| 493 |
+
var old = b.textContent; b.textContent = "Copiado"; setTimeout(function(){ b.textContent = old; }, 1500);
|
| 494 |
+
});
|
| 495 |
+
|
| 496 |
document.getElementById("copy-btn").addEventListener("click", function(){
|
| 497 |
var i = document.getElementById("share-url");
|
| 498 |
i.select(); i.setSelectionRange(0, 99999);
|
app/models.py
CHANGED
|
@@ -100,6 +100,12 @@ class Tenant(Base):
|
|
| 100 |
demo_expires_at: Mapped[datetime | None] = mapped_column(
|
| 101 |
DateTime(timezone=True), nullable=True
|
| 102 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
# Free-text instructions from the merchant appended to the system prompt
|
| 104 |
# ("we are a consultancy, never quote delivery times", "your job is to sell
|
| 105 |
# product X"...). Lets each business tune its assistant's behavior.
|
|
|
|
| 100 |
demo_expires_at: Mapped[datetime | None] = mapped_column(
|
| 101 |
DateTime(timezone=True), nullable=True
|
| 102 |
)
|
| 103 |
+
# Self-serve free trial: a demo the prospect ACTIVATED (no card). The bot
|
| 104 |
+
# stays live on their site until trial_ends_at; the scheduler then pauses it
|
| 105 |
+
# and emails the payment link, unless a Stripe subscription went active.
|
| 106 |
+
trial_ends_at: Mapped[datetime | None] = mapped_column(
|
| 107 |
+
DateTime(timezone=True), nullable=True
|
| 108 |
+
)
|
| 109 |
# Free-text instructions from the merchant appended to the system prompt
|
| 110 |
# ("we are a consultancy, never quote delivery times", "your job is to sell
|
| 111 |
# product X"...). Lets each business tune its assistant's behavior.
|
app/routes/demo.py
CHANGED
|
@@ -49,13 +49,14 @@ from app.rag import extract
|
|
| 49 |
from app.rag.chunk import chunk_text
|
| 50 |
from app.ratelimit import RateLimiter
|
| 51 |
from app.store import get_config, upsert_config
|
| 52 |
-
from app.tenancy import create_tenant, get_tenant_by_slug
|
| 53 |
|
| 54 |
log = logging.getLogger(__name__)
|
| 55 |
|
| 56 |
router = APIRouter()
|
| 57 |
|
| 58 |
DEMO_TTL_HOURS = 48
|
|
|
|
| 59 |
DEMO_DAILY_CAP = 40 # global starts/day, persisted in Config under _DAILY_KEY
|
| 60 |
DEMO_MAX_ACTIVE = 100 # live demo tenants at any moment
|
| 61 |
DEMO_STARTS_PER_IP_PER_HOUR = 3
|
|
@@ -458,6 +459,78 @@ async def demo_start(
|
|
| 458 |
return {"slug": slug, "stage": "leyendo", "expires_hours": DEMO_TTL_HOURS}
|
| 459 |
|
| 460 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
@router.get("/demo/status")
|
| 462 |
async def demo_status(d: str, db: AsyncSession = Depends(get_session)) -> dict:
|
| 463 |
"""Live progress for the demo page. Falls back to the DB when the
|
|
|
|
| 49 |
from app.rag.chunk import chunk_text
|
| 50 |
from app.ratelimit import RateLimiter
|
| 51 |
from app.store import get_config, upsert_config
|
| 52 |
+
from app.tenancy import create_tenant, generate_dashboard_token, get_tenant_by_slug
|
| 53 |
|
| 54 |
log = logging.getLogger(__name__)
|
| 55 |
|
| 56 |
router = APIRouter()
|
| 57 |
|
| 58 |
DEMO_TTL_HOURS = 48
|
| 59 |
+
TRIAL_DAYS = 14 # self-serve free trial length (no card upfront)
|
| 60 |
DEMO_DAILY_CAP = 40 # global starts/day, persisted in Config under _DAILY_KEY
|
| 61 |
DEMO_MAX_ACTIVE = 100 # live demo tenants at any moment
|
| 62 |
DEMO_STARTS_PER_IP_PER_HOUR = 3
|
|
|
|
| 459 |
return {"slug": slug, "stage": "leyendo", "expires_hours": DEMO_TTL_HOURS}
|
| 460 |
|
| 461 |
|
| 462 |
+
def _embed_snippet(slug: str) -> str:
|
| 463 |
+
return f'<script src="{PUBLIC_DEMO_BASE}/widget.js?t={slug}" defer></script>'
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
class DemoActivateIn(BaseModel):
|
| 467 |
+
email: str = ""
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
@router.post("/demo/{slug}/activate")
|
| 471 |
+
async def demo_activate(
|
| 472 |
+
slug: str, body: DemoActivateIn, db: AsyncSession = Depends(get_session)
|
| 473 |
+
) -> dict:
|
| 474 |
+
"""Self-serve free trial: the prospect liked their demo and clicks 'activate'.
|
| 475 |
+
We promote the disposable demo tenant into a real 14-day trial (no card): it
|
| 476 |
+
stops self-destructing, the bot stays live on their site, and they get the
|
| 477 |
+
embed snippet + a portal login. The scheduler pauses it at trial end unless a
|
| 478 |
+
subscription went active. No human (Victor) in the loop."""
|
| 479 |
+
if "@" not in (body.email or ""):
|
| 480 |
+
raise HTTPException(status_code=422, detail="Indica un email válido.")
|
| 481 |
+
tenant = await get_tenant_by_slug(db, slug)
|
| 482 |
+
if tenant is None:
|
| 483 |
+
raise HTTPException(status_code=404, detail="Demo no encontrada o caducada.")
|
| 484 |
+
|
| 485 |
+
already = bool(tenant.trial_ends_at) and not tenant.is_demo
|
| 486 |
+
if not already:
|
| 487 |
+
now = datetime.now(UTC)
|
| 488 |
+
tenant.is_demo = False
|
| 489 |
+
tenant.demo_expires_at = None
|
| 490 |
+
tenant.trial_ends_at = now + timedelta(days=TRIAL_DAYS)
|
| 491 |
+
tenant.chatbot_enabled = True
|
| 492 |
+
tenant.disabled_reason = ""
|
| 493 |
+
tenant.support_email = body.email
|
| 494 |
+
if not tenant.dashboard_token:
|
| 495 |
+
await generate_dashboard_token(db, tenant)
|
| 496 |
+
await db.flush()
|
| 497 |
+
await db.commit()
|
| 498 |
+
_spawn(_email_trial_activated(body.email, slug, tenant.dashboard_token))
|
| 499 |
+
|
| 500 |
+
return {
|
| 501 |
+
"status": "activated",
|
| 502 |
+
"trial_days": TRIAL_DAYS,
|
| 503 |
+
"embed": _embed_snippet(slug),
|
| 504 |
+
"dashboard_token": tenant.dashboard_token,
|
| 505 |
+
"portal_url": f"{PUBLIC_DEMO_BASE}/portal",
|
| 506 |
+
}
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
async def _email_trial_activated(email: str, slug: str, token: str) -> None:
|
| 510 |
+
"""Confirm the trial + hand over the embed snippet and portal login."""
|
| 511 |
+
if not email or "@" not in email:
|
| 512 |
+
return
|
| 513 |
+
snippet = _embed_snippet(slug)
|
| 514 |
+
body = (
|
| 515 |
+
"Hola,\n\n"
|
| 516 |
+
f"Tu asistente de Atendyo ya está activo, gratis durante {TRIAL_DAYS} días, "
|
| 517 |
+
"sin tarjeta.\n\n"
|
| 518 |
+
"1) Pega este código en tu web (antes de </body>) y el bot aparece solo:\n"
|
| 519 |
+
f"{snippet}\n\n"
|
| 520 |
+
" - Shopify: Tema > Editar código > theme.liquid, antes de </body>.\n"
|
| 521 |
+
" - WooCommerce/WordPress: un bloque HTML o el footer del tema.\n\n"
|
| 522 |
+
f"2) Gestiona tu bot (textos, color, idiomas) entrando en {PUBLIC_DEMO_BASE}/portal "
|
| 523 |
+
f"con esta clave:\n{token}\n\n"
|
| 524 |
+
f"A los {TRIAL_DAYS} días, si te sirve, son 29 euros al mes sin permanencia. "
|
| 525 |
+
"Si no, no haces nada y se desactiva solo.\n\n"
|
| 526 |
+
"Un saludo,\nVictor — Atendyo"
|
| 527 |
+
)
|
| 528 |
+
try:
|
| 529 |
+
await mailer.send_email(get_settings(), email, "Tu bot ya está activo (prueba gratis)", body)
|
| 530 |
+
except Exception: # noqa: BLE001 - email must never break activation
|
| 531 |
+
log.warning("trial activation email failed (non-fatal)", exc_info=True)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
@router.get("/demo/status")
|
| 535 |
async def demo_status(d: str, db: AsyncSession = Depends(get_session)) -> dict:
|
| 536 |
"""Live progress for the demo page. Falls back to the DB when the
|
app/scheduler.py
CHANGED
|
@@ -15,6 +15,7 @@ from datetime import UTC, datetime, timedelta
|
|
| 15 |
from sqlalchemy import or_, select
|
| 16 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 17 |
|
|
|
|
| 18 |
from app.config import get_settings
|
| 19 |
from app.db import get_sessionmaker
|
| 20 |
from app.models import KnowledgeSource, Tenant
|
|
@@ -28,10 +29,14 @@ _KEY = "last_url_reindex"
|
|
| 28 |
_PRODUCT_KEY = "last_product_sync"
|
| 29 |
_BILLING_KEY = "last_billing_reconcile"
|
| 30 |
_DEMO_PURGE_KEY = "last_demo_purge"
|
|
|
|
| 31 |
REINDEX_EVERY = timedelta(days=7)
|
| 32 |
PRODUCT_SYNC_EVERY = timedelta(days=1) # catalog text changes more often than docs
|
| 33 |
BILLING_RECONCILE_EVERY = timedelta(days=1)
|
| 34 |
DEMO_PURGE_EVERY = timedelta(days=1) # demos live 48h; a daily sweep is enough
|
|
|
|
|
|
|
|
|
|
| 35 |
CHECK_EVERY_SECONDS = 6 * 3600
|
| 36 |
FIRST_DELAY_SECONDS = 120 # let boot settle before the first check
|
| 37 |
|
|
@@ -210,6 +215,63 @@ async def _maybe_purge_demos() -> None:
|
|
| 210 |
log.info("demo purge removed %d expired demo tenant(s)", n)
|
| 211 |
|
| 212 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
async def run_periodic_reindex() -> None:
|
| 214 |
await asyncio.sleep(FIRST_DELAY_SECONDS)
|
| 215 |
while True:
|
|
@@ -218,6 +280,7 @@ async def run_periodic_reindex() -> None:
|
|
| 218 |
# reindex for the same reason — an expired demo gets no last crawl.
|
| 219 |
for tick in (
|
| 220 |
_maybe_reconcile_billing,
|
|
|
|
| 221 |
_maybe_purge_demos,
|
| 222 |
_maybe_reindex,
|
| 223 |
_maybe_sync_products,
|
|
|
|
| 15 |
from sqlalchemy import or_, select
|
| 16 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 17 |
|
| 18 |
+
from app import mailer
|
| 19 |
from app.config import get_settings
|
| 20 |
from app.db import get_sessionmaker
|
| 21 |
from app.models import KnowledgeSource, Tenant
|
|
|
|
| 29 |
_PRODUCT_KEY = "last_product_sync"
|
| 30 |
_BILLING_KEY = "last_billing_reconcile"
|
| 31 |
_DEMO_PURGE_KEY = "last_demo_purge"
|
| 32 |
+
_TRIAL_KEY = "last_trial_sweep"
|
| 33 |
REINDEX_EVERY = timedelta(days=7)
|
| 34 |
PRODUCT_SYNC_EVERY = timedelta(days=1) # catalog text changes more often than docs
|
| 35 |
BILLING_RECONCILE_EVERY = timedelta(days=1)
|
| 36 |
DEMO_PURGE_EVERY = timedelta(days=1) # demos live 48h; a daily sweep is enough
|
| 37 |
+
TRIAL_SWEEP_EVERY = timedelta(hours=12) # pause trials promptly once they expire
|
| 38 |
+
# 29 EUR/mo self-serve link (mirrors app/routes/demo.py MONTHLY_BUY_LINK).
|
| 39 |
+
TRIAL_PAY_LINK = "https://buy.stripe.com/eVq5kC5h6cQS9qa5ar5wI04"
|
| 40 |
CHECK_EVERY_SECONDS = 6 * 3600
|
| 41 |
FIRST_DELAY_SECONDS = 120 # let boot settle before the first check
|
| 42 |
|
|
|
|
| 215 |
log.info("demo purge removed %d expired demo tenant(s)", n)
|
| 216 |
|
| 217 |
|
| 218 |
+
async def _email_trial_ended(email: str, slug: str) -> None:
|
| 219 |
+
body = (
|
| 220 |
+
"Hola,\n\n"
|
| 221 |
+
"Tu prueba gratis de Atendyo ha terminado y el bot se ha desactivado en tu "
|
| 222 |
+
"web. Si te ha sido útil, actívalo de nuevo por 29 euros al mes, sin "
|
| 223 |
+
"permanencia y cancelas cuando quieras:\n"
|
| 224 |
+
f"{TRIAL_PAY_LINK}\n\n"
|
| 225 |
+
"En cuanto pagues, vuelve a funcionar al instante con toda tu configuración "
|
| 226 |
+
"intacta. Si no, no tienes que hacer nada.\n\n"
|
| 227 |
+
"Un saludo,\nVictor — Atendyo"
|
| 228 |
+
)
|
| 229 |
+
try:
|
| 230 |
+
await mailer.send_email(get_settings(), email, "Tu prueba de Atendyo ha terminado", body)
|
| 231 |
+
except Exception: # noqa: BLE001 - email must never break the sweep
|
| 232 |
+
log.warning("trial-ended email failed for %s", slug, exc_info=True)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
async def pause_expired_trials(db: AsyncSession) -> int:
|
| 236 |
+
"""Pause self-serve trials whose 14 days are up and who never subscribed:
|
| 237 |
+
flip chatbot_enabled off (the kill-switch already cuts service everywhere,
|
| 238 |
+
even with the embed still on their site) and email the payment link. A paid
|
| 239 |
+
tenant has a stripe_subscription_id and is skipped. chatbot_enabled=False is
|
| 240 |
+
the idempotency guard — a paused trial is never reselected/re-emailed."""
|
| 241 |
+
now = datetime.now(UTC)
|
| 242 |
+
expired = (
|
| 243 |
+
await db.execute(
|
| 244 |
+
select(Tenant).where(
|
| 245 |
+
Tenant.is_demo.is_(False),
|
| 246 |
+
Tenant.trial_ends_at.is_not(None),
|
| 247 |
+
Tenant.trial_ends_at < now,
|
| 248 |
+
Tenant.chatbot_enabled.is_(True),
|
| 249 |
+
Tenant.stripe_subscription_id == "",
|
| 250 |
+
)
|
| 251 |
+
)
|
| 252 |
+
).scalars().all()
|
| 253 |
+
for tenant in expired:
|
| 254 |
+
log.info("trial sweep: pausing expired trial %s", tenant.slug)
|
| 255 |
+
tenant.chatbot_enabled = False
|
| 256 |
+
tenant.disabled_reason = "trial"
|
| 257 |
+
if tenant.support_email:
|
| 258 |
+
await _email_trial_ended(tenant.support_email, tenant.slug)
|
| 259 |
+
await db.commit()
|
| 260 |
+
return len(expired)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
async def _maybe_pause_trials() -> None:
|
| 264 |
+
async with get_sessionmaker()() as db:
|
| 265 |
+
now = datetime.now(UTC)
|
| 266 |
+
if not _due(await get_config(db, _TRIAL_KEY) or {}, TRIAL_SWEEP_EVERY, now):
|
| 267 |
+
return
|
| 268 |
+
n = await pause_expired_trials(db)
|
| 269 |
+
await upsert_config(db, _TRIAL_KEY, {"at": now.isoformat()})
|
| 270 |
+
await db.commit()
|
| 271 |
+
if n:
|
| 272 |
+
log.info("trial sweep paused %d expired trial(s)", n)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
async def run_periodic_reindex() -> None:
|
| 276 |
await asyncio.sleep(FIRST_DELAY_SECONDS)
|
| 277 |
while True:
|
|
|
|
| 280 |
# reindex for the same reason — an expired demo gets no last crawl.
|
| 281 |
for tick in (
|
| 282 |
_maybe_reconcile_billing,
|
| 283 |
+
_maybe_pause_trials,
|
| 284 |
_maybe_purge_demos,
|
| 285 |
_maybe_reindex,
|
| 286 |
_maybe_sync_products,
|
migrations/versions/0022_trial_ends_at.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""tenants.trial_ends_at: self-serve free-trial deadline (no card upfront).
|
| 2 |
+
|
| 3 |
+
Additive, idempotent on Postgres (ADD COLUMN IF NOT EXISTS). On other dialects
|
| 4 |
+
it is a no-op (tests/dev use create_all which already has the column).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from alembic import op
|
| 10 |
+
|
| 11 |
+
revision = "0022_trial_ends_at"
|
| 12 |
+
down_revision = "0021_reviews"
|
| 13 |
+
branch_labels = None
|
| 14 |
+
depends_on = None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def upgrade() -> None:
|
| 18 |
+
if op.get_bind().dialect.name != "postgresql":
|
| 19 |
+
return
|
| 20 |
+
op.execute(
|
| 21 |
+
"ALTER TABLE tenants ADD COLUMN IF NOT EXISTS trial_ends_at TIMESTAMPTZ"
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def downgrade() -> None:
|
| 26 |
+
if op.get_bind().dialect.name != "postgresql":
|
| 27 |
+
return
|
| 28 |
+
op.execute("ALTER TABLE tenants DROP COLUMN IF EXISTS trial_ends_at")
|