Completes core logic refactoring (Phase 3)
Refactors the accounting logic into a clean, testable core module, separating business logic from database operations. This improves code quality, maintainability, and testability by creating a dedicated `core/` module, implementing `CastleInventory` for position tracking, moving balance calculations to `core/balance.py`, and adding comprehensive validation in `core/validation.py`.
This commit is contained in:
parent
6d84479f7d
commit
9c0bdc58eb
7 changed files with 1204 additions and 123 deletions
29
core/__init__.py
Normal file
29
core/__init__.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
"""
|
||||
Castle Core Module - Pure accounting logic separated from database operations.
|
||||
|
||||
This module contains the core business logic for double-entry accounting,
|
||||
following Beancount patterns for clean architecture:
|
||||
|
||||
- inventory.py: Position tracking across currencies
|
||||
- balance.py: Balance calculation logic
|
||||
- validation.py: Comprehensive validation rules
|
||||
|
||||
Benefits:
|
||||
- Testable without database
|
||||
- Reusable across different storage backends
|
||||
- Clear separation of concerns
|
||||
- Easier to audit and verify
|
||||
"""
|
||||
|
||||
from .inventory import CastleInventory, CastlePosition
|
||||
from .balance import BalanceCalculator
|
||||
from .validation import ValidationError, validate_journal_entry, validate_balance
|
||||
|
||||
__all__ = [
|
||||
"CastleInventory",
|
||||
"CastlePosition",
|
||||
"BalanceCalculator",
|
||||
"ValidationError",
|
||||
"validate_journal_entry",
|
||||
"validate_balance",
|
||||
]
|
||||
228
core/balance.py
Normal file
228
core/balance.py
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
"""
|
||||
Balance calculation logic for Castle accounting.
|
||||
|
||||
Pure functions for calculating account and user balances from journal entries,
|
||||
following double-entry accounting principles.
|
||||
"""
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Any, Dict, List, Optional
|
||||
from enum import Enum
|
||||
|
||||
from .inventory import CastleInventory, CastlePosition
|
||||
|
||||
|
||||
class AccountType(str, Enum):
|
||||
"""Account types in double-entry accounting"""
|
||||
ASSET = "asset"
|
||||
LIABILITY = "liability"
|
||||
EQUITY = "equity"
|
||||
REVENUE = "revenue"
|
||||
EXPENSE = "expense"
|
||||
|
||||
|
||||
class BalanceCalculator:
|
||||
"""
|
||||
Pure logic for calculating balances from journal entries.
|
||||
|
||||
This class contains no database access - it operates on data structures
|
||||
passed to it, making it easy to test and reuse.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def calculate_account_balance(
|
||||
total_debit: int,
|
||||
total_credit: int,
|
||||
account_type: AccountType
|
||||
) -> int:
|
||||
"""
|
||||
Calculate account balance based on account type.
|
||||
|
||||
Normal balances:
|
||||
- Assets and Expenses: Debit balance (debit - credit)
|
||||
- Liabilities, Equity, and Revenue: Credit balance (credit - debit)
|
||||
|
||||
Args:
|
||||
total_debit: Sum of all debits in satoshis
|
||||
total_credit: Sum of all credits in satoshis
|
||||
account_type: Type of account
|
||||
|
||||
Returns:
|
||||
Balance in satoshis
|
||||
"""
|
||||
if account_type in [AccountType.ASSET, AccountType.EXPENSE]:
|
||||
return total_debit - total_credit
|
||||
else:
|
||||
return total_credit - total_debit
|
||||
|
||||
@staticmethod
|
||||
def build_inventory_from_entry_lines(
|
||||
entry_lines: List[Dict[str, Any]],
|
||||
account_type: AccountType
|
||||
) -> CastleInventory:
|
||||
"""
|
||||
Build a CastleInventory from journal entry lines.
|
||||
|
||||
Args:
|
||||
entry_lines: List of entry line dictionaries with keys:
|
||||
- debit: int (satoshis)
|
||||
- credit: int (satoshis)
|
||||
- metadata: str (JSON string with optional fiat_currency, fiat_amount)
|
||||
account_type: Type of account (affects sign of amounts)
|
||||
|
||||
Returns:
|
||||
CastleInventory with positions for sats and fiat currencies
|
||||
"""
|
||||
import json
|
||||
|
||||
inventory = CastleInventory()
|
||||
|
||||
for line in entry_lines:
|
||||
# Parse metadata
|
||||
metadata = json.loads(line.get("metadata", "{}")) if line.get("metadata") else {}
|
||||
fiat_currency = metadata.get("fiat_currency")
|
||||
fiat_amount_raw = metadata.get("fiat_amount")
|
||||
|
||||
# Convert fiat amount to Decimal
|
||||
fiat_amount = Decimal(str(fiat_amount_raw)) if fiat_amount_raw else None
|
||||
|
||||
# Calculate amount based on debit/credit and account type
|
||||
debit = line.get("debit", 0)
|
||||
credit = line.get("credit", 0)
|
||||
|
||||
if debit > 0:
|
||||
sats_amount = Decimal(debit)
|
||||
# For liability accounts: debit decreases balance (negative)
|
||||
# For asset accounts: debit increases balance (positive)
|
||||
if account_type == AccountType.LIABILITY:
|
||||
sats_amount = -sats_amount
|
||||
fiat_amount = -fiat_amount if fiat_amount else None
|
||||
|
||||
inventory.add_position(
|
||||
CastlePosition(
|
||||
currency="SATS",
|
||||
amount=sats_amount,
|
||||
cost_currency=fiat_currency,
|
||||
cost_amount=fiat_amount,
|
||||
metadata=metadata,
|
||||
)
|
||||
)
|
||||
|
||||
if credit > 0:
|
||||
sats_amount = Decimal(credit)
|
||||
# For liability accounts: credit increases balance (positive)
|
||||
# For asset accounts: credit decreases balance (negative)
|
||||
if account_type == AccountType.ASSET:
|
||||
sats_amount = -sats_amount
|
||||
fiat_amount = -fiat_amount if fiat_amount else None
|
||||
|
||||
inventory.add_position(
|
||||
CastlePosition(
|
||||
currency="SATS",
|
||||
amount=sats_amount,
|
||||
cost_currency=fiat_currency,
|
||||
cost_amount=fiat_amount,
|
||||
metadata=metadata,
|
||||
)
|
||||
)
|
||||
|
||||
return inventory
|
||||
|
||||
@staticmethod
|
||||
def calculate_user_balance(
|
||||
accounts: List[Dict[str, Any]],
|
||||
account_balances: Dict[str, int],
|
||||
account_inventories: Dict[str, CastleInventory]
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Calculate user's total balance across all their accounts.
|
||||
|
||||
User balance represents what the Castle owes the user:
|
||||
- Positive: Castle owes user
|
||||
- Negative: User owes Castle
|
||||
|
||||
Args:
|
||||
accounts: List of account dictionaries with keys:
|
||||
- id: str
|
||||
- account_type: str (asset/liability/equity)
|
||||
account_balances: Dict mapping account_id to balance in sats
|
||||
account_inventories: Dict mapping account_id to CastleInventory
|
||||
|
||||
Returns:
|
||||
Dictionary with:
|
||||
- balance: int (total sats, positive = castle owes user)
|
||||
- fiat_balances: Dict[str, Decimal] (fiat balances by currency)
|
||||
"""
|
||||
total_balance = 0
|
||||
combined_inventory = CastleInventory()
|
||||
|
||||
for account in accounts:
|
||||
account_id = account["id"]
|
||||
account_type = AccountType(account["account_type"])
|
||||
balance = account_balances.get(account_id, 0)
|
||||
inventory = account_inventories.get(account_id, CastleInventory())
|
||||
|
||||
# Add sats balance based on account type
|
||||
if account_type == AccountType.LIABILITY:
|
||||
# Liability: positive balance means castle owes user
|
||||
total_balance += balance
|
||||
elif account_type == AccountType.ASSET:
|
||||
# Asset (receivable): positive balance means user owes castle (negative for user)
|
||||
total_balance -= balance
|
||||
# Equity contributions don't affect what castle owes
|
||||
|
||||
# Merge inventories for fiat tracking
|
||||
for position in inventory.positions.values():
|
||||
# Adjust sign based on account type
|
||||
if account_type == AccountType.ASSET:
|
||||
# For receivables, negate the position
|
||||
combined_inventory.add_position(position.negate())
|
||||
else:
|
||||
combined_inventory.add_position(position)
|
||||
|
||||
fiat_balances = combined_inventory.get_all_fiat_balances()
|
||||
|
||||
return {
|
||||
"balance": total_balance,
|
||||
"fiat_balances": fiat_balances,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def check_balance_matches(
|
||||
actual_balance_sats: int,
|
||||
expected_balance_sats: int,
|
||||
tolerance_sats: int = 0
|
||||
) -> bool:
|
||||
"""
|
||||
Check if actual balance matches expected within tolerance.
|
||||
|
||||
Args:
|
||||
actual_balance_sats: Actual calculated balance
|
||||
expected_balance_sats: Expected balance from assertion
|
||||
tolerance_sats: Allowed difference (±)
|
||||
|
||||
Returns:
|
||||
True if balances match within tolerance
|
||||
"""
|
||||
difference = abs(actual_balance_sats - expected_balance_sats)
|
||||
return difference <= tolerance_sats
|
||||
|
||||
@staticmethod
|
||||
def check_fiat_balance_matches(
|
||||
actual_balance_fiat: Decimal,
|
||||
expected_balance_fiat: Decimal,
|
||||
tolerance_fiat: Decimal = Decimal(0)
|
||||
) -> bool:
|
||||
"""
|
||||
Check if actual fiat balance matches expected within tolerance.
|
||||
|
||||
Args:
|
||||
actual_balance_fiat: Actual calculated fiat balance
|
||||
expected_balance_fiat: Expected fiat balance from assertion
|
||||
tolerance_fiat: Allowed difference (±)
|
||||
|
||||
Returns:
|
||||
True if balances match within tolerance
|
||||
"""
|
||||
difference = abs(actual_balance_fiat - expected_balance_fiat)
|
||||
return difference <= tolerance_fiat
|
||||
203
core/inventory.py
Normal file
203
core/inventory.py
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
"""
|
||||
Inventory system for position tracking.
|
||||
|
||||
Similar to Beancount's Inventory class, this module provides position tracking
|
||||
across multiple currencies with cost basis information.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CastlePosition:
|
||||
"""
|
||||
A position in the Castle inventory.
|
||||
|
||||
Represents an amount in a specific currency, optionally with cost basis
|
||||
information for tracking currency conversions.
|
||||
|
||||
Examples:
|
||||
# Simple sats position
|
||||
CastlePosition(currency="SATS", amount=Decimal("100000"))
|
||||
|
||||
# Sats with EUR cost basis
|
||||
CastlePosition(
|
||||
currency="SATS",
|
||||
amount=Decimal("100000"),
|
||||
cost_currency="EUR",
|
||||
cost_amount=Decimal("50.00")
|
||||
)
|
||||
"""
|
||||
|
||||
currency: str # "SATS", "EUR", "USD", etc.
|
||||
amount: Decimal
|
||||
|
||||
# Cost basis (for tracking conversions)
|
||||
cost_currency: Optional[str] = None # Original currency if converted
|
||||
cost_amount: Optional[Decimal] = None # Original amount
|
||||
|
||||
# Metadata
|
||||
date: Optional[datetime] = None
|
||||
metadata: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate position data"""
|
||||
if not isinstance(self.amount, Decimal):
|
||||
object.__setattr__(self, "amount", Decimal(str(self.amount)))
|
||||
|
||||
if self.cost_amount is not None and not isinstance(self.cost_amount, Decimal):
|
||||
object.__setattr__(
|
||||
self, "cost_amount", Decimal(str(self.cost_amount))
|
||||
)
|
||||
|
||||
def __add__(self, other: "CastlePosition") -> "CastlePosition":
|
||||
"""Add two positions (must be same currency and cost_currency)"""
|
||||
if self.currency != other.currency:
|
||||
raise ValueError(f"Cannot add positions with different currencies: {self.currency} != {other.currency}")
|
||||
|
||||
if self.cost_currency != other.cost_currency:
|
||||
raise ValueError(f"Cannot add positions with different cost currencies: {self.cost_currency} != {other.cost_currency}")
|
||||
|
||||
return CastlePosition(
|
||||
currency=self.currency,
|
||||
amount=self.amount + other.amount,
|
||||
cost_currency=self.cost_currency,
|
||||
cost_amount=(
|
||||
(self.cost_amount or Decimal(0)) + (other.cost_amount or Decimal(0))
|
||||
if self.cost_amount is not None or other.cost_amount is not None
|
||||
else None
|
||||
),
|
||||
date=other.date, # Use most recent date
|
||||
metadata={**self.metadata, **other.metadata},
|
||||
)
|
||||
|
||||
def negate(self) -> "CastlePosition":
|
||||
"""Return a position with negated amount"""
|
||||
return CastlePosition(
|
||||
currency=self.currency,
|
||||
amount=-self.amount,
|
||||
cost_currency=self.cost_currency,
|
||||
cost_amount=-self.cost_amount if self.cost_amount else None,
|
||||
date=self.date,
|
||||
metadata=self.metadata,
|
||||
)
|
||||
|
||||
|
||||
class CastleInventory:
|
||||
"""
|
||||
Track balances across multiple currencies with conversion tracking.
|
||||
|
||||
Similar to Beancount's Inventory but optimized for Castle's use case.
|
||||
Positions are keyed by (currency, cost_currency) to track different
|
||||
cost bases separately.
|
||||
|
||||
Examples:
|
||||
inv = CastleInventory()
|
||||
inv.add_position(CastlePosition("SATS", Decimal("100000")))
|
||||
inv.add_position(CastlePosition("SATS", Decimal("50000"), "EUR", Decimal("25")))
|
||||
|
||||
inv.get_balance_sats() # Returns: Decimal("150000")
|
||||
inv.get_balance_fiat("EUR") # Returns: Decimal("25")
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.positions: Dict[Tuple[str, Optional[str]], CastlePosition] = {}
|
||||
|
||||
def add_position(self, position: CastlePosition):
|
||||
"""
|
||||
Add or merge a position into the inventory.
|
||||
|
||||
Positions with the same (currency, cost_currency) key are merged.
|
||||
"""
|
||||
key = (position.currency, position.cost_currency)
|
||||
|
||||
if key in self.positions:
|
||||
self.positions[key] = self.positions[key] + position
|
||||
else:
|
||||
self.positions[key] = position
|
||||
|
||||
def get_balance_sats(self) -> Decimal:
|
||||
"""Get total balance in satoshis"""
|
||||
return sum(
|
||||
pos.amount
|
||||
for (curr, _), pos in self.positions.items()
|
||||
if curr == "SATS"
|
||||
)
|
||||
|
||||
def get_balance_fiat(self, currency: str) -> Decimal:
|
||||
"""
|
||||
Get balance in specific fiat currency from cost metadata.
|
||||
|
||||
This sums up all cost_amount values for positions that have
|
||||
the specified cost_currency.
|
||||
"""
|
||||
return sum(
|
||||
pos.cost_amount or Decimal(0)
|
||||
for (_, cost_curr), pos in self.positions.items()
|
||||
if cost_curr == currency
|
||||
)
|
||||
|
||||
def get_all_fiat_balances(self) -> Dict[str, Decimal]:
|
||||
"""Get balances for all fiat currencies present in the inventory"""
|
||||
fiat_currencies = set(
|
||||
cost_curr
|
||||
for _, cost_curr in self.positions.keys()
|
||||
if cost_curr
|
||||
)
|
||||
|
||||
return {
|
||||
curr: self.get_balance_fiat(curr)
|
||||
for curr in fiat_currencies
|
||||
}
|
||||
|
||||
def is_empty(self) -> bool:
|
||||
"""Check if inventory has no positions"""
|
||||
return len(self.positions) == 0
|
||||
|
||||
def is_zero(self) -> bool:
|
||||
"""
|
||||
Check if all positions sum to zero.
|
||||
|
||||
Returns True if the inventory has positions but they all sum to zero.
|
||||
"""
|
||||
return all(
|
||||
pos.amount == Decimal(0)
|
||||
for pos in self.positions.values()
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""
|
||||
Export inventory to dictionary format.
|
||||
|
||||
Returns:
|
||||
{
|
||||
"sats": 100000,
|
||||
"fiat": {
|
||||
"EUR": 50.00,
|
||||
"USD": 60.00
|
||||
}
|
||||
}
|
||||
"""
|
||||
fiat_balances = self.get_all_fiat_balances()
|
||||
|
||||
return {
|
||||
"sats": int(self.get_balance_sats()),
|
||||
"fiat": {
|
||||
curr: float(amount)
|
||||
for curr, amount in fiat_balances.items()
|
||||
},
|
||||
}
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""String representation for debugging"""
|
||||
if self.is_empty():
|
||||
return "CastleInventory(empty)"
|
||||
|
||||
positions_str = ", ".join(
|
||||
f"{curr}: {pos.amount}"
|
||||
for (curr, _), pos in self.positions.items()
|
||||
)
|
||||
return f"CastleInventory({positions_str})"
|
||||
324
core/validation.py
Normal file
324
core/validation.py
Normal file
|
|
@ -0,0 +1,324 @@
|
|||
"""
|
||||
Validation rules for Castle accounting.
|
||||
|
||||
Comprehensive validation following Beancount's plugin system approach,
|
||||
but implemented as simple functions that can be called directly.
|
||||
"""
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
class ValidationError(Exception):
|
||||
"""Raised when validation fails"""
|
||||
|
||||
def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.details = details or {}
|
||||
|
||||
|
||||
def validate_journal_entry(
|
||||
entry: Dict[str, Any],
|
||||
entry_lines: List[Dict[str, Any]]
|
||||
) -> None:
|
||||
"""
|
||||
Validate a journal entry and its lines.
|
||||
|
||||
Checks:
|
||||
1. Entry must have at least 2 lines (double-entry requirement)
|
||||
2. Entry must be balanced (sum of debits = sum of credits)
|
||||
3. All lines must have valid amounts (non-negative)
|
||||
4. All lines must have account_id
|
||||
|
||||
Args:
|
||||
entry: Journal entry dict with keys:
|
||||
- id: str
|
||||
- description: str
|
||||
- entry_date: datetime
|
||||
entry_lines: List of entry line dicts with keys:
|
||||
- account_id: str
|
||||
- debit: int
|
||||
- credit: int
|
||||
|
||||
Raises:
|
||||
ValidationError: If validation fails
|
||||
"""
|
||||
# Check minimum number of lines
|
||||
if len(entry_lines) < 2:
|
||||
raise ValidationError(
|
||||
"Journal entry must have at least 2 lines",
|
||||
{
|
||||
"entry_id": entry.get("id"),
|
||||
"line_count": len(entry_lines),
|
||||
}
|
||||
)
|
||||
|
||||
# Validate each line
|
||||
for i, line in enumerate(entry_lines):
|
||||
# Check account_id exists
|
||||
if not line.get("account_id"):
|
||||
raise ValidationError(
|
||||
f"Entry line {i + 1} missing account_id",
|
||||
{
|
||||
"entry_id": entry.get("id"),
|
||||
"line_index": i,
|
||||
}
|
||||
)
|
||||
|
||||
# Check amounts are non-negative
|
||||
debit = line.get("debit", 0)
|
||||
credit = line.get("credit", 0)
|
||||
|
||||
if debit < 0:
|
||||
raise ValidationError(
|
||||
f"Entry line {i + 1} has negative debit: {debit}",
|
||||
{
|
||||
"entry_id": entry.get("id"),
|
||||
"line_index": i,
|
||||
"debit": debit,
|
||||
}
|
||||
)
|
||||
|
||||
if credit < 0:
|
||||
raise ValidationError(
|
||||
f"Entry line {i + 1} has negative credit: {credit}",
|
||||
{
|
||||
"entry_id": entry.get("id"),
|
||||
"line_index": i,
|
||||
"credit": credit,
|
||||
}
|
||||
)
|
||||
|
||||
# Check that a line doesn't have both debit and credit
|
||||
if debit > 0 and credit > 0:
|
||||
raise ValidationError(
|
||||
f"Entry line {i + 1} has both debit and credit",
|
||||
{
|
||||
"entry_id": entry.get("id"),
|
||||
"line_index": i,
|
||||
"debit": debit,
|
||||
"credit": credit,
|
||||
}
|
||||
)
|
||||
|
||||
# Check that a line has at least one non-zero amount
|
||||
if debit == 0 and credit == 0:
|
||||
raise ValidationError(
|
||||
f"Entry line {i + 1} has both debit and credit as zero",
|
||||
{
|
||||
"entry_id": entry.get("id"),
|
||||
"line_index": i,
|
||||
}
|
||||
)
|
||||
|
||||
# Check entry is balanced
|
||||
total_debits = sum(line.get("debit", 0) for line in entry_lines)
|
||||
total_credits = sum(line.get("credit", 0) for line in entry_lines)
|
||||
|
||||
if total_debits != total_credits:
|
||||
raise ValidationError(
|
||||
"Journal entry is not balanced",
|
||||
{
|
||||
"entry_id": entry.get("id"),
|
||||
"total_debits": total_debits,
|
||||
"total_credits": total_credits,
|
||||
"difference": total_debits - total_credits,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def validate_balance(
|
||||
account_id: str,
|
||||
expected_balance_sats: int,
|
||||
actual_balance_sats: int,
|
||||
tolerance_sats: int = 0,
|
||||
expected_balance_fiat: Optional[Decimal] = None,
|
||||
actual_balance_fiat: Optional[Decimal] = None,
|
||||
tolerance_fiat: Optional[Decimal] = None,
|
||||
fiat_currency: Optional[str] = None
|
||||
) -> None:
|
||||
"""
|
||||
Validate that actual balance matches expected balance within tolerance.
|
||||
|
||||
Args:
|
||||
account_id: Account being checked
|
||||
expected_balance_sats: Expected satoshi balance
|
||||
actual_balance_sats: Actual calculated satoshi balance
|
||||
tolerance_sats: Allowed difference for sats (±)
|
||||
expected_balance_fiat: Expected fiat balance (optional)
|
||||
actual_balance_fiat: Actual fiat balance (optional)
|
||||
tolerance_fiat: Allowed difference for fiat (±)
|
||||
fiat_currency: Fiat currency code
|
||||
|
||||
Raises:
|
||||
ValidationError: If balance doesn't match
|
||||
"""
|
||||
# Check sats balance
|
||||
sats_difference = actual_balance_sats - expected_balance_sats
|
||||
if abs(sats_difference) > tolerance_sats:
|
||||
raise ValidationError(
|
||||
f"Balance assertion failed for account {account_id}",
|
||||
{
|
||||
"account_id": account_id,
|
||||
"expected_sats": expected_balance_sats,
|
||||
"actual_sats": actual_balance_sats,
|
||||
"difference_sats": sats_difference,
|
||||
"tolerance_sats": tolerance_sats,
|
||||
}
|
||||
)
|
||||
|
||||
# Check fiat balance if provided
|
||||
if expected_balance_fiat is not None and actual_balance_fiat is not None:
|
||||
if tolerance_fiat is None:
|
||||
tolerance_fiat = Decimal(0)
|
||||
|
||||
fiat_difference = actual_balance_fiat - expected_balance_fiat
|
||||
if abs(fiat_difference) > tolerance_fiat:
|
||||
raise ValidationError(
|
||||
f"Fiat balance assertion failed for account {account_id}",
|
||||
{
|
||||
"account_id": account_id,
|
||||
"currency": fiat_currency,
|
||||
"expected_fiat": float(expected_balance_fiat),
|
||||
"actual_fiat": float(actual_balance_fiat),
|
||||
"difference_fiat": float(fiat_difference),
|
||||
"tolerance_fiat": float(tolerance_fiat),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def validate_receivable_entry(
|
||||
user_id: str,
|
||||
amount: int,
|
||||
revenue_account_type: str
|
||||
) -> None:
|
||||
"""
|
||||
Validate a receivable entry (user owes castle).
|
||||
|
||||
Args:
|
||||
user_id: User ID
|
||||
amount: Amount in sats (must be positive)
|
||||
revenue_account_type: Must be "revenue"
|
||||
|
||||
Raises:
|
||||
ValidationError: If validation fails
|
||||
"""
|
||||
if amount <= 0:
|
||||
raise ValidationError(
|
||||
"Receivable amount must be positive",
|
||||
{"user_id": user_id, "amount": amount}
|
||||
)
|
||||
|
||||
if revenue_account_type != "revenue":
|
||||
raise ValidationError(
|
||||
"Receivable must credit a revenue account",
|
||||
{
|
||||
"user_id": user_id,
|
||||
"provided_account_type": revenue_account_type,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def validate_expense_entry(
|
||||
user_id: str,
|
||||
amount: int,
|
||||
expense_account_type: str,
|
||||
is_equity: bool
|
||||
) -> None:
|
||||
"""
|
||||
Validate an expense entry (user spent money).
|
||||
|
||||
Args:
|
||||
user_id: User ID
|
||||
amount: Amount in sats (must be positive)
|
||||
expense_account_type: Must be "expense" (unless is_equity is True)
|
||||
is_equity: If True, this is an equity contribution
|
||||
|
||||
Raises:
|
||||
ValidationError: If validation fails
|
||||
"""
|
||||
if amount <= 0:
|
||||
raise ValidationError(
|
||||
"Expense amount must be positive",
|
||||
{"user_id": user_id, "amount": amount}
|
||||
)
|
||||
|
||||
if not is_equity and expense_account_type != "expense":
|
||||
raise ValidationError(
|
||||
"Expense must debit an expense account",
|
||||
{
|
||||
"user_id": user_id,
|
||||
"provided_account_type": expense_account_type,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def validate_payment_entry(
|
||||
user_id: str,
|
||||
amount: int
|
||||
) -> None:
|
||||
"""
|
||||
Validate a payment entry (user paid their debt).
|
||||
|
||||
Args:
|
||||
user_id: User ID
|
||||
amount: Amount in sats (must be positive)
|
||||
|
||||
Raises:
|
||||
ValidationError: If validation fails
|
||||
"""
|
||||
if amount <= 0:
|
||||
raise ValidationError(
|
||||
"Payment amount must be positive",
|
||||
{"user_id": user_id, "amount": amount}
|
||||
)
|
||||
|
||||
|
||||
def validate_metadata(
|
||||
metadata: Dict[str, Any],
|
||||
required_keys: Optional[List[str]] = None
|
||||
) -> None:
|
||||
"""
|
||||
Validate entry line metadata.
|
||||
|
||||
Args:
|
||||
metadata: Metadata dictionary
|
||||
required_keys: List of required keys
|
||||
|
||||
Raises:
|
||||
ValidationError: If validation fails
|
||||
"""
|
||||
if required_keys:
|
||||
missing_keys = [key for key in required_keys if key not in metadata]
|
||||
if missing_keys:
|
||||
raise ValidationError(
|
||||
f"Metadata missing required keys: {', '.join(missing_keys)}",
|
||||
{
|
||||
"missing_keys": missing_keys,
|
||||
"provided_keys": list(metadata.keys()),
|
||||
}
|
||||
)
|
||||
|
||||
# Validate fiat currency and amount consistency
|
||||
has_fiat_currency = "fiat_currency" in metadata
|
||||
has_fiat_amount = "fiat_amount" in metadata
|
||||
|
||||
if has_fiat_currency != has_fiat_amount:
|
||||
raise ValidationError(
|
||||
"fiat_currency and fiat_amount must both be present or both absent",
|
||||
{
|
||||
"has_fiat_currency": has_fiat_currency,
|
||||
"has_fiat_amount": has_fiat_amount,
|
||||
}
|
||||
)
|
||||
|
||||
# Validate fiat amount is valid Decimal
|
||||
if has_fiat_amount:
|
||||
try:
|
||||
Decimal(str(metadata["fiat_amount"]))
|
||||
except (ValueError, TypeError) as e:
|
||||
raise ValidationError(
|
||||
f"Invalid fiat_amount: {metadata['fiat_amount']}",
|
||||
{"error": str(e)}
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue