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
fin_journal_lines.py · 6.6 KB · 159 lines
1"""Pre-write hook for fin_journal_lines: a settled journal's lines are
2settled too.
3
4A journal's AMOUNTS live in its lines. Whatever protects the journal
5record -- the closed-period gate in hook_fin_journals, the schema's
6`locked_when` on posted -- protects nothing if the lines under it can
7still move. So the same two rules, checked from the line's side:
8
9- **The parent journal is posted**: its lines are final. Balance is
10 checked once, on draft -> posted; after that a line edited to 1 cent,
11 a 777 debit added, or the credit line deleted each left a "posted"
12 journal that did not balance, and nothing refused any of them.
13- **The parent journal is dated in a closed period**: its lines are
14 settled books.
15
16Both are asked about EVERY journal the write touches. This hook used to
17read only the journal_id the line would have after the write, so a line
18was moved out of a posted FY2025 journal by PUTting journal_id to a 2026
19draft: the hook looked up the new parent, found it open, and passed --
20leaving the filed year at debit 0 / credit 10000. A move is a removal
21from one journal and an addition to another, so both are checked. And it
22did not run on delete at all.
23
24 create -> the journal the line joins
25 update -> the journal it is in AND the journal it would be in
26 delete -> the journal it is in
27
28Rejection-only. Lines on draft journals in open periods pass untouched --
29including the ordinary compose flow of drafting a journal and adding its
30lines. A journal_id that does not resolve is left to relation validation
31on create/update; on delete it means the line is an orphan, and removing
32an orphan settles nothing.
33
34Machine composers (object_finance.compose_posted_journal) write lines at
35the storage level and then post; they do not reach this hook.
36
37The closed-period half is also LOCKED_CHECK below
38(fin_journal_lines.json `locked_checks.closed_period`), which
39object_records calls inside the write lock for every writer, composers
40included, holding the `fin_periods` lock that writes to fin_journals and
41fin_closed_periods take too -- so neither the parent's date nor the
42period can move under it. Until 2026-11-30 the period rule lived only
43here, and the composers that write below this hook posted into closed
44months (bug report 2026-11-30-01-58-25-CST).
45
46The posted half stays advisory against a concurrent writer: a line edit
47that overlaps the post is checked against the draft
48(docs/validation-and-logic.md). It is not in the locked check because
49the composers write a draft's lines and then post, and nothing else at
50the storage level was found writing a posted journal's lines; a rule
51about another collection's state belongs in a locked check the day one
52is.
53
54Reads fail closed: a journal or the closed periods that cannot be read is
55a 503, not "not posted, not closed".
56"""
57
58import os
59
60import object_collections
61import object_finance
62import object_records
63
64_MISSING = (object_records.RecordNotFoundError,
65 object_collections.CollectionNotFoundError,
66 object_records.InvalidRecordIdError)
67
68
69def _base_dir():
70 return os.environ.get("DBBASIC_DATA_DIR", "data")
71
72
73def _unreadable(what):
74 return {"error": (f"{what} could not be read, so nothing can say whether this line "
75 "belongs to settled books. Nothing was changed."),
76 "status": 503}
77
78
79def _settled(journal_id, base, *, periods_only=False):
80 """A refusal when this journal's lines may no longer change.
81 periods_only: the closed-period rule alone (LOCKED_CHECK)."""
82 try:
83 journal = object_records.get_collection_record("fin_journals", journal_id, base_dir=base)
84 except _MISSING:
85 return None # relation validation owns a missing journal
86 except Exception:
87 return _unreadable("The journal")
88
89 try:
90 period = object_finance.closed_period_for(
91 journal.get("date"), base_dir=base,
92 owner_id=journal.get("owner_id") or "",
93 entity_id=journal.get("entity_id") or "",
94 strict=True)
95 except Exception:
96 return _unreadable("The closed periods")
97 if period is not None:
98 reason = str(period.get("reason") or "").strip()
99 label = f" ({reason})" if reason else ""
100 return {
101 "error": (f"This line belongs to a journal dated {journal.get('date')}, inside "
102 f"the closed period {period.get('start_date')} to "
103 f"{period.get('end_date')}{label}. Settled amounts are corrected by a "
104 "new journal in the current period, never by editing the old one's "
105 "lines."),
106 "status": 409,
107 }
108
109 if not periods_only and str(journal.get("status") or "") == "posted":
110 return {
111 "error": (f"Journal {journal_id} is posted, and a posted journal's lines are "
112 "final: it balanced when it was posted and must go on balancing. "
113 "Correct it with a reversing journal, never by adding, editing, "
114 "moving or removing a line."),
115 "status": 409,
116 }
117 return None
118
119
120def BEFORE_WRITE(request):
121 action = request.get("action")
122 if action not in ("create", "update", "delete"):
123 return None
124 return _judge(request, _base_dir(), periods_only=False)
125
126
127def _judge(request, base, *, periods_only):
128 action = request.get("action")
129 record = request.get("record") or {}
130 existing = request.get("existing") or {}
131
132 journals = []
133 if action in ("update", "delete"):
134 journals.append(str(existing.get("journal_id") or "").strip())
135 if action in ("create", "update"):
136 journals.append(str(record.get("journal_id") or "").strip())
137
138 seen = set()
139 for journal_id in journals:
140 if not journal_id or journal_id in seen:
141 continue # required/relation validation owns a blank parent
142 seen.add(journal_id)
143 refusal = _settled(journal_id, base, periods_only=periods_only)
144 if refusal:
145 return refusal
146 return None
147
148
149def LOCKED_CHECK(request):
150 """The closed-period rule, decided by object_records inside the write
151 lock for every writer (see the module docstring). Same three cases as
152 the hook -- the journal a line joins, the one it is in, both on a move
153 -- read under the fin_periods lock. A parent that does not exist yet
154 is allowed: object_materialize writes a generated journal's lines
155 before its header (the header is its commit signal), and the header's
156 own locked check refuses it if it is dated in a closed period."""
157 if request.get("action") not in ("create", "update", "delete"):
158 return None
159 return _judge(request, request.get("base_dir") or _base_dir(), periods_only=True)