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
time_logs.py · 5.2 KB · 118 lines
1"""Pre-write hook for time_logs: the gate between hours and money.
2
3Consulting hours are a usage metric with an approval gate, and this is
4the gate. Three things happen here and nowhere else:
5
6**Nothing is submitted while the clock is running.** An entry with no
7ended_at has no duration, and billing a duration that is still growing
8means the number on the invoice was never the number anyone approved.
9
10**Nobody approves their own hours.** An approval you can grant yourself
11is not an approval -- it is a formality with an audit trail. This is the
12one rule here that exists for the reader of the invoice rather than for
13the person entering time.
14
15**Approval stamps the rate.** The card in force on the day the work
16happened is resolved and written onto the entry (docs/logic-decisions.md
17#1), so a rate change next quarter cannot reprice work already approved,
18and "why am I being charged this?" stays answerable years later via
19rate_card_id.
20
21After that the entry is frozen -- but that is no longer said here. The
22schema's `locked_when` on approved/billed (only status, invoice_id and
23notes may still change; no delete), checked by object_records inside the
24write lock for every writer, is the whole rule, and `transitions` leaves
25billed terminal. The hook's copy of it ran before the lock, never saw a
26DELETE, and never saw a storage-level writer. The invoice generator, a
27trusted server-side writer, moves approved to billed and stamps invoice_id
28through the `except` fields.
29"""
30
31import os
32from datetime import datetime, timezone
33
34import object_rates
35import object_records
36
37
38def _base_dir():
39 return os.environ.get("DBBASIC_DATA_DIR", "data")
40
41
42def _truthy(value):
43 return str(value or "").strip().lower() in ("true", "1", "yes", "on")
44
45
46def _int(value):
47 try:
48 return int(str(value or "0").strip() or 0)
49 except (TypeError, ValueError):
50 return 0
51
52
53def BEFORE_WRITE(request):
54 action = request.get("action")
55 if action not in ("create", "update"):
56 # Every rule below reads "what status would this record have", and
57 # was written when only create and update arrived here. A delete of
58 # an approved entry has that status and no approved `existing`, so
59 # it ran the APPROVAL gate: the owner was refused for "approving
60 # their own hours" and anybody else got a rate stamp back. Neither
61 # is a decision about a delete, so this hook takes no position on
62 # one. Whether approved or billed time may be deleted is the
63 # schema's `locked_when` rule (it may not), judged on the stored
64 # row inside the write lock.
65 return None
66 record = dict(request.get("record") or {})
67 existing = request.get("existing") or {}
68 subject = request.get("subject") or {}
69 actor = str(subject.get("user_id") or "")
70
71 was = str(existing.get("status") or "") if action == "update" else ""
72 now = str(record.get("status") or existing.get("status") or "draft")
73
74 # --- submitting ------------------------------------------------------
75 if now == "submitted" and was != "submitted":
76 ended = str(record.get("ended_at") or existing.get("ended_at") or "").strip()
77 running = _truthy(record.get("is_running", existing.get("is_running")))
78 if running or not ended:
79 return {"error": ("Stop the timer before submitting. An entry that "
80 "is still running has no duration to approve."),
81 "status": 400}
82 if _int(record.get("duration_seconds", existing.get("duration_seconds"))) <= 0:
83 return {"error": "A time entry with no elapsed time has nothing to bill.",
84 "status": 400}
85
86 # --- approving -------------------------------------------------------
87 if now == "approved" and was != "approved":
88 merged = {**existing, **record}
89 if not _truthy(merged.get("billable")):
90 return {"error": ("Only billable time can be approved for billing. "
91 "Mark it billable, or leave it as recorded work."),
92 "status": 400}
93 owner = str(merged.get("owner_id") or "")
94 if actor and owner and actor == owner:
95 return {"error": ("Time is approved by somebody other than the "
96 "person who logged it. An approval you can grant "
97 "yourself is not an approval."), "status": 403}
98
99 try:
100 cards = object_records.read_collection_records(
101 "rate_cards", base_dir=_base_dir())
102 except Exception:
103 cards = []
104 rated = object_rates.rate_entry(merged, cards)
105 if rated["unrated_reason"]:
106 return {"error": (f"No rate applies to this time: "
107 f"{rated['unrated_reason']}. Add a rate card "
108 f"before approving it, or the hours would be "
109 f"approved at nothing."), "status": 409}
110
111 record["hourly_rate_cents"] = str(rated["rate_cents"])
112 record["amount_cents"] = str(rated["amount_cents"])
113 record["rate_card_id"] = rated["rate_card_id"]
114 record["approved_by"] = actor
115 record["approved_at"] = datetime.now(timezone.utc).isoformat()
116 return {"record": record}
117
118 return None