diff --git a/crud.py b/crud.py index 85ba9cc..9097421 100644 --- a/crud.py +++ b/crud.py @@ -317,6 +317,43 @@ async def get_user_balance(user_id: str) -> UserBalance: ) +async def get_all_user_balances() -> list[UserBalance]: + """Get balances for all users (used by castle to see who they owe)""" + # Get all user-specific accounts + all_accounts = await db.fetchall( + "SELECT * FROM accounts WHERE user_id IS NOT NULL", + {}, + Account, + ) + + # Group by user_id + users_dict = {} + for account in all_accounts: + if account.user_id not in users_dict: + users_dict[account.user_id] = [] + users_dict[account.user_id].append(account) + + # Calculate balance for each user + user_balances = [] + for user_id, accounts in users_dict.items(): + total_balance = 0 + for account in accounts: + balance = await get_account_balance(account.id) + if account.account_type == AccountType.LIABILITY: + total_balance += balance + elif account.account_type == AccountType.ASSET: + total_balance -= balance + + if total_balance != 0: # Only include users with non-zero balance + user_balances.append( + UserBalance( + user_id=user_id, balance=total_balance, accounts=accounts + ) + ) + + return user_balances + + async def get_account_transactions( account_id: str, limit: int = 100 ) -> list[tuple[JournalEntry, EntryLine]]: diff --git a/static/js/index.js b/static/js/index.js index b80dd16..816d846 100644 --- a/static/js/index.js +++ b/static/js/index.js @@ -8,6 +8,7 @@ window.app = Vue.createApp({ data() { return { balance: null, + allUserBalances: [], transactions: [], accounts: [], currencies: [], @@ -71,10 +72,27 @@ window.app = Vue.createApp({ this.g.user.wallets[0].inkey ) this.balance = response.data + + // If super user, also load all user balances + if (this.isSuperUser) { + await this.loadAllUserBalances() + } } catch (error) { LNbits.utils.notifyApiError(error) } }, + async loadAllUserBalances() { + try { + const response = await LNbits.api.request( + 'GET', + '/castle/api/v1/balances/all', + this.g.user.wallets[0].adminkey + ) + this.allUserBalances = response.data + } catch (error) { + console.error('Error loading all user balances:', error) + } + }, async loadTransactions() { try { const response = await LNbits.api.request( diff --git a/templates/castle/index.html b/templates/castle/index.html index 9fadea4..a798486 100644 --- a/templates/castle/index.html +++ b/templates/castle/index.html @@ -76,14 +76,17 @@