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
mileage_logs.py · 7.9 KB · 172 lines
1"""Pre-write hook and locked check for mileage_logs: the miles an auditor can follow.
2
3A mileage log replaces a receipt, so it has to be as hard to fudge as one.
4The ways a log goes wrong are few and specific, and each has one place:
5
6- An end reading at or below the start, or miles that do not match the two
7 readings: a typo that would pay for miles nobody drove. Refused.
8- Two trips claiming the same stretch of odometer: either a duplicate
9 entry or one invented trip. Ranges are half-open per vehicle -- a trip
10 may start at the reading the previous one ended on -- and a rejected log
11 occupies nothing, so a corrected trip can be logged again. Refused.
12- Approving your own trip. Refused, as for expenses (the hook knows who is
13 writing; a check never does).
14- Paying this year's trip at a rate somebody remembers. The rate is the
15 operator's row for the trip's calendar year (mileage_rates), stamped on
16 the log at approval with the reimbursement it produces
17 (docs/logic-decisions.md #1); a year with no row is refused by name,
18 because a guessed rate is a wrong payment that looks right.
19
20Placement. The odometer, overlap and rate rules are facts about the data,
21so they are a LOCKED_CHECK (inside the write lock, for every writer: HTTP,
22imports, the daemon): two overlapping trips submitted at the same moment
23cannot both land, which a hook -- advisory, before the lock -- could not
24promise. The check reads this collection (the other trips on the vehicle);
25every write to mileage_logs takes the check's lock, so those rows hold
26still while it decides. BEFORE_WRITE does what only a hook can: fill the
27miles from the readings and the stamps from the rate table so the person
28does not have to, and refuse self-approval. Both call
29object_expense_rules, so the early answer and the locked one agree.
30
31What creates the reimbursement is a REACTION (#6): system_mileage_expenses,
32after the approval has landed.
33"""
34
35import os
36from datetime import datetime, timezone
37
38import object_collections
39import object_expense_rules as rules
40import object_records
41
42
43def _base_dir():
44 return os.environ.get("DBBASIC_DATA_DIR", "data")
45
46
47def _vehicle(base, vehicle_id):
48 try:
49 return object_records.get_collection_record("vehicles", vehicle_id, base_dir=base)
50 except (object_records.RecordNotFoundError, object_collections.CollectionNotFoundError):
51 return None
52
53
54def _rates(base):
55 try:
56 return object_records.read_collection_records("mileage_rates", base_dir=base)
57 except object_collections.CollectionNotFoundError:
58 return []
59
60
61def _approving(record, existing):
62 now = rules.text(record.get("status"))
63 was = rules.text((existing or {}).get("status"))
64 return now == "approved" and (existing is None or was != "approved")
65
66
67def expected_stamps(record, base):
68 """(stamps, None) or (None, refusal): the rate year, the rate and the
69 reimbursement approving this log must carry. Raises when the rate table
70 or the vehicle cannot be read (a check then answers 503)."""
71 trip_date = rules.text(record.get("trip_date"))
72 year = trip_date[:4]
73 row = rules.rate_for_year(_rates(base), year)
74 if row is None:
75 return None, {"error": (f"There is no mileage rate for {year}. Add the year's rate "
76 "(mileage_rates, with its source) before approving trips in it."),
77 "status": 409}
78 rate = rules.whole(row.get("rate_hundredths_cent"), field="rate_hundredths_cent")
79 vehicle = _vehicle(base, rules.text(record.get("vehicle_id")))
80 if vehicle is None:
81 return None, {"error": "The vehicle this trip names does not exist.", "status": 409}
82 miles = rules.whole(record.get("miles"), field="miles")
83 owed = (rules.mileage_reimbursement(miles, rate)
84 if rules.text(vehicle.get("ownership")) != "business" else 0)
85 return {"rate_year": year, "rate_hundredths_cent": str(rate),
86 "reimbursement_cents": str(owed)}, None
87
88
89def _changed(record, existing, names):
90 if existing is None:
91 return True
92 return any(rules.text(record.get(n)) != rules.text(existing.get(n)) for n in names)
93
94
95def LOCKED_CHECK(request):
96 """mileage_rules: readings, overlap and the approval's stamps, for every writer."""
97 record = request.get("record") or {}
98 existing = request.get("existing") if request.get("action") == "update" else None
99 base = request.get("base_dir") or _base_dir()
100
101 try:
102 from_odometer = rules.odometer_miles(record.get("start_odometer"), record.get("end_odometer"))
103 except ValueError as exc:
104 return {"error": f"Odometer: {exc}.", "status": 409}
105 if from_odometer is not None and rules.text(record.get("miles")) != str(from_odometer):
106 return {"error": (f"The readings say {from_odometer} miles but the log says "
107 f"{rules.text(record.get('miles')) or 'none'}."), "status": 409}
108
109 if (from_odometer is not None and rules.text(record.get("status")) != "rejected"
110 and _changed(record, existing, ("vehicle_id", "start_odometer", "end_odometer", "status"))):
111 others = object_records.read_collection_records_where(
112 "mileage_logs", "vehicle_id", rules.text(record.get("vehicle_id")), base_dir=base)
113 clash = rules.overlapping_log(record, others)
114 if clash is not None:
115 return {"error": (f"Odometer {record.get('start_odometer')}-{record.get('end_odometer')} "
116 f"overlaps the trip on {clash.get('trip_date')} "
117 f"({clash.get('start_odometer')}-{clash.get('end_odometer')}) in the "
118 "same vehicle. Two trips cannot have used the same miles."),
119 "status": 409}
120
121 if _approving(record, existing):
122 wanted, refusal = expected_stamps(record, base)
123 if refusal:
124 return refusal
125 for name, value in wanted.items():
126 if rules.text(record.get(name)) != value:
127 return {"error": (f"Approving this trip stamps {name} {value} from the "
128 f"{wanted['rate_year']} mileage rate; the write carries "
129 f"{rules.text(record.get(name)) or 'nothing'}."), "status": 409}
130 return None
131
132
133def BEFORE_WRITE(request):
134 action = request.get("action")
135 if action not in ("create", "update"):
136 return None # a delete: locked_when and the rules decide
137 record = dict(request.get("record") or {})
138 existing = request.get("existing") if action == "update" else None
139 subject = request.get("subject") or {}
140 actor = rules.text(subject.get("user_id"))
141 base = _base_dir()
142 changed = False
143
144 try:
145 miles = rules.odometer_miles(record.get("start_odometer"), record.get("end_odometer"))
146 except ValueError as exc:
147 return {"error": f"Odometer: {exc}.", "status": 400}
148 if miles is not None and _changed(record, existing, ("start_odometer", "end_odometer")) \
149 and rules.text(record.get("miles")) != str(miles):
150 record["miles"] = str(miles)
151 changed = True
152
153 if _approving(record, existing):
154 owner = rules.text(record.get("owner_id"))
155 if actor and owner and actor == owner:
156 return {"error": ("Mileage is approved by somebody other than the person who "
157 "drove it."), "status": 403}
158 try:
159 wanted, refusal = expected_stamps(record, base)
160 except ValueError as exc:
161 return {"error": f"This trip cannot be priced: {exc}.", "status": 409}
162 except Exception:
163 return {"error": "The mileage rates are unreadable; refusing to price this trip.",
164 "status": 503}
165 if refusal:
166 return refusal
167 record.update(wanted)
168 record["approved_by"] = actor
169 record["approved_at"] = datetime.now(timezone.utc).isoformat()
170 changed = True
171
172 return {"record": record} if changed else None