fix: убрать WITHDRAWAL из автонегации, добавить abs() в агрегации, исправить all_time_stats

- Убран WITHDRAWAL из автонегации в create_transaction (ломал profit,
  expenses и display flip в admin_users)
- Добавлен func.abs() в by_type агрегацию (transaction.py)
- Добавлен func.abs() в total_spent user.py (_build_spending_stats_select)
- Исправлен all_time_stats в боте и webapi: передаём явный диапазон дат
  вместо дефолтного текущего месяца
This commit is contained in:
Fringg
2026-03-05 09:05:02 +03:00
parent 968d147046
commit 6da61d7951
4 changed files with 10 additions and 6 deletions
+3 -3
View File
@@ -39,8 +39,8 @@ async def create_transaction(
is_completed: bool = True,
created_at: datetime | None = None,
) -> Transaction:
# SUBSCRIPTION_PAYMENT and WITHDRAWAL are debits — always store as negative
if type in (TransactionType.SUBSCRIPTION_PAYMENT, TransactionType.WITHDRAWAL) and amount_kopeks > 0:
# SUBSCRIPTION_PAYMENT — always store as negative (debit from user balance)
if type == TransactionType.SUBSCRIPTION_PAYMENT and amount_kopeks > 0:
amount_kopeks = -amount_kopeks
transaction = Transaction(
@@ -248,7 +248,7 @@ async def get_transactions_statistics(
select(
Transaction.type,
func.count(Transaction.id).label('count'),
func.coalesce(func.sum(Transaction.amount_kopeks), 0).label('total_amount'),
func.coalesce(func.sum(func.abs(Transaction.amount_kopeks)), 0).label('total_amount'),
)
.where(
and_(
+1 -1
View File
@@ -54,7 +54,7 @@ def _build_spending_stats_select():
case(
(
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
Transaction.amount_kopeks,
func.abs(Transaction.amount_kopeks),
),
else_=0,
)
+3 -1
View File
@@ -137,7 +137,9 @@ async def show_revenue_statistics(callback: types.CallbackQuery, db_user: User,
month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
month_stats = await get_transactions_statistics(db, month_start, now)
all_time_stats = await get_transactions_statistics(db)
all_time_stats = await get_transactions_statistics(
db, start_date=datetime(2020, 1, 1, tzinfo=UTC), end_date=now
)
current_time = format_datetime(datetime.now(UTC))
text = f"""
+3 -1
View File
@@ -262,7 +262,9 @@ async def stats_full(
users_stats = await get_users_statistics(db)
subscriptions_stats = await get_subscriptions_statistics(db)
trial_stats = await get_trial_statistics(db)
transactions_stats = await get_transactions_statistics(db)
transactions_stats = await get_transactions_statistics(
db, start_date=datetime(2020, 1, 1, tzinfo=UTC), end_date=datetime.now(UTC)
)
referral_stats = await get_referral_statistics(db)
transactions_totals = transactions_stats.get('totals', {})