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

9 downloads

dbbasic-object-server/object_assets.py
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, 7 minutes ago History
object_assets.py · 46.6 KB · 975 lines
1"""Fixed assets and losses: depreciation arithmetic, and the pass that books
2what packages/app-assets' register says.
3
4Two halves, kept apart on purpose (AGENTS.md section 5, "pure logic at the
5root, I/O in packages" -- with object_finance's exception: the composer
6reads and writes, because three objects need the same sequence):
7
8PURE (no I/O, no clock): component_amounts, book_schedule, tax_schedule,
9disposal_result, disposal_lines. They take rows and integers and return
10integers. Every amount is integer cents (doctrine #10); the only division
11is integer division with an explicit rounding rule, so a schedule computed
12twice, on two machines, in two years, is the same schedule.
13
14I/O: books_pass_for_asset, books_pass_for_loss, run_register. They read the
15register (fixed_assets, asset_work, asset_disposals, loss_events) and the
16books, and compose journals through object_finance.compose_posted_journal,
17which owns idempotency (generated_from, declared unique on fin_journals and
18checked inside the write lock) and the closed-period policy (a date in a
19closed period books on the first open day, flagged for review). Callers own
20nothing but WHEN: the daily schedule, the on-demand action, an event
21handler -- all three call the same function, and a replay of any of them
22posts nothing twice.
23
24Decisions an accountant would ask about, stated once here and in
25docs/assets-and-losses.md:
26
27- Full-month convention. An asset (or an improvement) depreciates for the
28 whole month it is placed in service, and not at all for the month it is
29 disposed of. Simple, and the month count comes out right: a 60-month life
30 is 60 journals. Mid-month and half-year conventions are tax conventions;
31 they are not modelled.
32- Straight line spreads (cost - salvage) over the life in whole cents: month
33 k books floor(base*k/life) - floor(base*(k-1)/life), so the cents left by
34 the division fall into the months where the running total crosses them
35 and the last month lands EXACTLY on salvage. No drift, no plug.
36- Declining balance books round(NBV * rate / life) each month (rate in basis
37 points: 20000 is "double declining"), switching to straight line over the
38 remaining months when that is larger, never below salvage, and the last
39 month of the life books whatever is left above salvage.
40- An improvement is its own component: its cost starts depreciating in the
41 month it was performed, over its own life (blank: the asset's remaining
42 book life, at least one month), same method, no salvage of its own. The
43 asset's salvage stays the floor for the asset as a whole.
44- What is booked each month is the SCHEDULE's running total minus what the
45 books already hold for this asset. A late-recorded improvement is caught
46 up in the next unbooked month instead of rewriting a posted one (money
47 moves, it does not mutate -- doctrine #3); a depreciation journal somebody
48 reversed by hand is caught up the same way.
49- Tax depreciation is never booked. The tax columns are data (a method, a
50 life, a salvage) and a simple method computed from them, or amounts an
51 operator typed from the accountant's figures. MACRS tables, Section 179,
52 bonus depreciation and conventions are not implemented and must not be
53 guessed at here: ask your accountant.
54"""
55
56from __future__ import annotations
57
58import datetime as _dt
59from typing import Any, Iterable
60
61import object_collections
62import object_finance
63import object_records
64
65BOOK_METHODS = ("straight_line", "declining", "none")
66TAX_METHODS = ("none", "straight_line", "declining", "operator_entered")
67DEFAULT_DECLINING_RATE_BPS = 20000
68
69# Kinds of disposal whose loss must be an APPROVED loss event before the
70# books take it: somebody other than the reporter has seen the evidence.
71DISPOSALS_NEEDING_APPROVAL = ("theft", "casualty")
72
73ACTOR = "object_assets"
74
75
76# === small parsers ==========================================================
77
78def _text(value: Any) -> str:
79 return str(value if value is not None else "").strip()
80
81
82def _cents(value: Any) -> int:
83 """Integer cents from a stored cell; blank is 0. object_finance.to_cents
84 is the ledger's one defensive parser (it floors a stray fraction)."""
85 return object_finance.to_cents(value)
86
87
88def _count(value: Any) -> int:
89 text = _text(value)
90 if not text:
91 return 0
92 try:
93 return int(text)
94 except ValueError:
95 return 0
96
97
98# === months =================================================================
99
100def month_of(date_text: Any) -> str:
101 """'2026-03' for '2026-03-14' (or a datetime); '' when there is no date."""
102 text = _text(date_text)[:10]
103 try:
104 day = _dt.date.fromisoformat(text)
105 except ValueError:
106 return ""
107 return f"{day.year:04d}-{day.month:02d}"
108
109
110def month_index(month: str) -> int:
111 year, mon = month.split("-")
112 return int(year) * 12 + int(mon) - 1
113
114
115def month_from_index(index: int) -> str:
116 return f"{index // 12:04d}-{index % 12 + 1:02d}"
117
118
119def month_end(month: str) -> str:
120 index = month_index(month) + 1
121 first_of_next = _dt.date(index // 12, index % 12 + 1, 1)
122 return (first_of_next - _dt.timedelta(days=1)).isoformat()
123
124
125# === pure: one component ====================================================
126
127def component_amounts(cost: int, salvage: int, life_months: int, method: str,
128 rate_bps: int = DEFAULT_DECLINING_RATE_BPS) -> list[int]:
129 """Monthly depreciation of one component, month 1 first, in cents.
130
131 Never books below salvage; the amounts sum to exactly max(0, cost -
132 salvage) for both methods. A method of "none" (land, a work of art) or
133 a component with nothing above salvage depreciates nothing.
134 """
135 cost, salvage, life = int(cost), int(salvage), int(life_months)
136 base = cost - salvage
137 if method == "none" or life <= 0 or base <= 0:
138 return []
139 if method == "straight_line":
140 amounts, before = [], 0
141 for month in range(1, life + 1):
142 through = base * month // life
143 amounts.append(through - before)
144 before = through
145 return amounts
146 if method == "declining":
147 rate = int(rate_bps) if int(rate_bps or 0) > 0 else DEFAULT_DECLINING_RATE_BPS
148 amounts, book_value = [], cost
149 denominator = 10000 * life
150 for month in range(1, life + 1):
151 above_salvage = book_value - salvage
152 if above_salvage <= 0:
153 amounts.append(0)
154 continue
155 if month == life:
156 amount = above_salvage
157 else:
158 # round half up, integers only
159 declining = (book_value * rate * 2 + denominator) // (2 * denominator)
160 remaining = life - month + 1
161 straight = (above_salvage * 2 + remaining) // (2 * remaining)
162 amount = min(max(declining, straight), above_salvage)
163 amounts.append(amount)
164 book_value -= amount
165 return amounts
166 raise ValueError(f"unknown depreciation method {method!r}")
167
168
169# === pure: the asset's book schedule =======================================
170
171def _components(asset: dict, improvements: Iterable[dict], *, life_key: str,
172 salvage_key: str) -> list[dict]:
173 start = month_of(asset.get("placed_in_service_on"))
174 if not start:
175 return []
176 life = _count(asset.get(life_key))
177 components = [{
178 "source": f"fixed_assets/{_text(asset.get('id'))}",
179 "label": "Original cost",
180 "start": start,
181 "cost": _cents(asset.get("cost_cents")),
182 "salvage": _cents(asset.get(salvage_key)),
183 "life": life,
184 }]
185 ordered = sorted(improvements, key=lambda row: (_text(row.get("performed_on")),
186 _text(row.get("id"))))
187 for work in ordered:
188 work_start = month_of(work.get("performed_on"))
189 if not work_start:
190 continue
191 own_life = _count(work.get("life_months"))
192 if own_life <= 0:
193 elapsed = month_index(work_start) - month_index(start)
194 own_life = max(1, life - elapsed)
195 components.append({
196 "source": f"asset_work/{_text(work.get('id'))}",
197 "label": _text(work.get("description")) or "Improvement",
198 "start": work_start,
199 "cost": _cents(work.get("amount_cents")),
200 "salvage": 0,
201 "life": own_life,
202 })
203 return components
204
205
206def book_schedule(asset: dict, improvements: Iterable[dict] = (),
207 disposed_on: str = "") -> dict:
208 """The book depreciation schedule: one row per month with depreciation.
209
210 `improvements`: the asset_work rows (treatment=improvement) to include.
211 `disposed_on`: no depreciation in or after the month of disposal.
212
213 Rows: {month, period_end, amount_cents, accumulated_cents,
214 cost_basis_cents, net_book_value_cents, components: {source: cents}}.
215 """
216 method = _text(asset.get("book_method")) or "straight_line"
217 rate = _count(asset.get("book_declining_rate_bps")) or DEFAULT_DECLINING_RATE_BPS
218 components = _components(asset, improvements, life_key="book_life_months",
219 salvage_key="book_salvage_cents")
220 stop = month_index(month_of(disposed_on)) if month_of(disposed_on) else None
221
222 by_month: dict[int, dict[str, int]] = {}
223 if method != "none":
224 for component in components:
225 amounts = component_amounts(component["cost"], component["salvage"],
226 component["life"], method, rate)
227 first = month_index(component["start"])
228 for offset, amount in enumerate(amounts):
229 index = first + offset
230 if stop is not None and index >= stop:
231 break
232 if amount:
233 bucket = by_month.setdefault(index, {})
234 bucket[component["source"]] = bucket.get(component["source"], 0) + amount
235
236 rows, accumulated = [], 0
237 for index in sorted(by_month):
238 month = month_from_index(index)
239 amount = sum(by_month[index].values())
240 accumulated += amount
241 basis = sum(c["cost"] for c in components if month_index(c["start"]) <= index)
242 rows.append({
243 "month": month,
244 "period_end": month_end(month),
245 "amount_cents": amount,
246 "accumulated_cents": accumulated,
247 "cost_basis_cents": basis,
248 "net_book_value_cents": basis - accumulated,
249 "components": dict(by_month[index]),
250 })
251 return {
252 "method": method,
253 "salvage_cents": _cents(asset.get("book_salvage_cents")),
254 "cost_basis_cents": sum(c["cost"] for c in components),
255 "components": [{k: c[k] for k in ("source", "label", "start", "cost", "salvage", "life")}
256 for c in components],
257 "rows": rows,
258 }
259
260
261def scheduled_through(schedule: dict, month: str) -> int:
262 """The schedule's accumulated depreciation through `month` inclusive."""
263 total = 0
264 for row in schedule["rows"]:
265 if row["month"] > month:
266 break
267 total = row["accumulated_cents"]
268 return total
269
270
271TAX_NOTE = ("Tax depreciation is shown, never booked. A simple method computed from "
272 "the tax columns, or the amounts entered from your accountant's figures. "
273 "MACRS tables, Section 179, bonus depreciation and tax conventions are not "
274 "modelled: ask your accountant. Not tax advice.")
275
276
277def tax_schedule(asset: dict, improvements: Iterable[dict] = (),
278 entries: Iterable[dict] = (), disposed_on: str = "") -> dict:
279 """Tax depreciation by calendar year -- for the accountant's eyes only.
280
281 operator_entered: the asset_tax_entries rows, as typed. straight_line /
282 declining: the same component arithmetic as the books, with the tax
283 life, salvage and rate. none: nothing.
284 """
285 method = _text(asset.get("tax_method")) or "none"
286 if method == "operator_entered":
287 rows = sorted(({"year": _count(e.get("tax_year")),
288 "amount_cents": _cents(e.get("amount_cents")),
289 "basis_note": _text(e.get("basis_note"))} for e in entries),
290 key=lambda row: row["year"])
291 return {"method": method, "rows": rows, "note": TAX_NOTE}
292 if method not in ("straight_line", "declining"):
293 return {"method": method, "rows": [], "note": TAX_NOTE}
294 shadow = {**asset, "book_method": method,
295 "book_life_months": asset.get("tax_life_months"),
296 "book_salvage_cents": asset.get("tax_salvage_cents"),
297 "book_declining_rate_bps": asset.get("tax_declining_rate_bps")}
298 # An improvement's own life is a BOOK life; under tax it takes the
299 # asset's remaining tax life (the accountant decides otherwise).
300 tax_improvements = [{**w, "life_months": ""} for w in improvements]
301 monthly = book_schedule(shadow, tax_improvements, disposed_on)
302 by_year: dict[int, int] = {}
303 for row in monthly["rows"]:
304 year = int(row["month"][:4])
305 by_year[year] = by_year.get(year, 0) + row["amount_cents"]
306 return {"method": method,
307 "rows": [{"year": year, "amount_cents": amount, "basis_note": "simple method"}
308 for year, amount in sorted(by_year.items())],
309 "note": TAX_NOTE}
310
311
312# === pure: disposal ==========================================================
313
314def disposal_result(cost_basis_cents: int, accumulated_cents: int,
315 proceeds_cents: int = 0, insurance_cents: int = 0) -> dict:
316 """Net book value and gain (positive) or loss (negative) on disposal.
317
318 gain_loss = proceeds + insurance recovery - (cost basis - accumulated
319 depreciation). Integer cents in, integer cents out.
320 """
321 nbv = int(cost_basis_cents) - int(accumulated_cents)
322 gain_loss = int(proceeds_cents) + int(insurance_cents) - nbv
323 return {"cost_basis_cents": int(cost_basis_cents),
324 "accumulated_depreciation_cents": int(accumulated_cents),
325 "net_book_value_cents": nbv,
326 "proceeds_cents": int(proceeds_cents),
327 "insurance_recovery_cents": int(insurance_cents),
328 "gain_loss_cents": gain_loss}
329
330
331def disposal_lines(result: dict, accounts: dict) -> list[dict]:
332 """The disposal journal's lines. Balanced by construction:
333
334 DR accumulated depreciation A
335 DR proceeds P (when P > 0)
336 DR insurance receivable I (when I > 0)
337 DR loss on disposal -G (when a loss)
338 CR asset cost C
339 CR gain on disposal G (when a gain)
340
341 A + P + I + loss = C + gain, because G = P + I - (C - A).
342 `accounts` keys: cost, accumulated, proceeds, insurance, gain, loss.
343 """
344 lines = []
345
346 def debit(key, amount, memo):
347 if amount > 0:
348 lines.append({"account_id": accounts[key], "debit_cents": amount,
349 "credit_cents": 0, "memo": memo})
350
351 def credit(key, amount, memo):
352 if amount > 0:
353 lines.append({"account_id": accounts[key], "debit_cents": 0,
354 "credit_cents": amount, "memo": memo})
355
356 gain_loss = result["gain_loss_cents"]
357 debit("accumulated", result["accumulated_depreciation_cents"], "accumulated depreciation removed")
358 debit("proceeds", result["proceeds_cents"], "proceeds")
359 debit("insurance", result["insurance_recovery_cents"], "insurance recovery")
360 debit("loss", -gain_loss if gain_loss < 0 else 0, "loss on disposal")
361 credit("cost", result["cost_basis_cents"], "cost basis removed")
362 credit("gain", gain_loss if gain_loss > 0 else 0, "gain on disposal")
363 return lines
364
365
366def accounts_needed_for_disposal(result: dict) -> list[str]:
367 needed = ["cost"]
368 if result["accumulated_depreciation_cents"] > 0:
369 needed.append("accumulated")
370 if result["proceeds_cents"] > 0:
371 needed.append("proceeds")
372 if result["insurance_recovery_cents"] > 0:
373 needed.append("insurance")
374 if result["gain_loss_cents"] > 0:
375 needed.append("gain")
376 if result["gain_loss_cents"] < 0:
377 needed.append("loss")
378 return needed
379
380
381# === I/O: reading ============================================================
382
383class BooksUnavailable(Exception):
384 """Something the pass must read could not be read. Nothing is booked."""
385
386
387def _rows(base, collection, *, optional=False):
388 try:
389 return object_records.read_collection_records(collection, base_dir=base)
390 except object_collections.CollectionNotFoundError:
391 if optional:
392 return []
393 raise BooksUnavailable(f"{collection} is not installed")
394 except Exception as exc:
395 raise BooksUnavailable(f"{collection} could not be read: {str(exc)[:120]}") from exc
396
397
398def read_settings(base) -> dict[str, str]:
399 """Every app_settings key with a value. Not installed is "nothing
400 configured"; unreadable raises -- a per-kind account override that
401 could not be read must not quietly fall back to the general one."""
402 settings = {}
403 for row in _rows(base, "app_settings", optional=True):
404 key, value = _text(row.get("key")), _text(row.get("value"))
405 if key and value and key not in settings:
406 settings[key] = value
407 return settings
408
409
410def _asset_accounts(asset: dict, settings: dict) -> dict[str, str]:
411 return {
412 "cost": _text(asset.get("asset_account_id")) or settings.get("assets.journal.cost_account", ""),
413 "accumulated": (_text(asset.get("accumulated_account_id"))
414 or settings.get("assets.journal.accumulated_account", "")),
415 "expense": (_text(asset.get("expense_account_id"))
416 or settings.get("assets.journal.depreciation_account", "")),
417 "funding": (_text(asset.get("funding_account_id"))
418 or settings.get("assets.journal.funding_account", "")),
419 }
420
421
422class Books:
423 """One read of the books for a pass: journals by marker, lines by journal,
424 and which journals were reversed (action_reverse_journal's marker)."""
425
426 def __init__(self, base):
427 self.base = base
428 self.refresh()
429
430 def refresh(self):
431 journals = _rows(self.base, "fin_journals")
432 lines = _rows(self.base, "fin_journal_lines")
433 self.by_marker = {}
434 self.reversed = set()
435 for journal in journals:
436 marker = _text(journal.get("generated_from"))
437 if marker:
438 self.by_marker[marker] = journal
439 if marker.startswith("reversal:"):
440 self.reversed.add(marker[len("reversal:"):])
441 self.lines = {}
442 for line in lines:
443 self.lines.setdefault(_text(line.get("journal_id")), []).append(line)
444
445 def has(self, marker: str) -> bool:
446 return marker in self.by_marker
447
448 def live_amount(self, marker: str) -> int:
449 """The debit total of the journal under `marker`, 0 when there is none
450 or it was reversed. A draft counts: it is waiting to be posted, and
451 booking the same month again would post it twice."""
452 journal = self.by_marker.get(marker)
453 if not journal or _text(journal.get("id")) in self.reversed:
454 return 0
455 return sum(_cents(line.get("debit_cents")) for line in self.lines.get(_text(journal.get("id")), []))
456
457 def booked_depreciation(self, asset_id: str) -> dict[str, int]:
458 prefix = f"fixed_assets/{asset_id}/depreciation/"
459 return {marker[len(prefix):]: self.live_amount(marker)
460 for marker in self.by_marker if marker.startswith(prefix)}
461
462
463def _compose(base, books, report, *, marker, date, description, lines, owner_id,
464 entity_id, actor, kind="standard"):
465 result = object_finance.compose_posted_journal(
466 base, generated_from=marker, date=date, description=description,
467 lines=lines, owner_id=owner_id, entity_id=entity_id, kind=kind, actor=actor)
468 entry = {"marker": marker, **{k: v for k, v in result.items() if k != "ok"}}
469 if not result.get("ok"):
470 report["errors"].append(entry)
471 return None
472 if result.get("journal_id") and not result.get("skipped"):
473 report["posted"].append(entry)
474 elif result.get("skipped"):
475 report["skipped"].append(entry)
476 books.refresh()
477 return result
478
479
480def _fresh(collection, row, base):
481 """The row as stored now (one record read), so a compare-and-set is made
482 against what is on file rather than a collection-wide read from earlier
483 in the pass -- whose rev differs as soon as any write to the collection
484 adds a column, which is not a change anybody made to this row."""
485 return object_records.get_collection_record(collection, row["id"], base_dir=base)
486
487
488def _stamp(collection, row, changes, base, actor, *, decided_from=True):
489 """A trusted stamp. With `decided_from` (the default) it is a
490 compare-and-set against `row`, the row the decision was made from: if a
491 person changed it since, nothing is written and the next pass decides
492 again from what they wrote. A read-only stamp (a journal id) is no
493 decision and is written plainly: nobody but the server can change one."""
494 try:
495 return object_records.update_collection_record(
496 collection, row["id"], changes, base_dir=base, actor=actor,
497 preserve_read_only=True,
498 expected_rev=object_records.compute_record_rev(row) if decided_from else None)
499 except object_records.VersionConflictError:
500 return None
501
502
503def _new_report(**extra):
504 return {"posted": [], "skipped": [], "waiting": [], "errors": [], **extra}
505
506
507# === I/O: one asset ==========================================================
508
509def books_pass_for_asset(base, asset_id: str, *, as_of: str = "",
510 actor: str = ACTOR) -> dict:
511 """Bring the books up to date with one asset's register entries.
512
513 In order, each step only when the one before it is on the books:
514 capitalization, then improvements and repairs, then monthly
515 depreciation through the last month that has ended on or before
516 `as_of` (and before any disposal month), then the disposal. Every
517 journal carries a generated_from marker, so running this again --
518 tomorrow, twice at once, from a replayed event -- composes nothing
519 that is already there.
520 """
521 as_of = _text(as_of)[:10] or _dt.date.today().isoformat()
522 report = _new_report(asset_id=asset_id, as_of=as_of)
523 try:
524 settings = read_settings(base)
525 asset = object_records.get_collection_record("fixed_assets", asset_id, base_dir=base)
526 books = Books(base)
527 work_rows = [w for w in _rows(base, "asset_work") if _text(w.get("asset_id")) == asset_id]
528 disposals = [d for d in _rows(base, "asset_disposals") if _text(d.get("asset_id")) == asset_id]
529 except object_records.RecordNotFoundError:
530 report["errors"].append({"error": f"no asset {asset_id}"})
531 return report
532 except BooksUnavailable as exc:
533 report["errors"].append({"error": str(exc)})
534 return report
535
536 status = _text(asset.get("status"))
537 if status not in ("in_service", "disposed"):
538 report["waiting"].append({"step": "in_service", "reason": "not placed in service yet"})
539 return report
540 owner, entity = _text(asset.get("owner_id")), _text(asset.get("entity_id"))
541 accounts = _asset_accounts(asset, settings)
542 name = _text(asset.get("name")) or asset_id
543
544 # 1. capitalization ------------------------------------------------------
545 if _text(asset.get("capitalization")) != "booked_elsewhere":
546 marker = f"fixed_assets/{asset_id}/capitalization"
547 if not books.has(marker):
548 missing = [k for k in ("cost", "funding") if not accounts[k]]
549 if missing:
550 report["waiting"].append({"step": "capitalization", "reason": "accounts unconfigured",
551 "needs": _needs(missing)})
552 return report
553 if _compose(base, books, report, marker=marker,
554 date=_text(asset.get("placed_in_service_on")),
555 description=f"Fixed asset placed in service: {name}",
556 lines=[{"account_id": accounts["cost"], "debit_cents": _cents(asset.get("cost_cents")),
557 "credit_cents": 0, "memo": f"cost of {name}"},
558 {"account_id": accounts["funding"], "debit_cents": 0,
559 "credit_cents": _cents(asset.get("cost_cents")), "memo": "paid for"}],
560 owner_id=owner, entity_id=entity, actor=actor) is None:
561 return report
562 if _text(books.by_marker.get(marker, {}).get("id")) and not _text(asset.get("capitalization_journal_id")):
563 stamped = _stamp("fixed_assets", asset,
564 {"capitalization_journal_id": books.by_marker[marker]["id"]}, base, actor,
565 decided_from=False)
566 asset = stamped or asset
567
568 # 2. improvements and repairs --------------------------------------------
569 blocked = False
570 for work in sorted(work_rows, key=lambda w: (_text(w.get("performed_on")), _text(w.get("id")))):
571 if not _post_work(base, books, report, asset, accounts, settings, work, actor):
572 blocked = True
573 break
574 if blocked:
575 return report
576 work_rows = [w for w in _rows(base, "asset_work") if _text(w.get("asset_id")) == asset_id]
577 improvements = [w for w in work_rows if _text(w.get("treatment")) == "improvement"
578 and _text(w.get("status")) == "posted"]
579
580 # 3. depreciation -----------------------------------------------------------
581 disposal = disposals[0] if disposals else None
582 disposed_on = _text(disposal.get("disposed_on")) if disposal else ""
583 schedule = book_schedule(asset, improvements, disposed_on)
584 if schedule["rows"]:
585 missing = [k for k in ("expense", "accumulated") if not accounts[k]]
586 if missing:
587 report["waiting"].append({"step": "depreciation", "reason": "accounts unconfigured",
588 "needs": _needs(missing)})
589 return report
590 booked = books.booked_depreciation(asset_id)
591 running = 0
592 for row in schedule["rows"]:
593 if row["period_end"] > as_of:
594 break
595 month = row["month"]
596 running += booked.get(month, 0)
597 marker = f"fixed_assets/{asset_id}/depreciation/{month}"
598 if books.has(marker):
599 continue
600 amount = row["accumulated_cents"] - running
601 if amount < 0:
602 report["waiting"].append({"step": "depreciation", "month": month,
603 "reason": (f"the books hold {-amount} cents more depreciation "
604 "than the schedule: ask your accountant")})
605 continue
606 if amount == 0:
607 continue
608 result = _compose(base, books, report, marker=marker, date=row["period_end"],
609 description=f"Depreciation {month}: {name}",
610 lines=[{"account_id": accounts["expense"], "debit_cents": amount,
611 "credit_cents": 0, "memo": f"{name} {month}"},
612 {"account_id": accounts["accumulated"], "debit_cents": 0,
613 "credit_cents": amount, "memo": f"{name} {month}"}],
614 owner_id=owner, entity_id=entity, actor=actor, kind="adjusting")
615 if result is None:
616 return report
617 running += amount
618
619 # 4. disposal ---------------------------------------------------------------
620 if disposal:
621 _post_disposal(base, books, report, asset, accounts, settings, disposal,
622 schedule, as_of, actor)
623 return report
624
625
626def _needs(keys):
627 names = {"cost": "assets.journal.cost_account (or the asset's asset_account_id)",
628 "accumulated": "assets.journal.accumulated_account (or the asset's accumulated_account_id)",
629 "expense": "assets.journal.depreciation_account (or the asset's expense_account_id)",
630 "funding": "assets.journal.funding_account (or the asset's funding_account_id)",
631 "proceeds": "assets.journal.proceeds_account (or the disposal's proceeds_account_id)",
632 "insurance": "assets.journal.insurance_receivable_account (or the disposal's insurance_account_id)",
633 "gain": "assets.journal.gain_account",
634 "loss": "assets.journal.loss_account (or assets.journal.<kind>_loss_account)",
635 "repair": "assets.journal.repair_account (or the work's expense_account_id)",
636 "paid_from": "assets.journal.funding_account (or the work's paid_from_account_id)"}
637 return [names.get(k, k) for k in keys]
638
639
640def _post_work(base, books, report, asset, accounts, settings, work, actor) -> bool:
641 """Book one improvement or repair. False when the pass must stop here
642 (an earlier entry not on the books would make every later number wrong)."""
643 marker = f"asset_work/{work['id']}"
644 work = _fresh("asset_work", work, base)
645 treatment = _text(work.get("treatment"))
646 elsewhere = _text(work.get("booking")) == "booked_elsewhere"
647 posted = _text(work.get("status")) == "posted"
648 if posted and (elsewhere or books.has(marker)):
649 if books.has(marker) and not _text(work.get("journal_id")):
650 _stamp("asset_work", work, {"journal_id": books.by_marker[marker]["id"]}, base, actor,
651 decided_from=False)
652 return True
653
654 debit_key = "cost" if treatment == "improvement" else "repair"
655 debit = (accounts["cost"] if treatment == "improvement"
656 else _text(work.get("expense_account_id")) or settings.get("assets.journal.repair_account", ""))
657 credit = _text(work.get("paid_from_account_id")) or settings.get("assets.journal.funding_account", "")
658 if not elsewhere:
659 missing = [k for k, v in ((debit_key, debit), ("paid_from", credit)) if not v]
660 if missing:
661 report["waiting"].append({"step": "asset_work", "work_id": work["id"],
662 "reason": "accounts unconfigured", "needs": _needs(missing)})
663 return False
664
665 if not posted:
666 stamped = _stamp("asset_work", work, {
667 "status": "posted",
668 "posted_at": _dt.datetime.now(_dt.timezone.utc).isoformat()}, base, actor)
669 if stamped is None:
670 report["waiting"].append({"step": "asset_work", "work_id": work["id"],
671 "reason": "changed while the pass read it; the next pass decides"})
672 return False
673 work = stamped
674 if elsewhere:
675 report["skipped"].append({"marker": marker, "skipped": "booked elsewhere (recorded only)"})
676 return True
677
678 amount = _cents(work.get("amount_cents"))
679 what = "Improvement" if treatment == "improvement" else "Repair"
680 name = _text(asset.get("name")) or _text(asset.get("id"))
681 result = _compose(base, books, report, marker=marker, date=_text(work.get("performed_on")),
682 description=f"{what} to {name}: {_text(work.get('description'))}"[:300],
683 lines=[{"account_id": debit, "debit_cents": amount, "credit_cents": 0,
684 "memo": f"{what.lower()} ({_text(work.get('basis'))}): {_text(work.get('reason'))}"[:200]},
685 {"account_id": credit, "debit_cents": 0, "credit_cents": amount,
686 "memo": "paid for"}],
687 owner_id=_text(asset.get("owner_id")), entity_id=_text(asset.get("entity_id")),
688 actor=actor)
689 if result is None:
690 return False
691 if result.get("journal_id"):
692 _stamp("asset_work", work, {"journal_id": result["journal_id"]}, base, actor,
693 decided_from=False)
694 return True
695
696
697def _approved_loss_event(base, loss_event_id):
698 if not loss_event_id:
699 return None
700 try:
701 event = object_records.get_collection_record("loss_events", loss_event_id, base_dir=base)
702 except (object_records.RecordNotFoundError, object_collections.CollectionNotFoundError):
703 return None
704 return event if _text(event.get("status")) == "approved" else None
705
706
707def _post_disposal(base, books, report, asset, accounts, settings, disposal, schedule,
708 as_of, actor):
709 asset_id = _text(asset.get("id"))
710 marker = f"asset_disposals/{disposal['id']}"
711 disposal = _fresh("asset_disposals", disposal, base)
712 disposed_on = _text(disposal.get("disposed_on"))
713 kind = _text(disposal.get("kind"))
714 if disposed_on > as_of:
715 report["waiting"].append({"step": "disposal", "reason": f"dated {disposed_on}, after {as_of}"})
716 return
717
718 if _text(disposal.get("status")) != "posted":
719 if kind in DISPOSALS_NEEDING_APPROVAL and not _approved_loss_event(
720 base, _text(disposal.get("loss_event_id"))):
721 report["waiting"].append({
722 "step": "disposal", "reason": (f"a {kind} is booked once its loss event is approved: "
723 "set loss_event_id to an approved loss event")})
724 return
725 # Every month before the disposal month must be on the books first,
726 # or the net book value is a guess.
727 before = month_from_index(month_index(month_of(disposed_on)) - 1)
728 wanted = scheduled_through(schedule, before)
729 held = sum(books.booked_depreciation(asset_id).values())
730 if held != wanted:
731 report["waiting"].append({"step": "disposal", "reason": (
732 f"depreciation through {before} is not all on the books "
733 f"({held} of {wanted} cents)")})
734 return
735 improvements = sum(_cents(w.get("amount_cents")) for w in _rows(base, "asset_work")
736 if _text(w.get("asset_id")) == asset_id
737 and _text(w.get("treatment")) == "improvement"
738 and _text(w.get("status")) == "posted")
739 result = disposal_result(_cents(asset.get("cost_cents")) + improvements, held,
740 _cents(disposal.get("proceeds_cents")),
741 _cents(disposal.get("insurance_recovery_cents")))
742 disposal_accounts = _disposal_accounts(accounts, settings, disposal, kind)
743 missing = [k for k in accounts_needed_for_disposal(result) if not disposal_accounts[k]]
744 if missing:
745 report["waiting"].append({"step": "disposal", "reason": "accounts unconfigured",
746 "needs": _needs(missing)})
747 return
748 stamped = _stamp("asset_disposals", disposal, {
749 "status": "posted",
750 "cost_basis_cents": str(result["cost_basis_cents"]),
751 "accumulated_depreciation_cents": str(result["accumulated_depreciation_cents"]),
752 "net_book_value_cents": str(result["net_book_value_cents"]),
753 "gain_loss_cents": str(result["gain_loss_cents"]),
754 "posted_at": _dt.datetime.now(_dt.timezone.utc).isoformat(),
755 }, base, actor)
756 if stamped is None:
757 report["waiting"].append({"step": "disposal",
758 "reason": "changed while the pass read it; the next pass decides"})
759 return
760 disposal = stamped
761
762 # Posted: the stamps are the numbers (doctrine #1); compose from them.
763 result = disposal_result(_cents(disposal.get("cost_basis_cents")),
764 _cents(disposal.get("accumulated_depreciation_cents")),
765 _cents(disposal.get("proceeds_cents")),
766 _cents(disposal.get("insurance_recovery_cents")))
767 if not books.has(marker):
768 disposal_accounts = _disposal_accounts(accounts, settings, disposal, kind)
769 missing = [k for k in accounts_needed_for_disposal(result) if not disposal_accounts[k]]
770 if missing:
771 report["waiting"].append({"step": "disposal", "reason": "accounts unconfigured",
772 "needs": _needs(missing)})
773 return
774 name = _text(asset.get("name")) or asset_id
775 composed = _compose(base, books, report, marker=marker, date=disposed_on,
776 description=f"Disposal ({kind}) of {name}",
777 lines=disposal_lines(result, disposal_accounts),
778 owner_id=_text(asset.get("owner_id")),
779 entity_id=_text(asset.get("entity_id")), actor=actor)
780 if composed is None:
781 return
782 journal = books.by_marker.get(marker) or {}
783 if journal.get("id") and not _text(disposal.get("journal_id")):
784 _stamp("asset_disposals", disposal, {"journal_id": journal["id"]}, base, actor,
785 decided_from=False)
786 report["disposal"] = result
787 if _text(asset.get("status")) != "disposed":
788 try:
789 object_records.update_collection_record(
790 "fixed_assets", asset_id, {"status": "disposed", "disposed_on": disposed_on},
791 base_dir=base, actor=actor, preserve_read_only=True)
792 except Exception as exc:
793 report["errors"].append({"step": "disposal", "error": f"asset not marked disposed: {str(exc)[:160]}"})
794
795
796def _disposal_accounts(accounts, settings, disposal, kind):
797 return {
798 "cost": accounts["cost"],
799 "accumulated": accounts["accumulated"],
800 "proceeds": (_text(disposal.get("proceeds_account_id"))
801 or settings.get("assets.journal.proceeds_account", "")),
802 "insurance": (_text(disposal.get("insurance_account_id"))
803 or settings.get("assets.journal.insurance_receivable_account", "")),
804 "gain": settings.get("assets.journal.gain_account", ""),
805 "loss": (settings.get(f"assets.journal.{kind}_loss_account", "")
806 or settings.get("assets.journal.loss_account", "")),
807 }
808
809
810# === I/O: one loss event =====================================================
811
812def books_pass_for_loss(base, loss_event_id: str, *, actor: str = ACTOR) -> dict:
813 """What an APPROVED loss event books itself, which is only what nothing
814 else books:
815
816 - a write-off, when no stock move, asset or hand journal carries the
817 loss and the event names the account it came out of
818 (write_off_account_id): DR the loss account / CR that account, for
819 final_amount_cents, marker loss_events/{id};
820 - an insurance recovery, once insurance_status is paid: DR insurance
821 receivable / CR the recovery account, marker loss_events/{id}/recovery
822 -- unless a posted disposal already carried a recovery for this event
823 (then the disposal's journal holds it, and booking it here too would
824 count the cheque twice).
825
826 An inventory loss is booked by its stock move (system_stock_books or
827 action_apply_count); an equipment loss by its disposal. The event is the
828 evidence and the approval those numbers trace back to.
829 """
830 report = _new_report(loss_event_id=loss_event_id)
831 try:
832 settings = read_settings(base)
833 event = object_records.get_collection_record("loss_events", loss_event_id, base_dir=base)
834 books = Books(base)
835 disposals = [d for d in _rows(base, "asset_disposals", optional=True)
836 if _text(d.get("loss_event_id")) == loss_event_id]
837 except object_records.RecordNotFoundError:
838 report["errors"].append({"error": f"no loss event {loss_event_id}"})
839 return report
840 except BooksUnavailable as exc:
841 report["errors"].append({"error": str(exc)})
842 return report
843 if _text(event.get("status")) != "approved":
844 report["waiting"].append({"step": "approval", "reason": "not approved"})
845 return report
846 owner, entity = _text(event.get("owner_id")), _text(event.get("entity_id"))
847 kind = _text(event.get("kind"))
848 loss_account = (_text(event.get("loss_account_id"))
849 or settings.get(f"losses.journal.{kind}_account", "")
850 or settings.get("losses.journal.loss_account", ""))
851
852 # write-off
853 carried_by = ("stock move" if _text(event.get("stock_move_id"))
854 else "asset disposal" if _text(event.get("asset_id"))
855 else "hand journal" if _text(event.get("journal_id")) else "")
856 amount = _cents(event.get("final_amount_cents"))
857 marker = f"loss_events/{loss_event_id}"
858 if carried_by:
859 report["skipped"].append({"marker": marker, "skipped": f"the loss is booked by its {carried_by}"})
860 elif not _text(event.get("write_off_account_id")):
861 report["skipped"].append({"marker": marker,
862 "skipped": "no write_off_account_id: nothing names where the loss came from"})
863 elif amount > 0:
864 if not books.has(marker):
865 if not loss_account:
866 report["waiting"].append({"step": "write_off", "reason": "accounts unconfigured",
867 "needs": ["losses.journal.loss_account (or the event's loss_account_id)"]})
868 return report
869 if _compose(base, books, report, marker=marker,
870 date=_text(event.get("discovered_on")) or _text(event.get("occurred_on")),
871 description=f"Loss ({kind}): {_text(event.get('what'))}"[:300],
872 lines=[{"account_id": loss_account, "debit_cents": amount, "credit_cents": 0,
873 "memo": f"loss event {loss_event_id}"},
874 {"account_id": _text(event.get("write_off_account_id")), "debit_cents": 0,
875 "credit_cents": amount, "memo": "written off"}],
876 owner_id=owner, entity_id=entity, actor=actor) is None:
877 return report
878 journal = books.by_marker.get(marker) or {}
879 if journal.get("id") and not _text(event.get("writeoff_journal_id")):
880 event = _stamp("loss_events", event, {"writeoff_journal_id": journal["id"]}, base, actor,
881 decided_from=False) or event
882
883 # insurance recovery
884 recovery = _cents(event.get("insurance_recovery_cents"))
885 marker = f"loss_events/{loss_event_id}/recovery"
886 if _text(event.get("insurance_status")) == "paid" and recovery > 0:
887 on_disposal = [d for d in disposals if _text(d.get("status")) == "posted"
888 and _cents(d.get("insurance_recovery_cents")) > 0]
889 if on_disposal:
890 report["skipped"].append({"marker": marker, "skipped": "the recovery is on the disposal's journal"})
891 elif not books.has(marker):
892 receivable = settings.get("assets.journal.insurance_receivable_account", "")
893 credit = settings.get("losses.journal.recovery_account", "")
894 missing = [k for k, v in (("assets.journal.insurance_receivable_account", receivable),
895 ("losses.journal.recovery_account", credit)) if not v]
896 if missing:
897 report["waiting"].append({"step": "recovery", "reason": "accounts unconfigured",
898 "needs": missing})
899 return report
900 if _compose(base, books, report, marker=marker,
901 date=_text(event.get("recovered_on")) or _text(event.get("occurred_on")),
902 description=f"Insurance recovery ({kind}): {_text(event.get('what'))}"[:300],
903 lines=[{"account_id": receivable, "debit_cents": recovery, "credit_cents": 0,
904 "memo": _text(event.get("insurance_claim_ref")) or "insurance"},
905 {"account_id": credit, "debit_cents": 0, "credit_cents": recovery,
906 "memo": f"loss event {loss_event_id}"}],
907 owner_id=owner, entity_id=entity, actor=actor) is None:
908 return report
909 journal = books.by_marker.get(marker) or {}
910 if journal.get("id") and not _text(event.get("recovery_journal_id")):
911 _stamp("loss_events", event, {"recovery_journal_id": journal["id"]}, base, actor,
912 decided_from=False)
913 return report
914
915
916# === I/O: the whole register =================================================
917
918def run_register(base, *, as_of: str = "", asset_ids: Iterable[str] | None = None,
919 loss_event_ids: Iterable[str] | None = None, actor: str = ACTOR) -> dict:
920 """The pass over every asset (or the ones named) and every approved loss
921 event (or the ones named). One asset's trouble never stops another's."""
922 as_of = _text(as_of)[:10] or _dt.date.today().isoformat()
923 summary = {"as_of": as_of, "assets": [], "loss_events": [], "errors": []}
924 try:
925 if asset_ids is None:
926 asset_ids = [_text(a.get("id")) for a in _rows(base, "fixed_assets")
927 if _text(a.get("status")) in ("in_service", "disposed")]
928 if loss_event_ids is None:
929 loss_event_ids = [_text(e.get("id")) for e in _rows(base, "loss_events", optional=True)
930 if _text(e.get("status")) == "approved"]
931 except BooksUnavailable as exc:
932 summary["errors"].append(str(exc))
933 return summary
934 for asset_id in asset_ids:
935 try:
936 summary["assets"].append(books_pass_for_asset(base, asset_id, as_of=as_of, actor=actor))
937 except Exception as exc: # one asset never stops the next
938 summary["errors"].append(f"{asset_id}: {str(exc)[:200]}")
939 for event_id in loss_event_ids:
940 try:
941 summary["loss_events"].append(books_pass_for_loss(base, event_id, actor=actor))
942 except Exception as exc:
943 summary["errors"].append(f"{event_id}: {str(exc)[:200]}")
944 summary["posted"] = sum(len(r["posted"]) for r in summary["assets"] + summary["loss_events"])
945 return summary
946
947
948def asset_overview(base, asset: dict) -> dict:
949 """Everything an asset's schedule page shows, as data: the book schedule
950 (improvements recorded but not yet booked included, so a person sees
951 what the next pass will do) with what each month already has on the
952 books beside it, the tax schedule, the work, the disposal."""
953 asset_id = _text(asset.get("id"))
954
955 def rows(collection):
956 return [r for r in _rows(base, collection, optional=True)
957 if _text(r.get("asset_id")) == asset_id]
958
959 work = sorted(rows("asset_work"), key=lambda w: (_text(w.get("performed_on")), _text(w.get("id"))))
960 disposals = rows("asset_disposals")
961 disposal = disposals[0] if disposals else None
962 disposed_on = _text(disposal.get("disposed_on")) if disposal else ""
963 improvements = [w for w in work if _text(w.get("treatment")) == "improvement"]
964 schedule = book_schedule(asset, improvements, disposed_on)
965 booked = Books(base).booked_depreciation(asset_id)
966 for row in schedule["rows"]:
967 row["booked_cents"] = booked.get(row["month"], 0)
968 return {
969 "asset": asset,
970 "book": schedule,
971 "booked_total_cents": sum(booked.values()),
972 "tax": tax_schedule(asset, improvements, rows("asset_tax_entries"), disposed_on),
973 "work": work,
974 "disposal": disposal,
975 }