ifixkart-backend/app/api/v1/routers/CronRouter.py

195 lines
7.2 KiB
Python

import hmac
from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlalchemy.orm import Session
from sqlalchemy import select
from typing import Dict, Any
from datetime import datetime, timedelta, timezone
from app.core.database.db_session import get_db
from app.core.config.Config import settings
from app.core.permissions.RoleChecker import get_current_user
from app.models.OrderModel import Order
from app.models.WarrantyModel import Warranty
from app.schemas.NotificationGateway import EntityNotificationDispatchCreate
from app.models.ServiceModel import ServiceJob
from app.core.events.notification_events import dispatch_internal_notification
def verify_cron_access(
request: Request,
db: Session = Depends(get_db)
):
"""
Authenticate cron execution via X-Cron-Key header or Admin Bearer token.
Prevents unauthorized external triggers of business logic and notifications.
"""
cron_key = request.headers.get("X-Cron-Key") or request.headers.get("X-CRON-KEY")
if cron_key:
if settings.SECRET_KEY and hmac.compare_digest(cron_key, settings.SECRET_KEY):
return True
if settings.PUBLIC_API_KEY and hmac.compare_digest(cron_key, settings.PUBLIC_API_KEY):
return True
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid Cron authentication key"
)
auth_header = request.headers.get("Authorization")
if auth_header and auth_header.startswith("Bearer "):
token = auth_header.split(" ")[1]
user = get_current_user(request=request, token=token, db=db)
if user and user.role and user.role.role_name.lower() in ["super admin", "superadmin", "admin"]:
return True
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Insufficient permissions to execute cron tasks"
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Cron endpoint requires authentication (X-Cron-Key header or Admin Bearer token)"
)
router = APIRouter(
prefix="/api/v1/cron",
tags=["Cron Scheduled Tasks"],
dependencies=[Depends(verify_cron_access)]
)
@router.post("/end-of-day-report")
def trigger_end_of_day_report(db: Session = Depends(get_db)):
"""
Generate End of Day report and trigger END_OF_DAY_REPORT internal notification.
Intended to be hit by an external cron job at closing time.
"""
# Calculate simple stats for today
today = datetime.utcnow().date()
start_of_day = datetime(today.year, today.month, today.day)
# Orders today
orders = db.execute(select(Order).where(Order.created_at >= start_of_day)).scalars().all()
revenue_orders = sum(float(o.final_amount) for o in orders if o.payment_status in ["PAYMENT_CAPTURED", "PAID"])
# Service jobs completed today
services_completed = db.execute(
select(ServiceJob).where(
ServiceJob.status.in_(["COMPLETED", "READY_FOR_DELIVERY", "DELIVERED"]),
ServiceJob.updated_at >= start_of_day
)
).scalars().all()
context = {
"report_date": today.strftime("%Y-%m-%d"),
"total_orders": len(orders),
"order_revenue": f"₹{revenue_orders:.2f}",
"services_completed": len(services_completed)
}
dispatch_internal_notification(
"END_OF_DAY_REPORT",
f"End of Day Report for {context['report_date']}: {len(orders)} orders (₹{revenue_orders:.2f}), {len(services_completed)} services completed.",
context=context
)
return {"message": "End of Day Report triggered successfully", "stats": context}
@router.post("/repair-sla-breach")
def check_repair_sla_breaches(db: Session = Depends(get_db)):
"""
Check for any service jobs that are breaching SLA (e.g., > 3 days open)
Intended to be hit daily.
"""
threshold_date = datetime.utcnow() - timedelta(days=3)
breaching_jobs = db.execute(
select(ServiceJob).where(
ServiceJob.status.not_in(["COMPLETED", "DELIVERED", "CLOSED", "READY_FOR_DELIVERY", "CANCELLED"]),
ServiceJob.created_at <= threshold_date
)
).scalars().all()
notified_count = 0
for job in breaching_jobs:
days_open = (datetime.utcnow() - job.created_at).days
dispatch_internal_notification(
"REPAIR_SLA_BREACH",
f"SLA Breach! Job {job.job_no} has been open for {days_open} days. Status: {job.status}",
context={"job_no": job.job_no, "days_open": days_open, "status": job.status}
)
notified_count += 1
return {"message": "SLA checks completed", "breaches_found": notified_count}
@router.post("/warranty-expiration")
def process_warranty_expiration(db: Session = Depends(get_db)):
"""
Check for warranties expiring in 7 days and send notifications.
Also expire warranties whose end_date has passed.
"""
now = datetime.now(timezone.utc)
warning_date = now + timedelta(days=7)
# 1. Notification Sweep
expiring_soon = db.execute(
select(Warranty).where(
Warranty.status == "ACTIVE",
Warranty.end_date <= warning_date,
Warranty.end_date > now,
Warranty.expiry_notification_sent == False
)
).scalars().all()
notified_count = 0
for warranty in expiring_soon:
# We assume _dispatch_bg_notification can be used for WARRANTY_EXPIRING_SOON
from app.api.v1.routers.AdminOrderRouter import _dispatch_bg_notification
# Here we could enqueue it
# For simplicity, we just dispatch internal or entity notification
# The frontend will need a template for WARRANTY_EXPIRING_SOON
dispatch_internal_notification(
"WARRANTY_EXPIRING_SOON",
f"Warranty {warranty.warranty_id} is expiring on {warranty.end_date.strftime('%Y-%m-%d')}",
context={
"warranty_id": warranty.warranty_id,
"reference_id": warranty.reference_id,
"end_date": warranty.end_date.strftime("%Y-%m-%d")
}
)
warranty.expiry_notification_sent = True
notified_count += 1
db.commit()
# 2. Expiration Sweep
expired_warranties = db.execute(
select(Warranty).where(
Warranty.status == "ACTIVE",
Warranty.end_date <= now
)
).scalars().all()
expired_count = 0
for warranty in expired_warranties:
warranty.status = "EXPIRED"
expired_count += 1
db.commit()
return {
"message": "Warranty expiration sweep completed",
"notified": notified_count,
"expired": expired_count
}
@router.post("/process-credit-maturity")
def trigger_credit_maturity_sweep(db: Session = Depends(get_db)):
"""
Process pending store credits whose return/claim window has passed.
Transitions verified PENDING credits to MATURED active balance.
"""
from app.services.CreditService import CreditService
result = CreditService.process_maturing_credits(db)
return {
"message": "Store credit maturity sweep completed",
"result": result
}