# app/services/vas_task_service.py from datetime import datetime, date, timedelta from typing import List, Optional from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import func, text, select, or_, and_ from redis.asyncio import Redis from app.core.logger import logger from app.utils.search import apply_keyword_search_stmt from app.utils.pagination import paginate from app.core.biz_exception import NotFoundError, BizLogicError from app.models.vas_task import VasTask from app.models.order import VasOrder from app.schemas.vas_task import VasTaskCreate, VasTaskUpdate from app.services.task_handlers import task_processor class VasTaskService: @staticmethod async def create(db: AsyncSession, data: VasTaskCreate) -> VasTask: rec = VasTask( **data.dict(), status="pending", created_at=datetime.utcnow(), ) db.add(rec) await db.commit() await db.refresh(rec) logger.info(f"πŸ“‹ [VAS_TASK] Created task: id={rec.id} order_id={rec.order_id} routing_key={rec.routing_key}") return rec @staticmethod async def pop_vas_task(db: AsyncSession, routing_key: str, cooldown_seconds: int = 60) -> VasTask: stmt = ( select(VasTask) .where(VasTask.routing_key == routing_key) .where(VasTask.status == 'pending') .where( or_( VasTask.attempt_count == 0, and_( VasTask.attempt_count > 0, VasTask.updated_at < (func.utc_timestamp() - text(f"INTERVAL {cooldown_seconds} SECOND")) ) ) ) .order_by(VasTask.priority.desc(), VasTask.id.asc()) .limit(1) .with_for_update(skip_locked=True) ) result = await db.execute(stmt) task = result.scalar_one_or_none() if not task: raise NotFoundError(message="Task not found") task.status = 'running' task.attempt_count += 1 task.updated_at = func.utc_timestamp() await db.commit() logger.info(f"πŸƒ [VAS_TASK] Task popped: id={task.id} routing_key={routing_key} attempt={task.attempt_count}") return task @staticmethod async def get_task_by_order_id( db: AsyncSession, order_id: str, ) -> List[VasTask]: stmt = select(VasTask).where( VasTask.order_id == order_id ) result = await db.execute(stmt) return result.scalars().all() @staticmethod async def list_task( db: AsyncSession, status: Optional[str] = None, routing_key: Optional[str] = None, script_version: Optional[str] = None, keyword: Optional[str] = None, page: int = 0, size: int = 10, ): stmt = select(VasTask) if status: stmt = stmt.where(VasTask.status == status) if routing_key: stmt = stmt.where(VasTask.routing_key == routing_key) if script_version: stmt = stmt.where(VasTask.script_version == script_version) stmt = apply_keyword_search_stmt( stmt=stmt, model=VasTask, keyword=keyword, fields=["id", "order_id", "routing_key", "user_inputs", "config", "meta", "grabbed_history"], ).order_by(VasTask.created_at.desc()) return await paginate(db, stmt, page, size) @staticmethod async def get_expiring_tasks( db: AsyncSession, threshold_days: int = 3 ) -> List[dict]: """ θŽ·ε–ε³ε°†θΏ‡ζœŸηš„δ»»εŠ‘εˆ—θ‘¨ """ now = datetime.utcnow() threshold_date = now + timedelta(days=threshold_days) stmt = select(VasTask).where( VasTask.status == "grabbed", VasTask.grabbed_history.isnot(None) ) result = await db.execute(stmt) tasks = result.scalars().all() expiring_tasks = [] for task in tasks: grabbed_history = task.grabbed_history or {} slot_date_str = grabbed_history.get("slot_date") if not slot_date_str: continue try: try: slot_date = datetime.strptime(slot_date_str, "%Y-%m-%d") except ValueError: slot_date = datetime.strptime(slot_date_str, "%d/%m/%Y") if slot_date <= threshold_date: days_remaining = (slot_date.date() - now.date()).days expiring_tasks.append({ "task_id": task.id, "order_id": task.order_id, "routing_key": task.routing_key, "slot_date": slot_date_str, "slot_time": grabbed_history.get("slot_time"), "days_remaining": days_remaining, "days_remaining_display": f"{days_remaining} days" if days_remaining > 0 else "Today/Expired", "status": task.status }) except (ValueError, TypeError): continue expiring_tasks.sort(key=lambda x: x["days_remaining"]) return expiring_tasks @staticmethod async def update(db: AsyncSession, id: int, payload: VasTaskUpdate) -> VasTask: stmt = select(VasTask).where(VasTask.id == id) result = await db.execute(stmt) rec = result.scalar_one_or_none() if not rec: raise NotFoundError("Task not exist") old_status = rec.status if payload.status is not None: rec.status = payload.status if payload.grabbed_history is not None: rec.grabbed_history = payload.grabbed_history if payload.meta is not None: rec.meta = payload.meta await db.commit() await db.refresh(rec) logger.info(f"πŸ”„ [VAS_TASK] Updated task {id}: status {old_status} -> {rec.status}") return rec @staticmethod async def get_task_by_id( db: AsyncSession, task_id: int, ) -> VasTask: stmt = select(VasTask).where( VasTask.id == task_id, ) result = await db.execute(stmt) rec = result.scalar_one_or_none() if not rec: raise NotFoundError("Task not exist") return rec @staticmethod async def return_to_queue(db: AsyncSession, id: int) -> VasTask: stmt = select(VasTask).where(VasTask.id == id) result = await db.execute(stmt) rec = result.scalar_one_or_none() if not rec: raise NotFoundError("Task not exist") rec.status = "pending" await db.commit() await db.refresh(rec) logger.info(f"πŸ” [VAS_TASK] Returned task {id} to queue (status=pending)") return rec @staticmethod async def pause(db: AsyncSession, id: int) -> VasTask: stmt = select(VasTask).where(VasTask.id == id) result = await db.execute(stmt) rec = result.scalar_one_or_none() if not rec: raise NotFoundError("Task not exist") rec.status = "pause" await db.commit() await db.refresh(rec) logger.info(f"⏸️ [VAS_TASK] Paused task {id} (status=pause)") return rec @staticmethod async def manual_confirm(db: AsyncSession, id: int, redis_client: Redis) -> VasTask: stmt = select(VasTask).where(VasTask.id == id) result = await db.execute(stmt) task = result.scalar_one_or_none() if not task: raise NotFoundError("Task not exist") task.status = "completed" order_stmt = select(VasOrder).where(VasOrder.id == task.order_id) order_result = await db.execute(order_stmt) order = order_result.scalar_one_or_none() if not order: raise NotFoundError("Order not exist") order.status = "completed" await task_processor.execute(task.routing_key, db, redis_client, task, order) await db.commit() await db.refresh(task) logger.info(f"βœ… [VAS_TASK] Manually confirmed task {id} and order {order.id} as completed") return task