fix: harden valuation evidence selection
This commit is contained in:
@@ -86,7 +86,9 @@ def get_balance_reconciliation_report(account_id: str = "", baseline_balance: in
|
||||
effective_baseline = baseline_balance_int if baseline_balance_int is not None else account["last_balance"]
|
||||
effective_at = baseline_at_norm or account["last_synced_at"] or now_iso()
|
||||
calc = _account_balance_row(conn, account["id"], effective_at)
|
||||
valuation = conn.execute(
|
||||
valuation = None
|
||||
ambiguous_valuation = False
|
||||
valuation_rows = conn.execute(
|
||||
"""SELECT * FROM account_valuations v
|
||||
WHERE v.account_id=? AND v.verification_status='verified'
|
||||
AND v.basis_date<=?
|
||||
@@ -94,16 +96,25 @@ def get_balance_reconciliation_report(account_id: str = "", baseline_balance: in
|
||||
SELECT 1 FROM account_valuations child
|
||||
WHERE child.supersedes_id=v.id
|
||||
)
|
||||
ORDER BY CASE v.valuation_kind
|
||||
WHEN 'total_value' THEN 0
|
||||
WHEN 'balance' THEN 1
|
||||
WHEN 'cash_balance' THEN 2
|
||||
ELSE 3
|
||||
END,
|
||||
v.basis_date DESC, v.recorded_at DESC, v.id DESC
|
||||
LIMIT 1""",
|
||||
ORDER BY v.basis_date DESC, v.recorded_at DESC, v.id DESC""",
|
||||
(account["id"], effective_at[:10]),
|
||||
).fetchone()
|
||||
).fetchall()
|
||||
purposes = (
|
||||
("total_value", "balance", "cash_balance")
|
||||
if account["type"] == "investment"
|
||||
else ("cash_balance", "balance")
|
||||
)
|
||||
for purpose in purposes:
|
||||
scoped = [row for row in valuation_rows if row["valuation_kind"] == purpose]
|
||||
if not scoped:
|
||||
continue
|
||||
latest_basis = max(row["basis_date"] for row in scoped)
|
||||
latest = [row for row in scoped if row["basis_date"] == latest_basis]
|
||||
if len(latest) != 1:
|
||||
ambiguous_valuation = True
|
||||
else:
|
||||
valuation = latest[0]
|
||||
break
|
||||
if effective_baseline is None:
|
||||
difference = None
|
||||
ratio = None
|
||||
@@ -112,7 +123,10 @@ def get_balance_reconciliation_report(account_id: str = "", baseline_balance: in
|
||||
difference = int(effective_baseline) - int(calc["calculated_balance"])
|
||||
ratio = abs(difference) / abs(int(effective_baseline)) if int(effective_baseline) else None
|
||||
status = "OK" if abs(difference) <= tolerance_int else "REVIEW_NEEDED"
|
||||
if account["type"] == "investment" and valuation is not None:
|
||||
if account["type"] == "investment" and ambiguous_valuation:
|
||||
status = "AMBIGUOUS_VALUATION"
|
||||
difference = None
|
||||
elif account["type"] == "investment" and valuation is not None:
|
||||
status = "VALUATION_MANAGED"
|
||||
difference = None
|
||||
items.append({
|
||||
|
||||
Reference in New Issue
Block a user