Spaces:
Sleeping
Sleeping
axeronis commited on
Commit ·
9a6c2ea
1
Parent(s): b36e51b
feat: add subscription expiry email notifications (3d, 1d, 0d before expiry)
Browse files- backend/app/main.py +69 -1
- backend/app/services/email.py +66 -0
backend/app/main.py
CHANGED
|
@@ -223,7 +223,8 @@ async def on_startup():
|
|
| 223 |
|
| 224 |
# Start Background Tasks
|
| 225 |
asyncio.create_task(reactivation_scheduler_loop())
|
| 226 |
-
asyncio.create_task(hot_leads_scheduler_loop()) #
|
|
|
|
| 227 |
|
| 228 |
|
| 229 |
@app.on_event("shutdown")
|
|
@@ -302,6 +303,73 @@ async def reactivation_scheduler_loop():
|
|
| 302 |
await asyncio.sleep(60 * 60) # Retry in 1 hour
|
| 303 |
|
| 304 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
|
| 306 |
@app.get("/")
|
| 307 |
async def root():
|
|
|
|
| 223 |
|
| 224 |
# Start Background Tasks
|
| 225 |
asyncio.create_task(reactivation_scheduler_loop())
|
| 226 |
+
asyncio.create_task(hot_leads_scheduler_loop()) # Hourly for hot leads
|
| 227 |
+
asyncio.create_task(subscription_expiry_scheduler_loop()) # Daily expiry warnings
|
| 228 |
|
| 229 |
|
| 230 |
@app.on_event("shutdown")
|
|
|
|
| 303 |
await asyncio.sleep(60 * 60) # Retry in 1 hour
|
| 304 |
|
| 305 |
|
| 306 |
+
async def subscription_expiry_scheduler_loop():
|
| 307 |
+
"""
|
| 308 |
+
Background loop to check for expiring subscriptions and send email warnings.
|
| 309 |
+
Runs daily, sends warnings at 3 days, 1 day, and 0 days before expiry.
|
| 310 |
+
"""
|
| 311 |
+
from app.core.database import async_session_factory
|
| 312 |
+
from sqlmodel import select
|
| 313 |
+
from app.models.tenant import Tenant
|
| 314 |
+
from app.models.user import User
|
| 315 |
+
from app.services.email import get_email_service
|
| 316 |
+
from datetime import datetime, timedelta
|
| 317 |
+
|
| 318 |
+
logger.info("📧 Subscription Expiry Scheduler initialized (runs daily)")
|
| 319 |
+
|
| 320 |
+
# Wait 10 minutes after startup before first run
|
| 321 |
+
await asyncio.sleep(10 * 60)
|
| 322 |
+
|
| 323 |
+
while True:
|
| 324 |
+
try:
|
| 325 |
+
logger.info("📧 Checking for expiring subscriptions...")
|
| 326 |
+
email_service = get_email_service()
|
| 327 |
+
|
| 328 |
+
async with async_session_factory() as session:
|
| 329 |
+
now = datetime.utcnow()
|
| 330 |
+
|
| 331 |
+
# Find tenants expiring in 3 days, 1 day, or today
|
| 332 |
+
for days_left in [3, 1, 0]:
|
| 333 |
+
target_date = now + timedelta(days=days_left)
|
| 334 |
+
start_of_day = target_date.replace(hour=0, minute=0, second=0, microsecond=0)
|
| 335 |
+
end_of_day = target_date.replace(hour=23, minute=59, second=59, microsecond=999999)
|
| 336 |
+
|
| 337 |
+
stmt = select(Tenant).where(
|
| 338 |
+
Tenant.subscription_end >= start_of_day,
|
| 339 |
+
Tenant.subscription_end <= end_of_day,
|
| 340 |
+
Tenant.subscription_status == 'active'
|
| 341 |
+
)
|
| 342 |
+
result = await session.execute(stmt)
|
| 343 |
+
expiring_tenants = result.scalars().all()
|
| 344 |
+
|
| 345 |
+
for tenant in expiring_tenants:
|
| 346 |
+
# Find owner email
|
| 347 |
+
user_stmt = select(User).where(
|
| 348 |
+
User.tenant_id == tenant.id,
|
| 349 |
+
User.role == 'owner'
|
| 350 |
+
)
|
| 351 |
+
user_result = await session.execute(user_stmt)
|
| 352 |
+
owner = user_result.scalar_one_or_none()
|
| 353 |
+
|
| 354 |
+
if owner and owner.email:
|
| 355 |
+
await email_service.send_subscription_expiry_warning(
|
| 356 |
+
to_email=owner.email,
|
| 357 |
+
company_name=tenant.name or tenant.business_name or "Your Company",
|
| 358 |
+
days_remaining=days_left,
|
| 359 |
+
plan_name=tenant.subscription_plan or "trial"
|
| 360 |
+
)
|
| 361 |
+
logger.info(f"📧 Sent expiry warning to {owner.email} ({days_left} days left)")
|
| 362 |
+
|
| 363 |
+
# Sleep 24 hours
|
| 364 |
+
await asyncio.sleep(24 * 60 * 60)
|
| 365 |
+
|
| 366 |
+
except asyncio.CancelledError:
|
| 367 |
+
logger.info("Subscription expiry scheduler cancelled")
|
| 368 |
+
break
|
| 369 |
+
except Exception as e:
|
| 370 |
+
logger.error(f"Subscription expiry scheduler error: {e}")
|
| 371 |
+
await asyncio.sleep(60 * 60) # Retry in 1 hour
|
| 372 |
+
|
| 373 |
|
| 374 |
@app.get("/")
|
| 375 |
async def root():
|
backend/app/services/email.py
CHANGED
|
@@ -359,6 +359,72 @@ class EmailService:
|
|
| 359 |
text_body=text_body
|
| 360 |
)
|
| 361 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
|
| 363 |
# Singleton instance
|
| 364 |
_email_service = None
|
|
|
|
| 359 |
text_body=text_body
|
| 360 |
)
|
| 361 |
|
| 362 |
+
async def send_subscription_expiry_warning(
|
| 363 |
+
self,
|
| 364 |
+
to_email: str,
|
| 365 |
+
company_name: str,
|
| 366 |
+
days_remaining: int,
|
| 367 |
+
plan_name: str
|
| 368 |
+
) -> bool:
|
| 369 |
+
"""Send subscription expiry warning email."""
|
| 370 |
+
subject = f"⚠️ Подписка истекает через {days_remaining} дн. - {settings.APP_NAME}"
|
| 371 |
+
|
| 372 |
+
html_body = f"""
|
| 373 |
+
<html>
|
| 374 |
+
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; background: #f8fafc;">
|
| 375 |
+
<div style="max-width: 600px; margin: 0 auto; padding: 20px;">
|
| 376 |
+
<div style="background: white; border-radius: 12px; padding: 30px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
|
| 377 |
+
<h2 style="color: #f59e0b; margin-top: 0;">⚠️ Подписка скоро истекает</h2>
|
| 378 |
+
|
| 379 |
+
<p>Здравствуйте!</p>
|
| 380 |
+
|
| 381 |
+
<p>Ваша подписка на план <strong>{plan_name.upper()}</strong> для компании <strong>{company_name}</strong> истекает через <strong>{days_remaining} дн.</strong></p>
|
| 382 |
+
|
| 383 |
+
<div style="background: #fef3c7; border-left: 4px solid #f59e0b; padding: 15px; margin: 20px 0; border-radius: 0 8px 8px 0;">
|
| 384 |
+
<p style="margin: 0;">После истечения подписки:</p>
|
| 385 |
+
<ul style="margin: 10px 0 0 0; padding-left: 20px;">
|
| 386 |
+
<li>AI-бот перестанет отвечать на сообщения</li>
|
| 387 |
+
<li>Новые диалоги не будут создаваться</li>
|
| 388 |
+
<li>Все ваши данные сохранятся</li>
|
| 389 |
+
</ul>
|
| 390 |
+
</div>
|
| 391 |
+
|
| 392 |
+
<p>Продлите подписку сейчас, чтобы не терять клиентов!</p>
|
| 393 |
+
|
| 394 |
+
<a href="https://microfunnel.online/settings/billing" style="display: inline-block; background: linear-gradient(135deg, #6366f1, #8b5cf6); color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: bold; margin: 15px 0;">
|
| 395 |
+
Продлить подписку
|
| 396 |
+
</a>
|
| 397 |
+
|
| 398 |
+
<p style="color: #6b7280; font-size: 14px; margin-top: 30px; border-top: 1px solid #e5e7eb; padding-top: 20px;">
|
| 399 |
+
С уважением,<br>
|
| 400 |
+
Команда {settings.APP_NAME}
|
| 401 |
+
</p>
|
| 402 |
+
</div>
|
| 403 |
+
</div>
|
| 404 |
+
</body>
|
| 405 |
+
</html>
|
| 406 |
+
"""
|
| 407 |
+
|
| 408 |
+
text_body = f"""
|
| 409 |
+
⚠️ Подписка скоро истекает
|
| 410 |
+
|
| 411 |
+
Ваша подписка на план {plan_name.upper()} для компании {company_name} истекает через {days_remaining} дн.
|
| 412 |
+
|
| 413 |
+
После истечения подписки:
|
| 414 |
+
- AI-бот перестанет отвечать на сообщения
|
| 415 |
+
- Новые диалоги не будут создаваться
|
| 416 |
+
- Все ваши данные сохранятся
|
| 417 |
+
|
| 418 |
+
Продлите подписку: https://microfunnel.online/settings/billing
|
| 419 |
+
"""
|
| 420 |
+
|
| 421 |
+
return await self.send_email(
|
| 422 |
+
to=[to_email],
|
| 423 |
+
subject=subject,
|
| 424 |
+
html_body=html_body,
|
| 425 |
+
text_body=text_body
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
|
| 429 |
# Singleton instance
|
| 430 |
_email_service = None
|