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
slot_generator.py · 9.9 KB · 251 lines
1"""system_slot_generator -- tomorrow's collection windows, made overnight.
2
3POST {today?, days_ahead?, dry_run?} -- the daily pass that turns an
4opening-hours setting into the rows a storefront's time picker reads.
5
6**A shop that has to create tomorrow's slots by hand will one day forget,
7and take no orders at all.** That sentence is the whole design. Not a
8page with an "add slot" button, not a wizard somebody runs on a Sunday:
9a scheduled pass, declared in this package's manifest, that runs before
10the shop opens and leaves the next N days bookable whether or not anybody
11thought about it. The failure it exists to prevent is silent and total --
12the storefront offers no times, every customer is told the shop cannot
13take their order, and nothing anywhere logs an error, because a picker
14with nothing in it is indistinguishable from a shop that is fully booked.
15
16Five settings say what a day looks like, and every one of them has a
17default, so a shop that has configured nothing still gets a sensible
18board rather than an empty one:
19
20 pickup.open_time "09:00" -- when the first window starts
21 pickup.close_time "17:00" -- no window may end after this
22 pickup.slot_minutes 30 -- how long each window is
23 pickup.capacity_per_slot 4 -- orders, not items (see the schema)
24 pickup.days_ahead 7 -- how far out to build
25 pickup.location_id "" -- which counter these belong to
26
27**Idempotent by (starts_at, location_id).** Re-running the pass -- twice
28in a night, after a crash, or by an operator poking it to see what it
29does -- creates nothing that already exists, and the identity is those
30two fields rather than a generated marker because a slot IS its time and
31its counter. The same property app-billing's runner buys with a
32provenance marker in `notes`, bought here by the row's own natural key,
33which is stronger: an operator who typed a 6pm slot by hand gets it
34adopted rather than duplicated, and a shop with two counters gets two
356pm slots rather than one.
36
37It builds from TODAY, not from tomorrow. The window that has already
38passed is harmless -- action_pickup_slots never offers a slot inside the
39lead time, so this morning's nine o'clock is filtered out by the thing
40whose job that is -- and a shop that installs this app at eight in the
41morning must be able to take lunch orders today rather than discovering
42its own product tomorrow.
43
44What it deliberately does NOT do: close slots, change capacity on slots
45that already exist, or delete anything. A slot somebody edited is a
46decision, and a nightly pass that restated it would overwrite the
47operator every single night -- the same rule the package installer holds
48to for a paused schedule and a hidden nav entry. This pass only ever
49adds.
50"""
51
52import os
53from datetime import date, datetime, timedelta
54
55import object_ids
56import object_records
57
58ACTOR = "system_slot_generator"
59
60DEFAULT_OPEN = "09:00"
61DEFAULT_CLOSE = "17:00"
62DEFAULT_SLOT_MINUTES = 30
63DEFAULT_CAPACITY = 4
64DEFAULT_DAYS_AHEAD = 7
65
66# A guard, not a preference. days_ahead comes from a settings row anybody
67# with a manager role can type into, and a fat-fingered 3650 would fold
68# every collection in the shop into building a decade of empty windows on
69# the same box that is serving requests.
70MAX_DAYS_AHEAD = 60
71
72
73def _base_dir():
74 return os.environ.get("DBBASIC_DATA_DIR", "data")
75
76
77def _text(value):
78 return str(value if value is not None else "").strip()
79
80
81def _truthy(value):
82 return _text(value).lower() in ("true", "1", "yes", "on")
83
84
85def _setting(base, key, default):
86 """Duplicated, on purpose, from every other package that reads
87 app_settings: there is no shared settings module in this codebase yet
88 and inventing one for an nth copy is the layer docs/logic-decisions.md
89 #4 says to wait on.
90 """
91 try:
92 for row in object_records.read_collection_records("app_settings",
93 base_dir=base):
94 if row.get("key") == key and _text(row.get("value")):
95 return _text(row["value"])
96 except Exception:
97 pass
98 return default
99
100
101def _int(value, default=0):
102 try:
103 return int(_text(value) or default)
104 except (TypeError, ValueError):
105 return default
106
107
108def _minutes_of_day(value, default):
109 """"09:00" -> 540. A malformed setting falls back to the default
110 rather than raising: a typo in an opening time must cost the shop its
111 unusual hours for one night, not its whole board of slots.
112 """
113 text = _text(value) or default
114 parts = text.split(":")
115 try:
116 hours, minutes = int(parts[0]), int(parts[1])
117 except (IndexError, ValueError):
118 parts = default.split(":")
119 hours, minutes = int(parts[0]), int(parts[1])
120 if not (0 <= hours <= 23 and 0 <= minutes <= 59):
121 parts = default.split(":")
122 hours, minutes = int(parts[0]), int(parts[1])
123 return hours * 60 + minutes
124
125
126def _stamp(day, minutes):
127 return (datetime(day.year, day.month, day.day)
128 + timedelta(minutes=minutes)).isoformat()
129
130
131def _existing_keys(base):
132 """Every (starts_at, location_id) already on the board.
133
134 An unreadable collection is NOT treated as an empty one: returning an
135 empty set there would make the pass create a duplicate of every slot
136 it could not see, which is the one failure mode worse than creating
137 none. None means "cannot tell", and the caller declines.
138 """
139 try:
140 rows = object_records.read_collection_records("pickup_slots",
141 base_dir=base)
142 except Exception:
143 return None
144 return {(_text(row.get("starts_at")), _text(row.get("location_id")))
145 for row in rows}
146
147
148def _settings(base):
149 open_minutes = _minutes_of_day(_setting(base, "pickup.open_time", ""),
150 DEFAULT_OPEN)
151 close_minutes = _minutes_of_day(_setting(base, "pickup.close_time", ""),
152 DEFAULT_CLOSE)
153 slot_minutes = _int(_setting(base, "pickup.slot_minutes", ""),
154 DEFAULT_SLOT_MINUTES)
155 if slot_minutes <= 0:
156 slot_minutes = DEFAULT_SLOT_MINUTES
157 capacity = _int(_setting(base, "pickup.capacity_per_slot", ""),
158 DEFAULT_CAPACITY)
159 if capacity < 0:
160 capacity = DEFAULT_CAPACITY
161 days_ahead = _int(_setting(base, "pickup.days_ahead", ""),
162 DEFAULT_DAYS_AHEAD)
163 days_ahead = max(0, min(days_ahead, MAX_DAYS_AHEAD))
164 return {"open_minutes": open_minutes, "close_minutes": close_minutes,
165 "slot_minutes": slot_minutes, "capacity": capacity,
166 "days_ahead": days_ahead,
167 "location_id": _setting(base, "pickup.location_id", "")}
168
169
170def _starts_for_day(day, config):
171 """Every window start on one day.
172
173 A slot whose END would fall past closing time is not created: a shop
174 that closes at five does not hand somebody their dinner at five past,
175 and a half-length last window is a promise made by arithmetic rather
176 than by anybody who works there.
177 """
178 starts = []
179 minute = config["open_minutes"]
180 while minute + config["slot_minutes"] <= config["close_minutes"]:
181 starts.append(minute)
182 minute += config["slot_minutes"]
183 return [(_stamp(day, m), _stamp(day, m + config["slot_minutes"]))
184 for m in starts]
185
186
187def POST(request):
188 base = _base_dir()
189 dry_run = _truthy(request.get("dry_run"))
190 try:
191 today = date.fromisoformat(_text(request.get("today"))
192 or date.today().isoformat())
193 except ValueError:
194 return {"status": 400, "error": "today must be an ISO date (YYYY-MM-DD)"}
195
196 config = _settings(base)
197 # An explicit argument beats the setting, so an operator can build a
198 # long weekend without editing the shop's standing configuration.
199 if _text(request.get("days_ahead")):
200 config["days_ahead"] = max(0, min(_int(request.get("days_ahead"),
201 config["days_ahead"]),
202 MAX_DAYS_AHEAD))
203
204 existing = _existing_keys(base)
205 if existing is None:
206 # No pickup_slots collection (this app is not installed on this
207 # box, or its records file is unreadable). Saying so beats both
208 # raising -- the scheduler would log a failure every night on a
209 # shop that never wanted pickup -- and pretending it worked.
210 return {"ok": True, "skipped": "pickup not installed (pickup_slots absent)"}
211
212 created = 0
213 skipped = 0
214 days = []
215 for offset in range(config["days_ahead"] + 1):
216 day = today + timedelta(days=offset)
217 made = 0
218 for starts_at, ends_at in _starts_for_day(day, config):
219 key = (starts_at, config["location_id"])
220 if key in existing:
221 skipped += 1
222 continue
223 existing.add(key)
224 made += 1
225 if dry_run:
226 continue
227 object_records.create_collection_record(
228 "pickup_slots",
229 {
230 "id": object_ids.new_uuid4(),
231 "starts_at": starts_at,
232 "ends_at": ends_at,
233 "capacity": str(config["capacity"]),
234 "orders_taken": "0",
235 "is_open": "true",
236 "location_id": config["location_id"],
237 "notes": f"Generated by {ACTOR}",
238 "owner_id": "",
239 },
240 base_dir=base, actor=ACTOR)
241 created += made
242 days.append({"day": day.isoformat(), "created": made})
243
244 return {"ok": True, "today": today.isoformat(),
245 "days_ahead": config["days_ahead"],
246 "slot_minutes": config["slot_minutes"],
247 "capacity_per_slot": config["capacity"],
248 "location_id": config["location_id"],
249 "created": created, "already_there": skipped,
250 "days": days,
251 **({"dry_run": True} if dry_run else {})}