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.
fin_recurring_runner.py · 6.6 KB · 157 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 _add_months(current, months): |
| 33 | """Same day `months` later, clamped to the end of a shorter month (the |
| 34 | 31st of a 30-day month runs on the 30th; Feb 29 in a common year runs on |
| 35 | the 28th) -- the same clamp billing_runner._advance uses, so a schedule |
| 36 | never raises on a day the target month lacks.""" |
| 37 | index = current.month - 1 + months |
| 38 | year, month = current.year + index // 12, index % 12 + 1 |
| 39 | for day in (current.day, 30, 29, 28): |
| 40 | try: |
| 41 | return date(year, month, day) |
| 42 | except ValueError: |
| 43 | continue |
| 44 | return None |
| 45 | |
| 46 | |
| 47 | def _advance(day_iso, frequency): |
| 48 | """next_run after `day_iso` for one of the schema's frequency enum values. |
| 49 | |
| 50 | Only weekly/monthly/yearly used to be handled; `daily` and `quarterly` |
| 51 | fell through to the monthly default (a daily accrual booked once a |
| 52 | month, a quarterly entry three times a quarter), and `yearly` from Feb |
| 53 | 29 raised ValueError. An unknown frequency answers "" so the caller |
| 54 | refuses to advance rather than guessing a period.""" |
| 55 | try: |
| 56 | y, m, d = (int(x) for x in day_iso.split("-")) |
| 57 | current = date(y, m, d) |
| 58 | except (ValueError, AttributeError): |
| 59 | return "" |
| 60 | freq = (frequency or "monthly").strip().lower() |
| 61 | if freq == "daily": |
| 62 | return (current + timedelta(days=1)).isoformat() |
| 63 | if freq == "weekly": |
| 64 | return (current + timedelta(days=7)).isoformat() |
| 65 | months = {"monthly": 1, "quarterly": 3, "yearly": 12}.get(freq) |
| 66 | if months is None: |
| 67 | return "" |
| 68 | advanced = _add_months(current, months) |
| 69 | return advanced.isoformat() if advanced else "" |
| 70 | |
| 71 | |
| 72 | def _run_template(base, tpl, today): |
| 73 | """One due template: compose its period's journal, then advance. |
| 74 | |
| 75 | The period is consumed only once its journal exists (composed now, or by |
| 76 | an earlier pass that crashed before advancing) or there is definitively |
| 77 | nothing to book. When compose_posted_journal could not read the books it |
| 78 | declines to risk a duplicate -- right for the journal, wrong for the |
| 79 | schedule: advancing then would lose the period for good, so next_run is |
| 80 | left where it is and the next pass retries it. |
| 81 | Returns (result-or-None, composed_now).""" |
| 82 | next_run = (tpl.get("next_run") or "").strip() |
| 83 | marker = f"fin_recurring/{tpl['id']}:{next_run}" |
| 84 | already = object_finance.find_journal_by_provenance(base, marker) is not None |
| 85 | result, composed_now = None, False |
| 86 | if not already: |
| 87 | try: |
| 88 | lines_spec = json.loads(tpl.get("template_lines") or "[]") |
| 89 | except (ValueError, TypeError): |
| 90 | return {"template": tpl["id"], "error": "bad template_lines JSON"}, False |
| 91 | auto_post = (tpl.get("auto_post") or "").lower() in ("true", "1", "yes") |
| 92 | composed = object_finance.compose_posted_journal( |
| 93 | base, |
| 94 | generated_from=marker, |
| 95 | date=next_run, |
| 96 | description=f"{tpl.get('name') or 'Recurring entry'} ({next_run})", |
| 97 | lines=lines_spec, |
| 98 | owner_id=tpl.get("owner_id", ""), |
| 99 | entity_id=tpl.get("entity_id", ""), |
| 100 | kind="adjusting", |
| 101 | actor=ACTOR, |
| 102 | post=auto_post, |
| 103 | ) |
| 104 | if not composed.get("ok"): |
| 105 | return {"template": tpl["id"], "error": composed.get("error", "compose failed")}, False |
| 106 | result = {"template": tpl["id"], |
| 107 | "journal": composed.get("journal_id", ""), |
| 108 | "posted": bool(composed.get("posted"))} |
| 109 | if "did not balance" in (composed.get("note") or ""): |
| 110 | result["note"] = "unbalanced: left draft" |
| 111 | inconclusive = (not composed.get("journal_id") |
| 112 | and "unreadable" in str(composed.get("skipped") or "")) |
| 113 | if inconclusive: |
| 114 | return result, False |
| 115 | composed_now = bool(composed.get("journal_id")) and not composed.get("skipped") |
| 116 | following = _advance(next_run, tpl.get("frequency")) |
| 117 | if not following: |
| 118 | error = {"template": tpl["id"], |
| 119 | "error": f"cannot advance frequency {tpl.get('frequency')!r} from {next_run}"} |
| 120 | return (result or error), composed_now |
| 121 | object_records.update_collection_record( |
| 122 | "fin_recurring", tpl["id"], |
| 123 | {"next_run": following, "last_run": next_run}, |
| 124 | base_dir=base, actor=ACTOR, |
| 125 | ) |
| 126 | return result, composed_now |
| 127 | |
| 128 | |
| 129 | def POST(request): |
| 130 | base = _base_dir() |
| 131 | today = str(request.get("today") or date.today().isoformat()) |
| 132 | try: |
| 133 | templates = object_records.read_collection_records("fin_recurring", base_dir=base) |
| 134 | except Exception: |
| 135 | return {"ok": True, "skipped": "fin_recurring not installed"} |
| 136 | |
| 137 | ran, results = 0, [] |
| 138 | for tpl in templates: |
| 139 | if (tpl.get("is_active") or "").lower() not in ("true", "1", "yes"): |
| 140 | continue |
| 141 | next_run = (tpl.get("next_run") or "").strip() |
| 142 | if not next_run or next_run > today: |
| 143 | continue |
| 144 | # One broken template must not stop the ones after it (a raise here |
| 145 | # used to abort the pass on every run, so every later template was |
| 146 | # never composed). Its error is reported and it is retried next pass. |
| 147 | try: |
| 148 | result, composed_now = _run_template(base, tpl, today) |
| 149 | except Exception as exc: # noqa: BLE001 -- isolate templates |
| 150 | results.append({"template": tpl.get("id", ""), |
| 151 | "error": f"{type(exc).__name__}: {exc}"}) |
| 152 | continue |
| 153 | if result is not None: |
| 154 | results.append(result) |
| 155 | if composed_now: |
| 156 | ran += 1 |
| 157 | return {"ok": True, "ran": ran, "results": results, "today": today} |