Commit graph

89 commits

Author SHA1 Message Date
b9efd166a6 FInal commit before stripping down to use FAVA 2025-11-09 21:12:19 +01:00
0b64ffa54f feat: Add equity account support to transaction filtering and Beancount import
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.
2025-11-09 21:09:43 +01:00
6f1fa7203b change Recent Transactions pagination limit from 20 to 10 2025-11-09 00:32:54 +01:00
3af93c3479 Add receivable/payable filtering with database-level query optimization
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.
2025-11-09 00:28:54 +01:00
f3d0d8652b Add Recent Transactions pagination and table view to with filtering
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.
2025-11-09 00:27:17 +01:00
093cecbff2 Ensures transaction offset is a valid number
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.
2025-11-09 00:06:07 +01:00
69b8f6e2d3 Adds pagination to transaction history
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.
2025-11-08 23:51:12 +01:00
4b327a0aab Extends account lookup for user accounts
Implements account lookup logic for user-specific accounts,
specifically Liabilities:Payable and Assets:Receivable.

This allows the system to automatically map Beancount accounts
to corresponding accounts in the Castle system based on user ID.

Improves error messages when user accounts are not properly configured.
2025-11-08 23:51:07 +01:00
992a8fe554 Creates default user accounts on wallet setup
Ensures consistent user account structure by proactively
creating core liability and asset accounts when a user
configures their wallet settings.
2025-11-08 23:41:17 +01:00
9054b3eb62 Adds Beancount import helper script
Implements a script to import Beancount ledger transactions into the Castle accounting extension.

The script fetches BTC/EUR rates, retrieves accounts from the Castle API, maps users, parses Beancount transactions, converts EUR to sats, and uploads the data to Castle.

Adds error handling, dry-run mode, and detailed logging for improved usability.
Displays equity account status and validates the existence of user equity accounts.
2025-11-08 23:18:42 +01:00
4ae6a8f7d2 Refactors journal entry lines to use single amount
Simplifies the representation of journal entry lines by replacing separate debit and credit fields with a single 'amount' field.

Positive amounts represent debits, while negative amounts represent credits, aligning with Beancount's approach. This change improves code readability and simplifies calculations for balancing entries.
2025-11-08 11:48:08 +01:00
d0bec3ea5a Adapts receivable/payable logic for Beancount
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.
2025-11-08 10:52:43 +01:00
5cc2630777 REFACTOR Migrates to single 'amount' field for transactions
Refactors the data model to use a single 'amount' field for journal entry lines, aligning with the Beancount approach.
This simplifies the model, enhances compatibility, and eliminates invalid states.

Includes a database migration to convert existing debit/credit columns to the new 'amount' field.

Updates balance calculation logic to utilize the new amount field for improved accuracy and efficiency.
2025-11-08 10:33:17 +01:00
0b50ba0f82 Removes legacy equity accounts
Removes generic equity accounts that are no longer necessary
due to the user-specific equity model introduced by the
castle extension. Specifically, it removes
"Equity:MemberEquity" and "Equity:RetainedEarnings" accounts.
2025-11-08 10:14:38 +01:00
eefabc3441 Enables equity eligibility for users
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.
2025-11-08 10:14:24 +01:00
33c294de7f Removes parent-only accounts
Removes parent accounts from the database to simplify account management.

Since the application exports to Beancount and doesn't directly interface with it, parent accounts for organizational hierarchy aren't necessary. The hierarchy is implicitly derived from the colon-separated account names.

This change cleans the database and prevents accidental postings to parent accounts. Specifically removes "Assets:Bitcoin" and "Equity" accounts.
2025-11-07 23:24:11 +01:00
7752b41e06 Refactors Castle user retrieval
Simplifies the API endpoint for retrieving Castle users.

Instead of gathering users from various sources (accounts,
permissions, equity), it now focuses on users who have configured
their wallet settings, streamlining the process and aligning with
the intended use case.
2025-11-07 23:06:37 +01:00
d6a1c6e5b3 Enables user selection for permissions
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.
2025-11-07 23:06:24 +01:00
fc12dae435 Clarifies equity account name generation
Adds a comment to the `equity_account_name` field in the
`CreateUserEquityStatus` model, clarifying that it is
auto-generated if not provided.

This improves clarity for developers using the API.
2025-11-07 22:37:45 +01:00
988d7fdf20 Auto-creates equity account for eligible users
Automatically creates a user-specific equity account when a user is granted equity eligibility.
This simplifies the process of granting equity and ensures that each eligible user has a dedicated equity account.
2025-11-07 22:37:45 +01:00
88aaf0e28e Updates default chart of accounts
Expands the default chart of accounts with a more
detailed hierarchical structure. This includes new
accounts for fixed assets, livestock, equity
contributions, and detailed expense categories.
The migration script only adds accounts that don't
already exist, ensuring a smooth update process.
2025-11-07 22:37:45 +01:00
6f62c52c68 Adds user equity status models
Adds models for managing user equity status.
Includes UserEquityStatus and UserInfo models.
2025-11-07 18:20:45 +01:00
d7354556c3 Adds admin permissions management page
Implements an admin permissions management page.

This change allows superusers to manage permissions directly from the castle interface, providing a more streamlined experience for administrative tasks.
2025-11-07 18:05:30 +01:00
9c63511371 Adds permission management UI and logic
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.
2025-11-07 17:57:33 +01:00
92c1649f3b Adds account permissioning system
Adds an account permissioning system to allow granular control over account access.

Introduces the ability to grant users specific permissions (read, submit_expense, manage) on individual accounts.  This includes support for hierarchical permission inheritance, where permissions on parent accounts cascade to child accounts.

