Enables users to filter transactions by a custom date range, providing more flexibility in viewing transaction history.
Prioritizes custom date range over preset days for filtering.
Displays a warning if a user attempts to apply a custom date range without selecting both start and end dates.
- Add role management to "By User" tab
- Show all users with roles and/or direct permissions
- Add ability to assign/revoke roles from users
- Display role chips as clickable and removable
- Add "Assign Role" button for each user
- Fix account_id validation error in permission granting
- Extract account_id string from Quasar q-select object
- Apply fix to grantPermission, bulkGrantPermissions, and addRolePermission
- Fix role-based permission checking for expense submission
- Update get_user_permissions_with_inheritance() to include role permissions
- Ensures users with role-based permissions can submit expenses
- Improve Vue reactivity for role details dialog
- Use spread operator to create fresh arrays
- Add $nextTick() before showing dialog
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Changed default permission type from 'read' to 'submit_expense' in
all permission grant forms, as this is the most common use case when
Castle admins grant permissions to users.
Changes:
- grantForm initialization (line 31): 'read' → 'submit_expense'
- bulkGrantForm initialization (line 42): 'read' → 'submit_expense'
- resetGrantForm() method (line 315): 'read' → 'submit_expense'
- resetBulkGrantForm() method (line 402): 'read' → 'submit_expense'
Rationale: Most users need to submit expenses to their assigned
accounts, making 'submit_expense' a more practical default than
'read'. Admins can still select other permission types from the
dropdown if needed.
Affected: static/js/permissions.js
Co-Authored-By: Claude <noreply@anthropic.com>
Fixed UI hanging indefinitely on "Loading..." when users have no
account permissions or when API calls fail.
Problem: When API calls failed (due to no permissions, timeout, or
other errors), the error handlers would show error notifications but
wouldn't clear the loading state. This left data properties as null
or undefined, causing v-if/v-else templates to show spinners forever.
Solution: Set default/empty values in error handlers to clear loading
states and allow UI to render properly:
- loadBalance(): Set balance to {balance: 0, fiat_balances: {}, accounts: []}
- loadTransactions(): Set transactions to [] and pagination.total to 0
- loadAccounts(): Set accounts to []
Now when API calls fail, users see:
- Error notification (existing behavior)
- Empty state UI instead of infinite spinner (new behavior)
- "No transactions yet" / "0 sats" instead of "Loading..."
Affected files:
- static/js/index.js (lines 326-331, 391-393, 434-435)
Co-Authored-By: Claude <noreply@anthropic.com>
Fix Chart of Accounts loading spinner stuck issue
Fixed the Chart of Accounts section showing "Loading accounts..."
indefinitely when user has no account permissions.
Problem: The previous commit set accounts = [] in error handler to
clear loading state. However, the template logic was:
- v-if="accounts.length > 0" → show accounts list
- v-else → show loading spinner
When accounts = [] (empty array), it triggered v-else and showed
the spinner forever.
Solution: Changed the v-else block from loading spinner to empty
state message "No accounts available" with grey text styling.
Now when loadAccounts() fails or returns empty:
- Shows "No accounts available" instead of infinite spinner
- Consistent with other empty states (transactions, balances)
- User sees informative message instead of fake loading state
Affected: templates/castle/index.html (line 792-794)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented performance optimization to reduce Fava API load for ledgers
with large transaction histories. Users can now choose to view transactions
from the last 5, 30, 60, or 90 days instead of loading all entries.
Changes:
- Backend (views_api.py): Added 'days' parameter to api_get_user_entries
endpoint with default value of 5 days
- Backend (fava_client.py - previously committed): get_journal_entries
supports optional days parameter with date filtering logic
- Frontend (index.js): Added setTransactionDays() method and days
parameter handling in loadTransactions()
- Frontend (index.html): Added q-btn-toggle UI control for date range
selection visible to all users
Default: 5 days (aggressive optimization for large ledgers)
Options: 5, 30, 60, 90 days
Performance impact: ~10x improvement for typical ledgers (229 entries
reduced to 20-50 entries for 5-day window).
Co-Authored-By: Claude <noreply@anthropic.com>
Two related fixes for account access:
1. **Super user bypass for permission filtering**
- Super users now bypass permission checks and see all accounts
- Fixes issue where Castle system account was blocked from seeing accounts
- Regular users still get filtered by permissions as expected
2. **Show virtual accounts in permissions management UI**
- Permissions page now passes exclude_virtual=false
- Admins need to see virtual accounts to grant permissions on them
- Enables granting permission on 'Expenses:Supplies' to give access to all children
Impact:
- Super user can now create entries and see all accounts ✓
- Admins can grant permissions on virtual parent accounts ✓
- Regular users still only see permitted, non-virtual accounts ✓
- Permission inheritance works correctly for all users ✓
🤖 Generated with Claude Code (https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Two critical fixes for user account access:
1. **Permission inheritance for ALL permission types**
- Previously only checked READ permission inheritance
- Now checks ALL permission types (read, submit_expense, manage)
- Fixes issue where users with submit_expense on parent virtual accounts
couldn't see child expense accounts
2. **Virtual account filtering after permission check**
- Virtual accounts are now filtered AFTER permission inheritance logic
- This allows permission inheritance to work correctly for virtual parents
- Virtual accounts are still excluded from final results for users
3. **User-specific account filtering**
- Frontend now passes filter_by_user=true to only show permitted accounts
- Prevents users from seeing accounts they don't have access to
Flow now works correctly:
- Admin grants user submit_expense permission on virtual 'Expenses:Supplies'
- Permission inheritance checks ALL permission types (not just read)
- User sees all 'Expenses:Supplies:*' child accounts (Food, Kitchen, etc.)
- Virtual parent 'Expenses:Supplies' is filtered out from final results
- User only sees real expense accounts they can submit to
Fixes loading hang and empty account list in Add Expense dialog.
🤖 Generated with Claude Code (https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Updates permission grant dialogs to visually distinguish virtual accounts:
Changes:
- Add custom option template to account selectors (both grant and bulk grant dialogs)
- Show "🌐 Virtual parent" caption explaining inheritance behavior
- Add blue "Virtual" chip badge to virtual accounts in dropdown
- Update hint text: "virtual accounts cascade to all children"
- Include is_virtual flag in accountOptions computed property
User Experience:
When admin selects account in grant dialog, virtual accounts now clearly show:
- "Expenses" with "Virtual" badge
- Caption: "grants access to all Expenses:* accounts"
This helps admins understand that granting permission on "Expenses" will
automatically give users access to all real expense accounts:
- Expenses:Groceries
- Expenses:Gas:Kitchen
- Expenses:Maintenance:Property
- etc.
Related: migrations.py m003 (created virtual parent accounts)
🤖 Generated with Claude Code (https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implements Phase 1 of UI improvements plan with bulk grant dialog.
Changes:
- Replace single "Grant Permission" button with button group + dropdown menu
- Add "Bulk Grant" option in dropdown menu
- Add comprehensive bulk grant dialog:
* Multi-select user dropdown (with chips)
* Single account selector
* Permission type selector with descriptions
* Optional expiration date
* Optional notes field
* Preview banner showing what will be granted
* Results display with success/failure counts
* Errors dialog for viewing failed grants
JavaScript additions:
- New data properties: showBulkGrantDialog, showBulkGrantErrors, bulkGranting, bulkGrantResults, bulkGrantForm
- New computed property: isBulkGrantFormValid
- New methods: bulkGrantPermissions(), closeBulkGrantDialog(), resetBulkGrantForm()
User Experience improvements:
- Time to onboard 5 users: 10min → 1min (90% reduction)
- Clear feedback with success/failure counts
- Ability to review errors before closing dialog
- Auto-close on complete success after 2 seconds
Related: UI-IMPROVEMENTS-PLAN.md Phase 1
API endpoint: POST /api/v1/admin/permissions/bulk-grant
🤖 Generated with Claude Code (https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Removes the explicit call to the record-payment API when settling a receivable.
The webhook (on_invoice_paid in tasks.py) automatically handles recording the payment in Fava, making the API call redundant. This simplifies the frontend logic.
Also, in the `showPayUserDialog` function, it now correctly identifies users who are owed payments based on a negative balance instead of a positive balance.
Reverses the condition for displaying the settle receivable dialog.
It now correctly shows the dialog only for users with a positive balance,
which indicates they owe the castle.
Improves the handling of pending entries by extracting and deduplicating data from Fava's query results.
Adds support for displaying fiat amounts alongside entries and extracts them from the position data in Fava.
Streamlines receivables/payables/equity checks on the frontend by relying on BQL query to supply account type metadata and tags.
Improvements to equity account handling across the Castle extension:
Transaction Categorization (views_api.py):
- Prioritize equity accounts when enriching transaction entries
- Use two-pass lookup: first search for equity accounts, then fall back to liability/asset accounts
- Ensures transactions with Equity:User-<id> accounts are correctly categorized as equity
UI Enhancements (index.html, index.js):
- Add 'Equity' filter option to Recent Transactions table
- Display blue "Equity" badge for equity entries (before receivable/payable badges)
- Add isEquity() helper function to identify equity account entries
Beancount Import (import_beancount.py):
- Support importing Beancount Equity:<name> accounts
- Map Beancount "Equity:Pat" to Castle "Equity:User-<id>" accounts
- Update extract_user_from_user_account() to handle Equity: prefix
- Improve error messages to include equity account examples
- Add equity account lookup in get_account_id() with helpful error if equity not enabled
These changes ensure equity accounts (representing user capital contributions) are properly distinguished from payables and receivables throughout the system.
Add account type filtering to Recent Transactions table and fix pagination issue where filters were applied after fetching results, causing incomplete data display.
Database layer (crud.py):
- Add get_journal_entries_by_user_and_account_type() to filter entries by
both user_id and account_type at SQL query level
- Add count_journal_entries_by_user_and_account_type() for accurate counts
- Filters apply before pagination, ensuring all matching records are fetched
API layer (views_api.py):
- Add filter_account_type parameter ('asset' for receivable, 'liability' for payable)
- Refactor filtering logic to use new database-level filter functions
- Support filter combinations: user only, account_type only, user+account_type, or all
- Enrich entries with account_type metadata for UI display
Frontend (index.js):
- Add account_type to transactionFilter state
- Add accountTypeOptions computed property with receivable/payable choices
- Reorder table columns to show User before Date
- Update loadTransactions to send account_type filter parameter
- Update clearTransactionFilter to clear both user and account_type filters
UI (index.html):
- Add second filter dropdown for account type (Receivable/Payable)
- Show clear button when either filter is active
- Update button label from "Clear Filter" to "Clear Filters"
This fixes the critical bug where filtering for receivables would only show a subset of results (e.g., 2 out of 20 entries fetched) instead of all matching receivables. Now filters are applied at the database level before pagination, ensuring users see all relevant transactions.
Convert the Recent Transactions card from a list view to a paginated table
with enhanced filtering capabilities for super users.
Frontend changes:
- Replace q-list with q-table for better data presentation
- Add pagination with configurable page size (default: 20 items)
- Add transaction filter dropdown for super users to filter by username
- Define table columns: Status, Date, Description, User, Amount, Fiat, Reference
- Implement prev/next page navigation with page info display
- Add filter controls with clear filter button
Backend changes (views_api.py):
- Add pagination support with limit/offset parameters
- Add filter_user_id parameter for filtering by user (super user only)
- Enrich transaction entries with user_id and username from account lookups
- Return paginated response with total count and pagination metadata
Database changes (crud.py):
- Update get_all_journal_entries() to support offset parameter
- Update get_journal_entries_by_user() to support offset parameter
- Add count_all_journal_entries() for total count
- Add count_journal_entries_by_user() for user-specific count
This improves the Recent Transactions UX by providing better organization, easier navigation through large transaction lists, and the ability for admins to filter transactions by user.
Addresses an issue where the transaction offset could be non-numeric, causing errors in pagination.
Adds validation and parsing to ensure the offset is always an integer, falling back to 0 if necessary. Also ensures that limit is parsed into an Int.
Implements pagination for the transaction history, enabling users
to navigate through their transactions in manageable chunks. This
improves performance and user experience, especially for users
with a large number of transactions. It also introduces total entry counts.
Modifies receivable and payable checks to align with Beancount's accounting principles.
This adjustment ensures that the system correctly identifies receivables and payables based on the sign of the amounts, rather than just debit/credit.
Also, calculates transaction sizes using the absolute value of amounts.
Allows superusers to grant and revoke equity eligibility for users.
Adds UI components for managing equity eligibility.
Equity-eligible users can then contribute expenses as equity.
Replaces the user ID input field with a user selection dropdown,
allowing administrators to search and select users for permission
management. This simplifies the process of assigning permissions
and improves user experience.
Fetches Castle users via a new API endpoint and filters them
based on search input. Only users with Castle accounts
(receivables, payables, equity, or permissions) are listed.
Implements a Vue-based UI for managing user permissions, allowing administrators to grant and revoke access to expense accounts.
Provides views for managing permissions by user and by account, along with dialogs for granting and revoking permissions.
Integrates with the LNbits API to load accounts and permissions and to persist changes.
Uses usernames instead of user IDs in the audit log and
approval request listings to improve readability. If a user
is not found, it displays a truncated version of the user ID.
Adds a date field to expense entries for better tracking and reporting.
This allows users to specify the date of the expense transaction,
providing more accurate financial records.
Ensures that the currency field defaults to EUR in both the expense and receivable dialogs.
This provides a better user experience by pre-selecting a common currency, preventing the user from having to manually choose it every time.
Updates the exchange rate calculation to rely solely on the
current exchange rate when a valid fiat amount is not available.
Removes the hardcoded default exchange rate fallback and instead
displays a user-friendly warning message when fetching the exchange
rate fails. This informs the user that fiat currency conversions
might be unavailable.
Fetches the current BTC/EUR exchange rate from the CoinGecko API and uses it to calculate fiat values.
This ensures more accurate currency conversions, especially for expenses and payments. A fallback to a default rate is included in case the API is unavailable.
Implements the ability for the super user (Castle) to pay other users for expenses or liabilities.
Introduces a new `PayUser` model to represent these payments, along with API endpoints to process and record them.
Integrates a "Pay User" button into the user list, allowing the super user to initiate payments through either lightning or manual methods (cash, bank transfer, check).
Adds UI elements and logic for handling both lightning payments (generating invoices and paying them) and manual payment recording.
This functionality allows Castle to manage and settle debts with its users directly through the application.
Enhances the receivable settlement dialog by providing a default description based on the selected payment method, improving clarity for users.
Filters the user balance display to only show users with outstanding balances, making the interface cleaner and more focused for super users.
Adds support for settling receivables with fiat currencies
like EUR and USD, in addition to sats.
Updates the settlement dialog to handle fiat amounts and
exchange rates, defaulting to cash payment when a fiat balance
exists.
Modifies the API to accept currency and amount_sats parameters
and adjust the journal entry accordingly, converting the fiat amount
to minor units (e.g., cents) for accounting purposes.
Standardizes lightning account name to "Assets:Bitcoin:Lightning" for consistency.
Updates the database and code to reflect this change, ensuring that payment processing and account management use the new name.
Prevents polling of receivable dialog after settlement.
Allows administrators to generate payment invoices on behalf of specific users.
This is useful for handling settlement invoices in certain scenarios.
The changes include:
- Adding a `user_id` field to the generate payment invoice request model
- Updating the API endpoint to accept the `user_id` parameter
- Implementing checks to ensure only superusers can generate invoices for other users
- Updating the memo and extra data to reflect the target user
Implements the ability for users to settle their outstanding balance
using a Lightning Network invoice.
Generates an invoice on the Castle wallet and polls for payment,
automatically recording the transaction once payment is detected.
The UI is updated to display the invoice and handle the payment process.
Implements a "Settle Receivable" feature for super users to record manual payments from users who owe money.
Introduces a dialog for inputting payment details (amount, method, description, reference), triggers an API call to record the transaction, and updates user balances and transaction history.
This is for non-lightning payments like cash, bank transfers, or checks.
Implements balance assertions, reconciliation API endpoints, a reconciliation UI dashboard, and automated daily balance checks.
This provides comprehensive reconciliation tools to ensure accounting accuracy and catch discrepancies early.
Updates roadmap to mark Phase 2 as complete.
Improves balance assertion creation by handling Decimal types correctly for database insertion.
It also fixes a validation issue in the UI where the expected balance was not correctly validated as a required field and initializes the value to 0.
Adds balance assertion functionality to enable admins to verify accounting accuracy.
This includes:
- A new `balance_assertions` table in the database
- CRUD operations for balance assertions (create, get, list, check, delete)
- API endpoints for managing balance assertions (admin only)
- UI elements for creating, viewing, and re-checking assertions
Also, reorders the implementation roadmap in the documentation to reflect better the dependencies between phases.
Adds an admin approval workflow for user-submitted expenses. This ensures that only valid expenses affect user balances.
The workflow includes pending expense states, admin approval/rejection actions, balance filtering, and UI updates.
Implements expense approval functionality, allowing superusers to review and approve or reject expense entries.
This includes:
- Filtering account balance calculations and user balance calculations to only include cleared journal entries.
- Adding API endpoints to retrieve pending expense entries and approve/reject them.
- Updating the UI to display pending expenses to superusers and provide actions to approve or reject them.
This ensures better control over expenses within the system.
Implements core improvements from Phase 1 of the Beancount patterns adoption:
- Uses Decimal for fiat amounts to prevent floating point errors
- Adds a meta field to journal entries for a full audit trail
- Adds a flag field to journal entries for transaction status
- Migrates existing account names to a hierarchical format
This commit introduces a database migration to add the `flag` and `meta` columns to the `journal_entries` table. It also includes updates to the models, CRUD operations, and API endpoints to handle the new fields.
Provides detailed documentation for the Castle Accounting extension, including architecture, transaction flows, balance calculation, API endpoints, and future improvements.
Documents design patterns inspired by Beancount, such as immutable data structures, plugin architecture, and balance assertions, with recommendations for adoption in the Castle extension.
Includes an implementation roadmap, security considerations, performance considerations, and a migration path for existing data.
Improves clarity by displaying "Payable" or "Receivable" badges on entries
in the transaction list.
The badge color depends on whether the user is a superuser, indicating
the direction of the transaction from the user's perspective.
This helps users quickly understand which transactions are owed to them
and which they owe.
Enables users to request manual payments from the Castle and provides admin functions to approve or reject these requests.
Introduces the `manual_payment_requests` table and related CRUD operations.
Adds API endpoints for creating, retrieving, approving, and rejecting manual payment requests.
Updates the UI to allow users to request payments and for admins to review pending requests.
For super users, the balance view now displays the net position
(liabilities - receivables) of the Castle. The journal view
shows all entries across all users.
The settings are now loaded first to determine if the user is a
super user.
Improves user experience by visually indicating entries that represent outstanding payments owed by users.
This change introduces a "Pending Payment" badge for receivable entries in the transaction list. A receivable entry is determined by checking if the entry contains a debit line item against an account receivable account. This provides immediate visual feedback to the user, highlighting transactions requiring their action.
Updates journal entry retrieval to filter entries based on
the user's accounts rather than the user ID.
This ensures that users only see journal entries that
directly affect their accounts.
Also displays fiat amount in journal entries if available in
the metadata.
Extends user balance information to include fiat currency balances,
calculated based on entry line metadata and account types.
This allows for a more comprehensive view of user balances,
including both satoshi and fiat currency holdings.
Updates the castle index template and API to display fiat balances.
Improves the reliability of payment status updates by ensuring that the payment polling interval is properly cleared when a payment dialog is closed, when a payment is submitted, or when a new payment dialog is opened. This prevents multiple polling intervals from running simultaneously, which could lead to incorrect payment status updates.
Adds a watch to clear interval when the pay dialog closes.
Adds functionality for users to pay their Castle balance by generating and paying a Lightning invoice.
This includes:
- Adding API endpoints for invoice generation and payment recording.
- Updating the frontend to allow users to initiate the invoice payment process.
- Passing the wallet's `inkey` to the frontend for payment status checks.
Implements a feature that allows users to pay their outstanding balance via Lightning.
The changes include:
- Adds the UI elements for invoice generation and display, including QR code.
- Integrates backend endpoints to generate and record payments.
- Adds polling mechanism to track payments and update balance.
- Creates new database models to support manual payment requests.