Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
bank_matcher.py · 6.1 KB · 156 lines
1"""system_bank_matcher -- propose book-side records for unmatched bank lines.
2
3POST {bank_account_id?, today?} -- runs over unmatched lines and writes what
4it found onto each: match_status=suggested plus a `suggestions` JSON block
5saying which records, at which tier, and WHY. Schedulable daily like any
6other runner (the scheduler board shows its results).
7
8The important restraint: **the matcher suggests, a person confirms.** Only
9tier 1 (the record's reference appears in the statement text AND the amount
10agrees -- two independent signals) is auto-confirmable, and even that is
11configurable down to nothing:
12
13 reconcile.auto_match_tier 0 = never auto-match, 1 = tier 1 (default)
14 reconcile.date_window_days how far apart a line and a record may be (5)
15
16Confirming a match is deliberately NOT an action object -- it is an
17ordinary attributed record update, so the change log names who reconciled
18what and when. Reconciliation done invisibly by the same hands that move
19the money is the classic fraud hole; making confirmation a normal write
20closes it with machinery that already exists.
21
22Candidates are payments (money in) and refunds (money out), each converted
23to the statement's sign convention before comparison. Journals and bills
24join the candidate pool when those flows exist.
25"""
26
27import json
28import os
29
30import object_banking
31import object_records
32
33ACTOR = "system_bank_matcher"
34
35DEFAULT_WINDOW_DAYS = 5
36DEFAULT_AUTO_TIER = 1
37
38
39def _base_dir():
40 return os.environ.get("DBBASIC_DATA_DIR", "data")
41
42
43def _setting(base, key, default):
44 try:
45 for row in object_records.read_collection_records("app_settings", base_dir=base):
46 if row.get("key") == key and str(row.get("value") or "").strip():
47 return row["value"].strip()
48 except Exception:
49 pass
50 return default
51
52
53def _int_setting(base, key, default):
54 try:
55 return int(_setting(base, key, default))
56 except (TypeError, ValueError):
57 return default
58
59
60def _candidates(base, owner_id):
61 """Book-side records this line could be, in the statement's signs."""
62 out = []
63 try:
64 for payment in object_records.read_collection_records("payments", base_dir=base):
65 if owner_id and payment.get("owner_id") and payment["owner_id"] != owner_id:
66 continue
67 if (payment.get("status") or "received") != "received":
68 continue
69 out.append({
70 "ref": f"payments/{payment['id']}",
71 "amount_cents": int(payment.get("amount_cents") or 0), # money in: positive
72 "date": payment.get("received_on") or payment.get("created_at", "")[:10],
73 "reference": payment.get("reference") or "",
74 })
75 except Exception:
76 pass
77 try:
78 for refund in object_records.read_collection_records("refunds", base_dir=base):
79 if owner_id and refund.get("owner_id") and refund["owner_id"] != owner_id:
80 continue
81 out.append({
82 "ref": f"refunds/{refund['id']}",
83 "amount_cents": -abs(int(refund.get("amount_cents") or 0)), # money out
84 "date": refund.get("refunded_on") or refund.get("created_at", "")[:10],
85 "reference": refund.get("payment_id") or "",
86 })
87 except Exception:
88 pass
89 return out
90
91
92def _already_matched(lines):
93 """Refs already claimed by another line -- one book record, one line.
94
95 From the bank lines POST already read, every owner's: this used to
96 read them a second time and fold a failure to "nothing is claimed",
97 so a payment another line already held could be auto-matched again."""
98 return {row["matched_to"] for row in lines if row.get("matched_to")}
99
100
101def POST(request):
102 base = _base_dir()
103 identity = request.get("_identity") or {}
104 owner_id = identity.get("user_id") or ""
105 only_account = str(request.get("bank_account_id") or "").strip()
106
107 window = _int_setting(base, "reconcile.date_window_days", DEFAULT_WINDOW_DAYS)
108 auto_tier = _int_setting(base, "reconcile.auto_match_tier", DEFAULT_AUTO_TIER)
109
110 try:
111 lines = object_records.read_collection_records("bank_lines", base_dir=base)
112 except Exception:
113 return {"ok": True, "skipped": "banking not installed (bank_lines absent)"}
114
115 open_lines = [l for l in lines
116 if (l.get("match_status") or "unmatched") in ("unmatched", "suggested")
117 and not (only_account and l.get("bank_account_id") != only_account)
118 and not (owner_id and l.get("owner_id") and l["owner_id"] != owner_id)]
119 if not open_lines:
120 return {"ok": True, "scanned": 0, "suggested": 0, "auto_matched": 0, "results": []}
121
122 pool = _candidates(base, owner_id)
123 claimed = _already_matched(lines)
124 available = [c for c in pool if c["ref"] not in claimed]
125
126 suggested = auto_matched = 0
127 results = []
128 for line in open_lines:
129 proposals = object_banking.candidate_matches(
130 line, [c for c in available if c["ref"] not in claimed], window_days=window)
131 if not proposals:
132 continue
133 best = proposals[0]
134 changes = {"suggestions": json.dumps(proposals[:5])}
135 outcome = "suggested"
136 if best["tier"] <= auto_tier and len(best["refs"]) == 1:
137 changes["match_status"] = "matched"
138 changes["matched_to"] = best["refs"][0]
139 claimed.add(best["refs"][0])
140 auto_matched += 1
141 outcome = "auto_matched"
142 else:
143 changes["match_status"] = "suggested"
144 suggested += 1
145 try:
146 object_records.update_collection_record(
147 "bank_lines", line["id"], changes, base_dir=base, actor=ACTOR)
148 except Exception as exc:
149 results.append({"line": line["id"], "error": str(exc)[:160]})
150 continue
151 results.append({"line": line["id"], "outcome": outcome, "tier": best["tier"],
152 "refs": best["refs"], "why": best["why"]})
153
154 return {"ok": True, "scanned": len(open_lines), "suggested": suggested,
155 "auto_matched": auto_matched, "auto_match_tier": auto_tier,
156 "window_days": window, "results": results}