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

0 downloads

dbbasic-object-server/object_rates.py
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
object_rates.py · 8.8 KB · 225 lines
1"""Rate cards: what an hour of human work costs, and which hour.
2
3The pure half of time-and-materials billing, kept out of the objects so
4it can be tested exhaustively without a data directory -- the same
5posture as object_billing's rating and object_money's conversions.
6
7Consulting hours are a usage metric with an approval gate. That is the
8whole insight behind this file: metering, rating and invoicing are the
9same spine as cloud billing, and the only structural difference is that a
10human has to say "yes, bill that" before an hour becomes money. So the
11rating half looks deliberately like object_billing -- integer minor
12units, rounding stated where it happens, no I/O.
13
14Two rules matter more than the arithmetic:
15
16**Most specific wins.** A rate card can be scoped to a person on a
17project, a project, a person, or nothing at all. Resolution walks from
18narrowest to widest and stops, because the reason anyone writes a rate
19for "Dana on the Acme rebuild" is that it must beat both the Acme rate
20and Dana's standard rate.
21
22**Never look forward.** A card applies from its valid_from onward, so the
23rate in force is the newest one that had already started when the work
24happened. Picking today's rate for last quarter's unbilled hours is how a
25client gets an invoice that does not match the engagement letter they
26signed.
27
28The resolved rate is then STAMPED onto the entry at approval (doctrine
29#1). Everything here is about choosing it correctly once; after that the
30number belongs to the entry, and a rate change next quarter can never
31reprice work someone already approved.
32"""
33
34from __future__ import annotations
35
36from decimal import Decimal, InvalidOperation, ROUND_HALF_UP, ROUND_UP
37from typing import Any
38
39# Narrowest first. A card matches a scope only when every part of that
40# scope is present on it AND agrees with the work; the first scope with
41# any match wins outright, so a project rate is never averaged against a
42# person rate -- one of them is the answer.
43SCOPE_ORDER = ("person_project", "project", "person", "default")
44
45
46def _text(value: Any) -> str:
47 return str(value if value is not None else "").strip()
48
49
50def _num(value: Any, default: int = 0) -> Decimal:
51 try:
52 return Decimal(_text(value) or str(default))
53 except (InvalidOperation, TypeError, ValueError):
54 return Decimal(default)
55
56
57def _scope_of(card: dict) -> str:
58 """Which scope a card occupies, read from what it actually carries.
59
60 Derived rather than trusted from a scope_type column: a card naming
61 both a person and a project IS a person-project rate, and letting the
62 two disagree would mean a card that resolves differently from how it
63 reads.
64 """
65 person = _text(card.get("person_id"))
66 project = _text(card.get("project_id"))
67 if person and project:
68 return "person_project"
69 if project:
70 return "project"
71 if person:
72 return "person"
73 return "default"
74
75
76def _truthy(value: Any) -> bool:
77 return _text(value).lower() in ("true", "1", "yes", "on")
78
79
80def _active(card: dict) -> bool:
81 # Absent is_active means active: a rate card written without the flag
82 # is a rate somebody meant to use.
83 raw = card.get("is_active")
84 return True if raw in (None, "") else _truthy(raw)
85
86
87def find_rate(cards: list[dict], *, on_date: str, person_id: str = "",
88 project_id: str = "") -> dict | None:
89 """The rate card in force for this work, or None.
90
91 `on_date` is the date the work HAPPENED, not today: an entry approved
92 late is still billed at the rate that applied when it was done.
93 """
94 day = _text(on_date)[:10]
95 person = _text(person_id)
96 project = _text(project_id)
97
98 candidates: dict[str, list[dict]] = {scope: [] for scope in SCOPE_ORDER}
99 for card in cards:
100 if not _active(card):
101 continue
102 if _num(card.get("hourly_rate_cents"), -1) < 0:
103 continue
104 valid_from = _text(card.get("valid_from"))[:10]
105 if day and valid_from and valid_from > day:
106 continue # not yet in force -- never look forward
107 scope = _scope_of(card)
108 card_person = _text(card.get("person_id"))
109 card_project = _text(card.get("project_id"))
110 if card_person and card_person != person:
111 continue
112 if card_project and card_project != project:
113 continue
114 candidates[scope].append(card)
115
116 for scope in SCOPE_ORDER:
117 rows = candidates[scope]
118 if not rows:
119 continue
120 # Newest applicable version wins within the scope. Rate cards
121 # version forward and are never edited, so "the latest one that
122 # had already started" is the whole of the lookup.
123 return max(rows, key=lambda c: (_text(c.get("valid_from"))[:10],
124 _text(c.get("id"))))
125 return None
126
127
128def billable_seconds(duration_seconds: Any, increment_minutes: Any = 0) -> int:
129 """Seconds actually billed, after any minimum increment.
130
131 Increment lives on the rate card rather than in a global setting
132 because rounding to the next six minutes is a term of the engagement,
133 not a preference of the server. It rounds UP -- that is what an
134 increment means -- which is exactly why it must be something a client
135 agreed to in writing rather than a default that quietly inflates
136 every bill. Zero (the default) bills the seconds that happened.
137 """
138 seconds = _num(duration_seconds)
139 if seconds <= 0:
140 return 0
141 step = _num(increment_minutes)
142 if step <= 0:
143 return int(seconds)
144 step_seconds = step * 60
145 blocks = (seconds / step_seconds).to_integral_value(rounding=ROUND_UP)
146 return int(blocks * step_seconds)
147
148
149def amount_cents(duration_seconds: Any, hourly_rate_cents: Any,
150 increment_minutes: Any = 0) -> int:
151 """What this entry is worth, rounded half-up ONCE.
152
153 Rounding per entry, not per hour and not per invoice: an entry is the
154 thing a client disputes, so it has to be the thing whose arithmetic
155 they can reproduce, and the invoice total must equal the sum of its
156 own lines.
157 """
158 seconds = Decimal(billable_seconds(duration_seconds, increment_minutes))
159 if seconds <= 0:
160 return 0
161 rate = _num(hourly_rate_cents)
162 if rate <= 0:
163 return 0
164 amount = (seconds / Decimal(3600)) * rate
165 return int(amount.to_integral_value(rounding=ROUND_HALF_UP))
166
167
168def rate_entry(entry: dict, cards: list[dict]) -> dict:
169 """Resolve and price one time entry: {rate_cents, amount_cents,
170 increment_minutes, rate_card_id, unrated_reason}.
171
172 An entry with no applicable card comes back priced at nothing WITH a
173 reason, never priced at zero in silence. Unbillable hours that look
174 identical to hours nobody wrote a rate for is how revenue goes
175 missing quietly.
176 """
177 card = find_rate(
178 cards,
179 on_date=_text(entry.get("worked_on") or entry.get("started_at")),
180 person_id=_text(entry.get("owner_id")),
181 project_id=_text(entry.get("project_id")),
182 )
183 if card is None:
184 return {"rate_cents": 0, "amount_cents": 0, "increment_minutes": 0,
185 "rate_card_id": "",
186 "unrated_reason": "no rate card applies to this person, "
187 "project and date"}
188 rate = int(_num(card.get("hourly_rate_cents")))
189 increment = int(_num(card.get("increment_minutes")))
190 return {
191 "rate_cents": rate,
192 "increment_minutes": increment,
193 "rate_card_id": _text(card.get("id")),
194 "amount_cents": amount_cents(entry.get("duration_seconds"), rate, increment),
195 "unrated_reason": "",
196 }
197
198
199def with_markup(amount_cents: Any, markup_bps: Any = 0) -> int:
200 """A pass-through cost as it appears on the client's bill.
201
202 Basis points rather than a percentage, matching invoice_lines'
203 tax_rate_bps: 1500 is 15%. Rounded half-up once, on the whole amount,
204 so the line total equals what the arithmetic says and a client
205 checking it with a calculator gets the same answer.
206
207 A markup of zero is the default and means the cost is passed through
208 at cost -- the honest baseline, and the one a client assumes unless
209 the engagement said otherwise.
210 """
211 amount = _num(amount_cents)
212 if amount <= 0:
213 return 0
214 bps = _num(markup_bps)
215 if bps <= 0:
216 return int(amount.to_integral_value(rounding=ROUND_HALF_UP))
217 grossed = amount * (Decimal(10000) + bps) / Decimal(10000)
218 return int(grossed.to_integral_value(rounding=ROUND_HALF_UP))
219
220
221def hours(duration_seconds: Any, increment_minutes: Any = 0) -> str:
222 """Billable hours as a human reads them on an invoice line."""
223 seconds = Decimal(billable_seconds(duration_seconds, increment_minutes))
224 return str((seconds / Decimal(3600)).quantize(Decimal("0.01"),
225 rounding=ROUND_HALF_UP))