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
reverse_journal.py · 6.9 KB · 144 lines
1"""Reverse a posted journal: compose and post its mirror entry.
2
3Posted journals are immutable by design (transitions: posted -> []); every
4correction is a new compensating record (docs/logic-decisions.md #3). This
5action is the one-click version of that doctrine -- and the first real
6instance of a schema-derived action (the record's real verb, not an edit).
7
8POST payload: {"journal_id": "...", "date"?: "YYYY-MM-DD"}. Allowed for
9the journal's owner or an admin (the executing identity arrives in
10request["_identity"]). Refuses non-posted journals and journals already
11reversed (the unique generated_from key). The mirror swaps every line's debit/credit,
12stamps kind=reversing + generated_from="reversal:{id}", and posts (a mirror
13of a balanced entry is balanced by construction; re-verified anyway).
14
15The period lock (docs/logic-decisions.md #7: a generated entry faces the
16same gates). The mirror is dated `date` when given, else the original's
17date, and is refused (409) when that date lies in a closed period of the
18journal's books -- or when the closed periods cannot be read, because an
19unreadable lock is not an open one. compose_posted_journal writes at the
20storage level, so hook_fin_journals never sees this entry; the check has to
21be here. Until 2026-11-28 it was not, and reversing a journal from a filed
22quarter posted a mirror INTO the filed quarter
23(bug-reports/2026-11-28-06-14-37-CST-reverse-journal-posts-into-closed-period).
24
25What was rejected: silently dating the mirror "today" when the original's
26period is closed. That is the usual answer in accounting, but it moves an
27entry between periods without anybody choosing to, and "today" may itself
28be closed or belong to a different set of books' calendar. Refusing names
29the closed period and asks for a date; the person correcting filed books
30picks the open period the correction belongs to.
31
32The unattended composers (payments, expenses, stock, ...) do take the
33"usual answer" -- the first open day, flagged for review -- because nobody
34is there to ask (object_finance.compose_posted_journal). This action is a
35person at the keyboard, so it asks: compose is called with
36if_closed="refuse".
37
38A period closed between this check and the write used to land the mirror
39in it. It no longer can: fin_journals' locked check (hook_fin_journals.
40LOCKED_CHECK) refuses the header inside the write lock, and compose, told
41to refuse, answers that as a refusal rather than moving the date.
42"""
43
44import os
45import re
46
47import object_finance
48import object_records
49
50ACTOR = "action_reverse_journal"
51
52
53def _base_dir():
54 return os.environ.get("DBBASIC_DATA_DIR", "data")
55
56
57def POST(request):
58 identity = request.get("_identity") or {}
59 user_id = identity.get("user_id") or ""
60 roles = identity.get("roles") or []
61 journal_id = str(request.get("journal_id") or "").strip()
62 if not journal_id:
63 return {"status": 400, "error": "journal_id is required"}
64
65 base = _base_dir()
66 try:
67 # access: the journal must be the caller's own, or the caller an admin: checked on the next lines
68 journal = object_records.get_collection_record("fin_journals", journal_id, base_dir=base)
69 except Exception:
70 return {"status": 404, "error": f"Journal not found: {journal_id}"}
71
72 # The books are kept by the bookkeeper and the owner (decision 5,
73 # 2026-11-30): either may reverse any posted journal, as may an admin.
74 keeper = {str(r).split(":", 1)[-1] for r in roles} & {"admin", "finance", "owner"}
75 if not keeper and (not user_id or journal.get("owner_id") != user_id):
76 return {"status": 403, "error": ("Only the bookkeeper, the owner or an admin "
77 "may reverse a journal.")}
78 if journal.get("status") != "posted":
79 return {"status": 409, "error": "Only a posted journal can be reversed; edit the draft instead."}
80
81 # "Already reversed" is the books' provenance key, not a scan here:
82 # fin_journals.generated_from is unique (inside the write lock), and
83 # compose_posted_journal below answers a repeat with `skipped`.
84 marker = f"reversal:{journal_id}"
85
86 date = str(request.get("date") or "").strip() or str(journal.get("date") or "")
87 if request.get("date") and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date):
88 return {"status": 400, "error": "date must be YYYY-MM-DD"}
89 try:
90 period = object_finance.closed_period_for(
91 date, base_dir=base, owner_id=journal.get("owner_id", ""),
92 entity_id=journal.get("entity_id", ""), strict=True)
93 except Exception as exc:
94 return {"status": 409,
95 "error": ("Could not read the closed periods, so the reversal "
96 f"was not posted: {str(exc)[:200]}")}
97 if period is not None:
98 return {"status": 409,
99 "error": (f"{date} falls in a closed period "
100 f"({period.get('start_date')} to {period.get('end_date')}"
101 f"{': ' + period['reason'] if period.get('reason') else ''}). "
102 "Pass a date in an open period for the reversal."),
103 "closed_period": {"start_date": period.get("start_date", ""),
104 "end_date": period.get("end_date", "")}}
105
106 # access: lines of the journal checked above
107 lines = [
108 l for l in object_records.read_collection_records("fin_journal_lines", base_dir=base)
109 if l.get("journal_id") == journal_id
110 ]
111 if not lines:
112 return {"status": 409, "error": "Journal has no lines to reverse."}
113
114 composed = object_finance.compose_posted_journal(
115 base,
116 generated_from=marker,
117 date=date,
118 description=f"Reversal of {journal.get('reference') or journal.get('description') or journal_id}",
119 lines=[
120 {
121 "account_id": line.get("account_id", ""),
122 "debit_cents": line.get("credit_cents", "0"), # swapped
123 "credit_cents": line.get("debit_cents", "0"), # swapped
124 "memo": line.get("memo", ""),
125 "entity_id": line.get("entity_id", ""),
126 }
127 for line in lines
128 ],
129 owner_id=journal.get("owner_id", ""),
130 entity_id=journal.get("entity_id", ""),
131 kind="reversing",
132 actor=ACTOR,
133 if_closed="refuse",
134 )
135 if not composed.get("ok"):
136 return {"status": 409, "error": composed.get("error", "could not compose the mirror"),
137 **({"closed_period": composed["closed_period"]}
138 if composed.get("closed_period") else {})}
139 if composed.get("skipped"):
140 return {"status": 409, "error": f"Already reversed ({composed.get('journal_id', 'unknown')})."}
141 if composed.get("posted"):
142 return {"status": 200, "reversal_id": composed["journal_id"], "posted": True}
143 return {"status": 200, "reversal_id": composed["journal_id"], "posted": False,
144 "note": "left draft: mirror did not balance"}