# app/services/cost_service.py from datetime import datetime from typing import Optional, List, Dict from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, func from app.models.cost import VasCostRecord from app.schemas.cost import VasCostCreate from app.utils.pagination import paginate class CostService: @staticmethod async def create(db: AsyncSession, data: VasCostCreate, user_id: str) -> VasCostRecord: record = VasCostRecord( category=data.category, amount=data.amount, currency=data.currency, description=data.description, voucher_url=data.voucher_url, paid_at=data.paid_at or datetime.utcnow(), created_by=user_id, ) db.add(record) await db.commit() await db.refresh(record) return record @staticmethod async def list_costs( db: AsyncSession, period_id: Optional[str] = None, category: Optional[str] = None, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None, page: int = 0, size: int = 20, ): stmt = select(VasCostRecord) if period_id: stmt = stmt.where(VasCostRecord.period_id == period_id) if category: stmt = stmt.where(VasCostRecord.category == category) if start_date: stmt = stmt.where(VasCostRecord.paid_at >= start_date) if end_date: stmt = stmt.where(VasCostRecord.paid_at <= end_date) stmt = stmt.order_by(VasCostRecord.paid_at.desc()) return await paginate(db, stmt, page, size) @staticmethod async def get_costs_summary_by_date( db: AsyncSession, start_date: datetime, end_date: datetime ) -> Dict[str, int]: """ 统计时间段内各项耗材的总支出 (分) """ stmt = ( select(VasCostRecord.category, func.sum(VasCostRecord.amount)) .where(VasCostRecord.paid_at >= start_date, VasCostRecord.paid_at <= end_date) .group_by(VasCostRecord.category) ) res = await db.execute(stmt) summary = {cat: 0 for cat in ['vps', 'proxy_ip', 'captcha_api', 'sms_api', 'other']} for cat, total in res.fetchall(): summary[cat] = int(total or 0) return summary