Commit graph

108 commits

Author SHA1 Message Date
116df46d38 Net settlement + credit overflow on /receivables/settle (libra-#33, libra-#41)
When the caller omits settled_entry_links (the default), the endpoint
auto-detects open entries across both directions for the user and writes
a single transaction that:

  - Zeros every per-user account that has an open balance, not just the
    net (the libra-#33 bug — previously the 2-leg form left both Payable
    and Receivable carrying non-zero balances after a complete cash
    settlement, while only netting the cash side).
  - Routes any cash above the net obligation to Liabilities:Credit:User-X
    (libra-#41), so over-payment lands on a real liability account
    instead of silently drifting.
  - Attaches every reconciled source entry's link
    (exp-..., rcv-...) so a reader scanning the settlement transaction
    can trace what it cleared.

Cash less than the net obligation, with no explicit links, returns 400
with a structured diff (cash_paid, net_obligation, receivable_total,
payable_total). The operator either pays the exact net or passes
settled_entry_links to settle a specific subset; partial settlement
without a coherent target is not silently absorbed.

The legacy explicit-links code path is unchanged — callers that pass
settled_entry_links keep the 2-leg shape with no auto-detection. None
of the callers in libra or aiolabs/webapp currently use that field, but
the contract is preserved for the partial-settle-of-specific-entries
flow.

format_fiat_net_settlement_entry is the new helper for the 2/3/4-leg
shape; it enforces the cash-balance constraint inline so callers can't
accidentally produce an unbalanced transaction.

tests/test_settlement_api.py (6 tests) locks in:
  - Nancy's #33 scenario: receivable 100 + payable 50 + cash 50
    zeros both per-user accounts, links both source entries
  - Overpay: cash 70 against net 50 → credit balance 20
  - Pure receivable overpay → credit appears
  - Underpay without explicit links → 400 with diff
  - No open receivables → 400 with hint pointing at /payables/pay
  - Explicit settled_entry_links uses legacy 2-leg path

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-07 15:39:45 +02:00
50658440a4 Surface user credit balance in GET /balance per libra-#41
Extends get_user_balance_bql and get_all_user_balances_bql to fold
Liabilities:Credit:User-X into the same query as Payable and Receivable.
Credit is the overpay-absorbing liability that libra owes the user going
forward — it carries the same sign as Payable, so the existing fiat
aggregation subtracts it from net obligation without further changes.

Adds UserBalance.account_balances to surface the BQL per-account
breakdown so libra extension UI and webapp can render Payable /
Receivable / Credit as distinct line items. The legacy `accounts` field
stays empty for back-compat with anything reading the older shape.

Prepares for libra-#33 / libra-#41: settlement netting (#14 task) will
write the overflow leg to credit; this changeset makes sure that, the
moment credit exists, the displayed net everywhere already reflects it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-07 15:39:45 +02:00
9c88993c13 Merge pull request 'Show voided transactions in user-entries endpoint' (#34) from feat/show-voided-user-entries into main
Reviewed-on: #34
2026-06-07 13:38:30 +00:00
1c89e69030 feat(api): include voided transactions in user-entries endpoint
The /api/v1/entries/user view was silently dropping any transaction tagged
'voided', so users couldn't see entries that had been rejected against
their accounts. Per the libra reject convention, voided entries keep the
'!' flag and carry a 'voided' tag for audit; clients can use the tag to
style them distinctly. Pending-approval listing still filters voided.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-06 20:47:27 +02:00
34ecb3f249 Add POST /api/v1/admin/accounts for chart-of-accounts entries
Companion to the fava ledger split (aiolabs/server-deploy#4). Super-user
endpoint that adds a new Open directive to accounts/chart.beancount via
fava_client.add_account (explicit target_file), then mirrors the account
into Libra's DB via sync_single_account_from_beancount so permissions can
be granted on it.

Validates the account name against the five Beancount top-level prefixes
(Assets:/Liabilities:/Equity:/Income:/Expenses:) and returns 400 on a bad
prefix.

Per-user accounts (matching :User-xxxxxxxx) keep their existing code path
via crud.get_or_create_user_account, which inherits the inferred target_file
(accounts/users.beancount) from the add_account default.

Backend only -- the LNbits admin UI on top is tracked separately as
aiolabs/libra#30.

Refs: aiolabs/libra#29
2026-06-06 15:30:23 +02:00
1201557f0c Gate cross-user admin endpoints behind require_super_user
Twenty-six endpoints documented "(admin only)" were using
require_admin_key, which only checks the caller owns a wallet with
its admin key — not LNbits-instance admin. Any logged-in user could
fabricate receivables against any other user_id, grant themselves
MANAGE permission on any account, create + self-assign privileged
roles, etc.

Swaps Depends(require_admin_key) -> Depends(require_super_user) on:
receivable/revenue creation, equity-eligibility grant/revoke/list,
permission grant/list/revoke/bulk/bulk-grant, account-sync admin,
role + role-permission + user-role CRUD, cross-user contributions
and unsettled-entries reports.

Also deletes the unsafe duplicate /api/v1/pay-user — both function
defs shared the name api_pay_user, the second shadowed the first at
module scope but FastAPI registered both routes. /api/v1/payables/pay
already provides the super-user-gated equivalent.

Two pre-existing orphan wallet.wallet.user references inside
api_settle_receivable and api_approve_manual_payment_request (both
already used the auth parameter) would have raised NameError at
runtime; fixed in passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-05 22:57:59 +02:00
deeec7e2c5 Add lifetime income/expense totals to UserBalance
New get_user_lifetime_totals_bql() runs tag-filtered BQL queries
(Payable + expense-entry, Receivable + income-entry) to compute
per-user lifetime totals separately from the net balance. Plumbed
through /api/v1/balance and /api/v1/balance/{user_id}; existing
clients keep working (fields default to zero / empty dict).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 16:06:16 +02:00
0f2a38ee7f Record income receipts as a user receivable, not an entity asset
When a user submits income, the money is physically in *their* pocket,
not the entity's cash drawer. The original income endpoint posted DR
on a configurable payment-method asset account (Cash/Bank/Lightning),
which implicitly assumed the entity already had the funds.

Mirror the expense flow instead: DR Assets:Receivable:User-{id[:8]}
(via get_or_create_user_account), CR the revenue account. The user
now owes the entity until they hand the cash over via the existing
/settle-receivable workflow. With this, the per-user Outstanding
Balances card correctly nets expenses (entity owes user, -liability)
against income receipts (user owes entity, +receivable).

Drops payment_method_account from IncomeEntry — no longer needed.
2026-05-16 23:40:08 +02:00
93b5c2677c Add user-facing income/revenue submission endpoint
Mirrors the existing expense submission flow so non-admin users can log
income on behalf of the organization for super-user review. New endpoint
POST /api/v1/entries/income takes invoice-key auth, creates a Beancount
transaction with the pending '!' flag, and reuses the existing
/entries/{id}/approve and /reject endpoints (which match by libra-{id}
link regardless of entry type).

Adds PermissionType.SUBMIT_INCOME granted on revenue accounts (parallel
to SUBMIT_EXPENSE on expense accounts) rather than overloading
SUBMIT_EXPENSE — the two operations target distinct account types and
should be grantable independently. Enforces AccountType.REVENUE on the
income account and AccountType.ASSET on the payment-method account;
fiat currency is required (matches the expense flow's effective
requirement). Income entries get a 'income-entry' tag and an
^inc-{entry_id} link for tracking, and surface in the existing
/entries/pending list for super-user approval.

UI work lives in the standalone webapp, out of scope here.

Closes #9

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 19:01:47 +02:00
4085280711 Filter synthetic Beancount entries from journal listings
The Recent Transactions card was showing Beancount-generated opening-balance
entries from ledger summarization (flag 'S'). Adds a _SYNTHETIC_FLAGS set
mirroring Fava's _EXCL_FLAGS (S/T/C/P/U/R/M) and skips matching entries in
the two user-facing endpoints that previously only filtered by transaction
type. Other journal callers already filter by flag '!' so are unaffected.

Closes #3

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 09:43:32 +02:00
b2b2c109a4 Clean up awkward "the Libra" phrasing left over from rename
Replaces entity-sense references to "the Libra" with "the
organization"/"the collective" where Libra was being used as a
stand-in for the original "Castle" entity, and drops the redundant
"(like cooperatives)" parenthetical in DOCUMENTATION.md. Also swaps
the 🏰 emoji in the import helper for ⚖️.

Closes #12

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 08:37:30 +02:00
c174cda48d Rename Castle Accounting extension to Libra
Full identifier rename: module path lnbits.extensions.castle →
lnbits.extensions.libra, DB ext_castle → ext_libra, URL prefix
/castle/ → /libra/, manifest id castle → libra, fava ledger slug
default castle-ledger → libra-ledger, Beancount source metadata
castle-api → libra-api and link prefixes castle-{entry,tx}- →
libra-{entry,tx}-, column castle_wallet_id → libra_wallet_id, all
Python/JS/HTML identifiers (castle_ext, CastleSettings,
castle_reference, castleWalletConfigured, etc.).

Display name "Castle Accounting" → "Libra" (the scales/balance
metaphor — fits double-entry bookkeeping).

No backward compat: production hosts will be force-updated. Old
castle-prefixed Beancount metadata in existing Fava ledgers is
historical; new entries use libra-* prefixes going forward.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 10:24:46 +02:00
Patrick Mulligan
c4f784360d Fix Pay User lightning payment bugs
- Fix default amount showing fiat instead of sats when lightning payment selected
- Fix invoice response field name (bolt11 instead of payment_request)
- Fix NameError in payables/pay endpoint (wallet -> auth.user_id)
- Add get_user_wallet_settings_by_prefix() for truncated 8-char user IDs
- Update user-wallet endpoint to handle truncated IDs from Beancount accounts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 07:17:12 -05:00
8d9e14ee5a Fix approve/reject endpoints to use Fava source API correctly
The Fava /context endpoint returns structured entry data, not raw source
text with slice/sha256sum as expected. Updated both endpoints to:

1. Get entry metadata (filename, lineno) from the parsed entry
2. Read the full source file via GET /source
3. Modify the specific line at the entry's line number
4. Write back via PUT /source with sha256sum for concurrency control

- Approve: Changes flag from '!' to '*' at the entry line
- Reject: Adds #voided tag to the entry line

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 15:47:09 +01:00
ca0cee7312 Add centralized authorization module and fix security vulnerabilities
- Create auth.py with AuthContext, require_super_user, require_authenticated
- Fix 6 CRITICAL unprotected endpoints exposing sensitive data
- Consolidate 16+ admin endpoints with duplicated super_user checks
- Standardize on user_id (wallet.wallet.user) instead of wallet_id

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 13:35:07 +01:00
Patrick Mulligan
e403ec223d Add settlement links to payment entries for traceability
- Add settled_entry_links parameter to format_payment_entry and format_net_settlement_entry
- Query unsettled expenses/receivables before creating settlement entries
- Pass original entry links to format functions so settlements reference what they settle
- Update all callers in views_api.py (5 locations) and tasks.py (1 location)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 19:34:25 +01:00
Patrick Mulligan
da74e668c8 Fix entry_id mismatch between castle links and exp/rcv links
Pass entry_id from views_api.py to format_expense_entry and
format_receivable_entry so that all links use the same ID:
- ^castle-{entry_id}
- ^exp-{entry_id} / ^rcv-{entry_id}
- entry-id metadata

Previously, views_api.py generated an entry_id for castle-* links
but didn't pass it to the format functions, which generated their
own separate IDs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 18:34:45 +01:00
1ae5c8c927 Fix missing Optional import in views_api.py
Added typing.Optional import that was missing after adding the
report endpoints with optional date parameters.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-15 01:21:44 +01:00
7dabe8700d Add BQL-based report endpoints for expenses and contributions
New endpoints:
- GET /api/v1/reports/expenses - Expense summary by account or month
- GET /api/v1/reports/contributions - User contribution totals

New FavaClient methods:
- get_expense_summary_bql() - Aggregates expenses with date filtering
- get_user_contributions_bql() - Aggregates user expense submissions

Both use sum(weight) for efficient SATS aggregation from price notation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-15 01:15:29 +01:00
49d18c3e73 Update get_account_balance to use sum(weight) for SATS
Replace sum(position) with sum(weight) for efficient SATS aggregation
from price notation. Also return fiat amount from sum(number).

This simplifies the parsing logic and provides consistent SATS totals
across all BQL-based balance methods.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-15 01:10:46 +01:00
048d19f90b Add BQL-optimized get_unsettled_entries_bql method
Replace inefficient approach that fetched ALL journal entries with
targeted BQL queries that:
- Filter by account pattern and tags in the database
- Use weight column for SATS amounts (no string parsing)
- Query only expense/receivable entries for the specific user

This significantly reduces data transfer and processing overhead.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-15 01:08:38 +01:00
913e4705b1 Fix amount parsing to handle both @ and @@ SATS notation
Pending expense entries use per-unit price notation (@ SATS) while
migrated entries use total price notation (@@ SATS).

Formats handled:
- "50.00 EUR @@ 50000 SATS" - total price (multiply = amount)
- "50.00 EUR @ 1000.5 SATS" - per-unit price (multiply for total)
- "50.00 EUR" with metadata - legacy format
- "50000 SATS" - old SATS-first format

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-15 00:19:49 +01:00
7173e051fe Use BQL sum(weight) for efficient SATS balance queries
Now that the ledger uses @@ SATS price notation, BQL can efficiently
aggregate SATS balances using the weight column instead of manual
entry-by-entry aggregation.

Changes:
- fava_client.py: Update get_user_balance_bql() and get_all_user_balances_bql()
  to use sum(weight) for SATS aggregation (5-10x performance improvement)
- views_api.py: Switch all balance endpoints to use BQL methods

The weight column returns the @@ price value, enabling server-side
filtering and aggregation instead of fetching all entries.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-14 23:58:56 +01:00
dfdcc441a1 Add expense-to-settlement linking with price notation
Implement transaction linking to connect expenses with their settlements,
enabling audit trails and tracking of individual expense reimbursements.

Changes:
- beancount_format.py: Use @@ SATS price notation for BQL queryability,
  generate unique ^exp-{id} and ^rcv-{id} links, add #settlement tag
- fava_client.py: Add get_unsettled_entries() to find unlinked expenses
- models.py: Add settled_entry_links field to PayUser/SettleReceivable
- views_api.py: Add GET /users/{id}/unsettled-entries endpoint,
  pass settlement links through pay_user and settle_receivable

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-14 23:40:33 +01:00
1d2eb05c36 Adds custom date range filtering to transactions
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.
2025-12-14 12:47:23 +01:00
52c6c3f8f1 Fix RBAC role-based permissions for accounts endpoint
Fixed critical bugs preventing users from seeing accounts through their assigned roles:

1. **Fixed duplicate function definition** (crud.py)
   - Removed duplicate auto_assign_default_role() that only took 1 parameter
   - Kept correct version with proper signature and logging
   - Added get_all_user_roles() helper function

2. **Added role-based permissions to accounts endpoint** (views_api.py)
   - Previously only checked direct user permissions
   - Now retrieves and combines both direct AND role permissions
   - Auto-assigns default role to new users on first access

3. **Fixed permission inheritance logic** (views_api.py)
   - Inheritance check now uses combined permissions (direct + role)
   - Previously only checked direct user permissions for parents
   - Users can now inherit access to child accounts via role permissions

Changes enable proper RBAC functionality:
- Users with "Employee" role (or any role) now see permitted accounts
- Permission inheritance works correctly with role-based permissions
- Auto-assignment of default role on first Castle access

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-12 03:00:17 +01:00
c086916be8 Add RBAC API endpoints - Phase 2A
Implemented comprehensive REST API for role-based access control:

Role Management Endpoints (Admin only):
- GET /api/v1/admin/roles - List all roles with user/permission counts
- POST /api/v1/admin/roles - Create new role
- GET /api/v1/admin/roles/{role_id} - Get role details with permissions and users
- PUT /api/v1/admin/roles/{role_id} - Update role (name, description, is_default)
- DELETE /api/v1/admin/roles/{role_id} - Delete role (cascades to permissions/assignments)

Role Permission Endpoints (Admin only):
- POST /api/v1/admin/roles/{role_id}/permissions - Add permission to role
- DELETE /api/v1/admin/roles/{role_id}/permissions/{permission_id} - Remove permission

User Role Assignment Endpoints (Admin only):
- POST /api/v1/admin/user-roles - Assign user to role (with optional expiration)
- GET /api/v1/admin/user-roles/{user_id} - Get user's role assignments
- DELETE /api/v1/admin/user-roles/{user_role_id} - Revoke role assignment

User Endpoints:
- GET /api/v1/users/me/roles - Get current user's roles and effective permissions
  (includes both role-based and direct permissions)

All endpoints include:
- Proper error handling with HTTP status codes
- Admin key requirement for management operations
- Rich response data with timestamps and metadata
- Role details enriched with user counts and permission counts

Next: Implement Roles tab UI and JavaScript integration

🤖 Generated with Claude Code
2025-11-11 23:47:13 +01:00
61a3831b15 Add user-selectable date range filters for Recent Transactions
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>
2025-11-11 22:54:14 +01:00
bf79495ceb Optimize recent transactions with 30-day date filter
Performance improvement for large ledgers:
- Added optional 'days' parameter to get_journal_entries()
- User dashboard now fetches only last 30 days of entries
- Dramatically reduces data transfer for ledgers with 100+ entries
- Filters in Python after fetching from Fava API

Example impact: 229 entries → ~20-50 entries (typical 30-day activity)

This is a "quick win" optimization as recommended for accounting systems
with growing transaction history. Admin endpoints still fetch all entries.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-11 22:39:22 +01:00
7506b0250f Fix super user bypass and show virtual accounts in admin UI
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>
2025-11-11 03:33:31 +01:00
0e6fe3e3cd Fix virtual account filtering and permission inheritance
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>
2025-11-11 03:25:49 +01:00
ed1e6509ee Add bulk grant permission API endpoint
New Features:
- BulkGrantPermission model: Grant same permission to multiple users
- BulkGrantResult model: Detailed success/failure results
- POST /api/v1/admin/permissions/bulk-grant endpoint

This simplifies the admin workflow for granting the same account
permission to multiple users at once (e.g., onboarding a team).

The endpoint validates the account exists and is active, then grants
the permission to each user, collecting successes and failures to
return a detailed result.

Related: UI-IMPROVEMENTS-PLAN.md Phase 1
2025-11-11 02:13:59 +01:00
4a3922895e Integrate account sync with API, background tasks, and user creation
Integration Components:
1. Manual API Endpoints (admin-only):
   - POST /api/v1/admin/accounts/sync (full sync)
   - POST /api/v1/admin/accounts/sync/{account_name} (single account)

2. Scheduled Background Sync:
   - Hourly background task (wait_for_account_sync)
   - Registered in castle_start() lifecycle
   - Automatically syncs new accounts from Beancount to Castle DB

3. Auto-sync on User Account Creation:
   - Updated get_or_create_user_account() in crud.py
   - Uses sync_single_account_from_beancount() for consistency
   - Ensures receivable/payable accounts are synced when users register

Flow:
- User associates wallet → creates receivable/payable in Beancount
  → syncs to Castle DB → permissions can be granted
- Admin manually syncs → all Beancount accounts added to Castle DB
- Hourly task → catches any accounts created directly in Beancount

This ensures Beancount remains the source of truth while Castle DB
maintains metadata for permissions and user associations.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-11 01:28:59 +01:00
9974a8fa64 USERNAME DEBUG LOGS removal 2025-11-10 22:59:06 +01:00
a3c3e44e5f Implement hybrid approach for balance assertions
Balance assertions now use a hybrid architecture where Beancount is the source
of truth for validation, while Castle stores metadata for UI convenience.

Backend changes:
- Add format_balance() function to beancount_format.py for formatting balance directives
- Update POST /api/v1/assertions to write balance directive to Beancount first (via Fava)
- Store metadata in Castle DB (created_by, tolerance, notes) for UI features
- Validate assertions immediately by querying Fava for actual balance

Frontend changes:
- Update dialog description to explain Beancount validation
- Update button tooltip to clarify balance assertions are written to Beancount
- Update empty state message to mention Beancount checkpoints

Benefits:
- Single source of truth (Beancount ledger file)
- Automatic validation by Beancount
- Best of both worlds: robust validation + friendly UI

See misc-docs/BALANCE-ASSERTIONS-HYBRID-APPROACH.md for full documentation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-10 20:46:12 +01:00
74115b7e5b drop old db tables and remove old functions 2025-11-10 20:02:01 +01:00
4220ff285e attempt to fix usernames 2025-11-10 19:39:14 +01:00
1b1d066d07 update CLAUDE.md 2025-11-10 19:32:00 +01:00
87a3505376 Enriches journal entries with usernames
Enhances the journal entries API to include username information.

This is achieved by extracting the user ID from transaction
metadata or account names and retrieving the corresponding
username. A default username is provided if the user is not found.

The pending entries API is updated with the same functionality.
2025-11-10 16:21:21 +01:00
700beb6f7f Improves amount parsing for new architecture
Prioritizes parsing amount strings in the new EUR/USD format and introduces support for metadata containing sats equivalent.
Fallbacks to legacy parsing when the new format is not detected.
This ensures correct interpretation of amount data from different sources.
2025-11-10 16:17:23 +01:00
51ae2e8e47 Sanitizes reference links for Beancount
Ensures that user-provided reference strings for expense,
receivable, and revenue entries are sanitized before being
included as Beancount links. This prevents issues caused by
invalid characters in the links, improving compatibility with
Beancount's link format. A new utility function is introduced
to handle the sanitization process.
2025-11-10 15:04:27 +01:00
a6b67b7416 Improves Beancount entry generation and sanitization
Adds a function to sanitize strings for use as Beancount links,
ensuring compatibility with Beancount's link restrictions.

Refactors the journal entry creation process to use EUR-based
postings when fiat currency is provided, improving accuracy
and consistency. The legacy SATS-based fallback is retained for
cases without fiat currency information.

Adjusts reference generation for Beancount entries using the
sanitized description.
2025-11-10 11:35:41 +01:00
0e93fc5ffc Enhances Beancount import and API entry creation
Improves the Beancount import process to send SATS amounts with fiat metadata to the API, enabling automatic conversion to EUR-based postings.
Updates the API to store entries in Fava instead of the Castle DB, simplifying the JournalEntry creation process.
Adds error handling to the upload entry function.
Includes a note about imported transactions being stored in EUR with SATS in metadata.
2025-11-10 11:29:01 +01:00
490b361268 Adds fiat settlement entry formatting
Introduces a function to format fiat settlement entries for Beancount, handling cash, bank transfers, and other non-lightning payments.

This allows for recording transactions in fiat currency with sats as metadata.

Updates the API endpoint to use the new function when settling receivables with fiat currencies.
2025-11-10 10:51:55 +01:00
8342318fde Refactors duplicate payment check in Fava
Improves payment recording logic by fetching recent entries and filtering using Python, replacing the BQL query.

This addresses issues with matching against set types in BQL, enhancing reliability.
2025-11-10 10:25:05 +01:00
313265b185 Supports new EUR/USD amount string format
Adds support for parsing direct EUR/USD amount strings in the format "37.22 EUR" or "12.34 USD".

It also retrieves the SATS equivalent from the metadata if present, for the new amount format. This ensures compatibility with both the old "SATS {EUR}" format and the newer, direct fiat formats.
2025-11-10 03:46:17 +01:00
476e9dec4b Supports new amount format and metadata tracking
Updates the amount parsing logic to support a new format where fiat amounts (EUR/USD) are specified directly.

Adds support for tracking SATS equivalents from metadata when the new format is used.

Also tracks fiat amounts specified in metadata as a fallback for backward compatibility.
Reverses the calculation of net balance to correctly reflect receivables and liabilities.
2025-11-10 03:42:30 +01:00
8396331d5a Calculates user balance from journal entries
Refactors user balance calculation to directly parse journal
entries, enhancing accuracy and efficiency. This change
eliminates reliance on direct database queries and provides a
more reliable mechanism for determining user balances.

Adds logging for debugging purposes.

Also extracts and uses fiat metadata from invoice/payment extras.
2025-11-10 02:18:49 +01:00
0f24833e02 Adds unique IDs to receivable and revenue entries
Ensures unique identification for receivable and
revenue entries by generating a UUID and incorporating
it into a castle reference.

This enhances tracking and linking capabilities by
providing a consistent and easily identifiable
reference across the system.
2025-11-10 01:26:59 +01:00
3cb3b23a8d Improves pending entry amount parsing
Updates the pending entries API to correctly parse the amount and fiat values from the amount string, which can now contain both SATS and fiat information.

This change handles different formats of the amount string, including cases where the fiat amount is present within curly braces.
2025-11-10 01:09:49 +01:00