diff --git a/app/database/crud/transaction.py b/app/database/crud/transaction.py index 603f0c65..fb9e1d1d 100644 --- a/app/database/crud/transaction.py +++ b/app/database/crud/transaction.py @@ -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_( diff --git a/app/database/crud/user.py b/app/database/crud/user.py index 05670354..9c8fd0fb 100644 --- a/app/database/crud/user.py +++ b/app/database/crud/user.py @@ -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, ) diff --git a/app/handlers/admin/statistics.py b/app/handlers/admin/statistics.py index 606c52a8..5c78a088 100644 --- a/app/handlers/admin/statistics.py +++ b/app/handlers/admin/statistics.py @@ -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""" diff --git a/app/webapi/routes/stats.py b/app/webapi/routes/stats.py index b0a0173a..78e7cca5 100644 --- a/app/webapi/routes/stats.py +++ b/app/webapi/routes/stats.py @@ -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', {})