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

0 downloads

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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
time_logs.py · 5.4 KB · 125 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. Correcting approved or billed time is a
22compensating entry or a credit on the invoice, never an edit to the
23record of what happened (#5, #8). Note the standing posture: hooks gate
24the PUBLIC write surface, so the invoice generator -- a trusted
25server-side writer going through object_records directly -- stamps
26invoice_id and moves approved to billed without asking permission here.
27"""
28
29import os
30from datetime import datetime, timezone
31
32import object_rates
33import object_records
34
35# What an entry may still change once a human has approved it. Everything
36# else about it is now evidence.
37_ALLOWED_AFTER_APPROVAL = {"status", "invoice_id", "notes"}
38
39
40def _base_dir():
41 return os.environ.get("DBBASIC_DATA_DIR", "data")
42
43
44def _truthy(value):
45 return str(value or "").strip().lower() in ("true", "1", "yes", "on")
46
47
48def _int(value):
49 try:
50 return int(str(value or "0").strip() or 0)
51 except (TypeError, ValueError):
52 return 0
53
54
55def BEFORE_WRITE(request):
56 action = request.get("action")
57 record = dict(request.get("record") or {})
58 existing = request.get("existing") or {}
59 changes = request.get("changes") or {}
60 subject = request.get("subject") or {}
61 actor = str(subject.get("user_id") or "")
62
63 was = str(existing.get("status") or "") if action == "update" else ""
64 now = str(record.get("status") or existing.get("status") or "draft")
65
66 # --- frozen once approved -------------------------------------------
67 if action == "update" and was in ("approved", "billed"):
68 touched = [field for field in changes
69 if field not in _ALLOWED_AFTER_APPROVAL]
70 if touched:
71 return {"error": (
72 f"This time entry is {was} and its record of what happened is "
73 f"settled. Correct it with a compensating entry or a credit on "
74 f"the invoice, not by editing "
75 f"{', '.join(sorted(touched))}."), "status": 409}
76 if was == "billed" and now != "billed":
77 return {"error": ("Billed time cannot be reopened. A disputed hour "
78 "is a credit on the invoice, not a rewind."),
79 "status": 409}
80
81 # --- submitting ------------------------------------------------------
82 if now == "submitted" and was != "submitted":
83 ended = str(record.get("ended_at") or existing.get("ended_at") or "").strip()
84 running = _truthy(record.get("is_running", existing.get("is_running")))
85 if running or not ended:
86 return {"error": ("Stop the timer before submitting. An entry that "
87 "is still running has no duration to approve."),
88 "status": 400}
89 if _int(record.get("duration_seconds", existing.get("duration_seconds"))) <= 0:
90 return {"error": "A time entry with no elapsed time has nothing to bill.",
91 "status": 400}
92
93 # --- approving -------------------------------------------------------
94 if now == "approved" and was != "approved":
95 merged = {**existing, **record}
96 if not _truthy(merged.get("billable")):
97 return {"error": ("Only billable time can be approved for billing. "
98 "Mark it billable, or leave it as recorded work."),
99 "status": 400}
100 owner = str(merged.get("owner_id") or "")
101 if actor and owner and actor == owner:
102 return {"error": ("Time is approved by somebody other than the "
103 "person who logged it. An approval you can grant "
104 "yourself is not an approval."), "status": 403}
105
106 try:
107 cards = object_records.read_collection_records(
108 "rate_cards", base_dir=_base_dir())
109 except Exception:
110 cards = []
111 rated = object_rates.rate_entry(merged, cards)
112 if rated["unrated_reason"]:
113 return {"error": (f"No rate applies to this time: "
114 f"{rated['unrated_reason']}. Add a rate card "
115 f"before approving it, or the hours would be "
116 f"approved at nothing."), "status": 409}
117
118 record["hourly_rate_cents"] = str(rated["rate_cents"])
119 record["amount_cents"] = str(rated["amount_cents"])
120 record["rate_card_id"] = rated["rate_card_id"]
121 record["approved_by"] = actor
122 record["approved_at"] = datetime.now(timezone.utc).isoformat()
123 return {"record": record}
124
125 return None