askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
fin_recurring_runner.py · 4.3 KB · 108 lines
| 1 | """Run due fin_recurring templates: the dormant half of adjusting entries. |
| 2 | |
| 3 | fin_recurring shipped schema-only (template_lines, frequency, next_run, |
| 4 | auto_post) -- the daemon never processed it. This object is the engine: |
| 5 | POST runs one pass over due templates (is_active, next_run <= today), |
| 6 | composes a journal (kind=adjusting) from template_lines, posts it when |
| 7 | auto_post says so AND it balances (an unbalanced template stays draft with a |
| 8 | note -- a broken template must never crash the pass), then advances |
| 9 | next_run by frequency and stamps last_run. |
| 10 | |
| 11 | Time-driven work belongs to the daemon (docs/logic-decisions.md #2): wire it |
| 12 | via the existing scheduler contract -- a scheduler task with |
| 13 | object_id="system_fin_recurring_runner", method="POST" on a daily cron. Also |
| 14 | callable manually (an admin "run now"). Idempotent per period: |
| 15 | generated_from="fin_recurring/{id}:{next_run}". |
| 16 | """ |
| 17 | |
| 18 | import json |
| 19 | import os |
| 20 | from datetime import date, timedelta |
| 21 | |
| 22 | import object_finance |
| 23 | import object_records |
| 24 | |
| 25 | ACTOR = "fin_recurring_runner" |
| 26 | |
| 27 | |
| 28 | def _base_dir(): |
| 29 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 30 | |
| 31 | |
| 32 | def _advance(day_iso, frequency): |
| 33 | try: |
| 34 | y, m, d = (int(x) for x in day_iso.split("-")) |
| 35 | current = date(y, m, d) |
| 36 | except (ValueError, AttributeError): |
| 37 | return "" |
| 38 | freq = (frequency or "monthly").strip().lower() |
| 39 | if freq == "weekly": |
| 40 | return (current + timedelta(days=7)).isoformat() |
| 41 | if freq == "yearly": |
| 42 | return current.replace(year=current.year + 1).isoformat() |
| 43 | # monthly (default): same day next month, clamped |
| 44 | month = current.month + 1 |
| 45 | year = current.year + (1 if month > 12 else 0) |
| 46 | month = 1 if month > 12 else month |
| 47 | for day in (current.day, 30, 29, 28): |
| 48 | try: |
| 49 | return date(year, month, day).isoformat() |
| 50 | except ValueError: |
| 51 | continue |
| 52 | return "" |
| 53 | |
| 54 | |
| 55 | def POST(request): |
| 56 | base = _base_dir() |
| 57 | today = str(request.get("today") or date.today().isoformat()) |
| 58 | try: |
| 59 | templates = object_records.read_collection_records("fin_recurring", base_dir=base) |
| 60 | except Exception: |
| 61 | return {"ok": True, "skipped": "fin_recurring not installed"} |
| 62 | |
| 63 | ran, results = 0, [] |
| 64 | for tpl in templates: |
| 65 | if (tpl.get("is_active") or "").lower() not in ("true", "1", "yes"): |
| 66 | continue |
| 67 | next_run = (tpl.get("next_run") or "").strip() |
| 68 | if not next_run or next_run > today: |
| 69 | continue |
| 70 | marker = f"fin_recurring/{tpl['id']}:{next_run}" |
| 71 | already = object_finance.find_journal_by_provenance(base, marker) is not None |
| 72 | if not already: |
| 73 | try: |
| 74 | lines_spec = json.loads(tpl.get("template_lines") or "[]") |
| 75 | except (ValueError, TypeError): |
| 76 | results.append({"template": tpl["id"], "error": "bad template_lines JSON"}) |
| 77 | continue |
| 78 | auto_post = (tpl.get("auto_post") or "").lower() in ("true", "1", "yes") |
| 79 | composed = object_finance.compose_posted_journal( |
| 80 | base, |
| 81 | generated_from=marker, |
| 82 | date=next_run, |
| 83 | description=f"{tpl.get('name') or 'Recurring entry'} ({next_run})", |
| 84 | lines=lines_spec, |
| 85 | owner_id=tpl.get("owner_id", ""), |
| 86 | entity_id=tpl.get("entity_id", ""), |
| 87 | kind="adjusting", |
| 88 | actor=ACTOR, |
| 89 | post=auto_post, |
| 90 | ) |
| 91 | if not composed.get("ok"): |
| 92 | results.append({"template": tpl["id"], "error": composed.get("error", "compose failed")}) |
| 93 | continue |
| 94 | result = {"template": tpl["id"], |
| 95 | "journal": composed.get("journal_id", ""), |
| 96 | "posted": bool(composed.get("posted"))} |
| 97 | if "did not balance" in (composed.get("note") or ""): |
| 98 | result["note"] = "unbalanced: left draft" |
| 99 | results.append(result) |
| 100 | ran += 1 |
| 101 | # Advance the schedule even if this period was already composed |
| 102 | # (a crashed earlier pass may have composed but not advanced). |
| 103 | object_records.update_collection_record( |
| 104 | "fin_recurring", tpl["id"], |
| 105 | {"next_run": _advance(next_run, tpl.get("frequency")), "last_run": next_run}, |
| 106 | base_dir=base, actor=ACTOR, |
| 107 | ) |
| 108 | return {"ok": True, "ran": ran, "results": results, "today": today} |