46 lines
1.6 KiB
Python
46 lines
1.6 KiB
Python
from fastapi import APIRouter, Depends
|
|
from fastapi.encoders import jsonable_encoder
|
|
from fastapi.responses import JSONResponse
|
|
from sqlalchemy import text
|
|
from sqlmodel import Session, select
|
|
|
|
from ..database import get_session
|
|
from ..deps import get_current_user
|
|
from ..models import Account, User
|
|
|
|
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
|
|
|
|
|
@router.post("/recalculate-balances")
|
|
def recalculate_balances(
|
|
session: Session = Depends(get_session),
|
|
current_user: User = Depends(get_current_user),
|
|
):
|
|
accounts = session.exec(
|
|
select(Account).where(Account.user_id == current_user.id)
|
|
).all()
|
|
|
|
for account in accounts:
|
|
result = session.exec(
|
|
text(
|
|
'SELECT COALESCE(SUM(CASE WHEN type = \'CREDIT\' THEN "amountCents" ELSE -"amountCents" END), 0)::bigint '
|
|
'FROM "Transaction" WHERE "accountId" = :account_id AND type != \'TRANSFER\''
|
|
).bindparams(account_id=account.id)
|
|
).first()
|
|
account.current_balance_cents = int(result[0]) if result else 0
|
|
session.add(account)
|
|
|
|
session.commit()
|
|
|
|
# Remove snapshots for accounts that have no transactions
|
|
session.exec(
|
|
text(
|
|
'DELETE FROM "BalanceSnapshot" WHERE "accountId" IN '
|
|
'(SELECT id FROM "Account" WHERE "userId" = :user_id) '
|
|
'AND NOT EXISTS (SELECT 1 FROM "Transaction" WHERE "accountId" = "BalanceSnapshot"."accountId")'
|
|
).bindparams(user_id=current_user.id)
|
|
)
|
|
session.commit()
|
|
|
|
return JSONResponse(content=jsonable_encoder({"ok": True, "accounts": len(accounts)}))
|