Adds new API endpoints for managing account permissions, including granting, listing, and revoking permissions.

Integrates permission checks into existing endpoints, such as creating expense entries, to ensure that users only have access to the accounts they are authorized to use.

Fixes #33 - Implements role based access control
2025-11-07 17:55:59 +01:00
7f9cecefa1 Adds user equity eligibility management
Implements functionality to manage user equity eligibility, allowing admins to grant and revoke access.

Adds database migration, models, CRUD operations, and API endpoints for managing user equity status.
This feature enables finer-grained control over who can convert expenses to equity contributions.
Validates a user's eligibility before allowing them to submit expenses as equity.
2025-11-07 16:51:55 +01:00
3248d3dad6 add dev docs 2025-11-04 01:19:30 +01:00
3add13075c Adds fiat currency metadata to payments
Adds fiat currency information to payment invoices and ledger entries.

This allows for tracking the fiat value of transactions and provides a more complete financial picture. Calculates the fiat amount proportionally based on the user's balance and includes the fiat currency, amount, and exchange rates in the invoice's extra data. This data is then extracted and added to the ledger entry's metadata when recording the payment.
2025-11-02 02:52:41 +01:00
8f35788e1a Adds task cleanup on extension shutdown
Implements a mechanism to cancel pending background tasks
when the extension is stopped. This ensures proper cleanup and
prevents potential issues with lingering tasks.
2025-11-02 01:41:34 +01:00
cfa25cc61b Adds background task for invoice processing
Implements a background task that listens for paid invoices
and automatically records them in the accounting system. This
ensures payments are captured even if the user closes their
browser before the client-side polling detects the payment.

Introduces a new `get_journal_entry_by_reference` function to
improve idempotency when recording payments.
2025-11-02 01:40:40 +01:00
4957826c49 Updates asset account names for consistency
Ensures that default and specified account names for
cash, bank transfers, and checks align with the correct
asset account structure.
2025-11-01 23:47:08 +01:00
e2472d13a2 Adds on-chain Bitcoin payment support
Adds support for on-chain Bitcoin payments by:
- Introducing a new `Assets:Bitcoin:OnChain` account.
- Updating the `SettleReceivable` and `PayUser` models to include `txid` for storing transaction IDs.
- Modifying the API endpoints to handle `btc_onchain` as a valid payment method and associate it with the new account.

This allows tracking on-chain Bitcoin transactions separately from Lightning Network payments.
2025-11-01 23:45:28 +01:00
8b16ead5b1 Formats fiat amounts and rates in API calls
Ensures consistent formatting of fiat currency, amount,
and exchange rates in the `api_settle_receivable` and
`api_pay_user` API endpoints.
Specifically, it:
- Converts fiat currency to uppercase.
- Formats fiat amount to three decimal places.
- Calculates and includes fiat and BTC rates.
2025-11-01 23:24:38 +01:00
5e67ce562b Adds CLAUDE.md to guide Claude Code
Creates a markdown file to provide guidance to Claude Code (claude.ai/code) when interacting with the Castle Accounting codebase.

This document outlines project overview, architecture, key files, database schema, transaction flows, API endpoints, development notes, and other crucial information. It aims to improve Claude's ability to understand and assist with code-related tasks.
2025-11-01 23:22:25 +01:00
762f5cc411 Improves user display in audit log and requests
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.
2025-11-01 09:25:22 +01:00
d1f22dfda8 Reorders cards on the dashboard
Moves the pending expense approvals card to the top of the dashboard
and the user balance card to a later position for better UX.
2025-11-01 09:21:49 +01:00
c7bc0c7904 Adds entry date to expense entries
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.
2025-11-01 09:10:01 +01:00
b529a72d9e Sets default currency to EUR
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.
2025-11-01 08:59:39 +01:00
a2108e5931 Improves exchange rate handling and error display.
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.
2025-10-23 10:04:53 +02:00
176501211d Fetches and applies real-time exchange rate
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.
2025-10-23 10:04:37 +02:00
60aba90e00 Adds functionality to pay users (Castle pays)
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.
2025-10-23 10:01:33 +02:00
f0257e7c7f Improves receivable settlement and balance display.
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.
2025-10-23 09:18:20 +02:00
b4408cd53d Ensures journal entries use satoshis for settlements
Updates the `api_settle_receivable` function to ensure all journal entries are recorded in satoshis, regardless of the currency used for payment.

This change standardizes the journal entries to match the receivable account balance, simplifying reconciliation. It also enforces that `amount_sats` must be provided when settling with fiat currency to correctly calculate the sats equivalent.
2025-10-23 04:27:07 +02:00
70013d1c29 Enables manual settlement with fiat currencies
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.
2025-10-23 04:19:26 +02:00
49f21da55a Refactors lightning account naming
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.
2025-10-23 04:10:06 +02:00
8a961e1331 Replaces QR code implementation with lnbits-qrcode
Replaces the generic QR code generation with the lnbits-qrcode component.
This simplifies the code and utilizes a component specifically designed for LNbits applications.
Removes the input field for the invoice string as it is no longer necessary.
2025-10-23 03:20:07 +02:00
af424109f1 Enables admin to generate invoices for users
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
2025-10-23 03:07:47 +02:00
a2a58d323b Adds lightning payment option for settling receivables
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.
2025-10-23 03:04:50 +02:00
1412359172 Adds settle receivable functionality
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.
2025-10-23 02:57:21 +02:00
d06f46a63c Moves Quick Actions card to top
Moves the "Quick Actions" card to the top of the dashboard for better user accessibility and discoverability.
Removes the duplicate card at the bottom.
2025-10-23 02:45:50 +02:00