Files
CosScene/server/app/services/point_service.py
T
2026-05-09 16:40:29 +08:00

35 lines
831 B
Python

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.point_ledger import PointLedger
async def grant_points(
db: AsyncSession,
user_id: int,
change: int,
reason: str,
ref_type: str | None = None,
ref_id: int | None = None,
) -> PointLedger:
last_entry = await db.execute(
select(PointLedger)
.where(PointLedger.user_id == user_id)
.order_by(PointLedger.id.desc())
.limit(1)
)
last = last_entry.scalar_one_or_none()
current_balance = last.balance if last else 0
ledger = PointLedger(
user_id=user_id,
change=change,
balance=current_balance + change,
reason=reason,
ref_type=ref_type,
ref_id=ref_id,
)
db.add(ledger)
await db.flush()
return ledger