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
stock_hold.py · 6.9 KB · 170 lines
1"""system_stock_hold -- an online order's line is a hold, decided inside the lock.
2
3Ships one function, LOCKED_CHECK, which order_lines.json declares as the
4locked check `stock_hold` under the lock "stock". object_records calls it
5for EVERY writer of an order line -- action_checkout, the API, an import --
6holding that lock, and every write to a collection the verdict reads
7(orders, the stock log, shipment lines, payments, invoices, pickup slots,
8products, locations, settings) takes the same lock first. So "is there
9still one left?" and "this order takes it" are one step: two shoppers
10racing for the last unit both reach this function, one after the other,
11and the second one sees the first one's line.
12
13Why here and not in action_checkout's gate. The gate reads and decides
14before anything is written; ten checkouts released together all read the
15same shelf and all passed, which is how one unit was sold to two orders
16and three to ten. A gate cannot close that (AGENTS.md: "Hooks cannot close
17a race"); a check the store runs under a lock can. The gate still runs
18first, so a shopper hears every problem together and before anything is
19written -- this is the part that holds when the gate was raced.
20
21What it refuses: a line of a reserving order for a product sold in the
22shop only (products.in_store_only) or beyond the product's online limit
23per order (products.online_max_per_order) -- the sentence action_cart and
24checkout give too, object_reservations.online_refusal; and a line of an
25order that RESERVES (orders.reserves_stock,
26stamped by checkout) for a tracked product whose seller does not take
27backorders, when on hand less what other live orders hold is less than
28this line plus the order's other lines of that product. Everything else is
29allowed and untouched: an operator's own order (it does not reserve), a
30service or a download (no shelf), a product whose backorder_policy is
31`allow` (sold with the shop's open agreement that it is not here yet; the
32line still HOLDS, so the next shopper is promised nothing that is owed),
33a box without the stock app (no shelf to count).
34
35The arithmetic is object_reservations, shared with the checkout gate and
36the storefront so the three cannot disagree. Reads only; never asks who is
37writing -- this is a fact about the shelf, not a permission.
38"""
39
40import os
41from decimal import Decimal
42
43import object_collections
44import object_records
45
46INACTIVE = ("false", "0", "no", "off")
47
48
49def _base_dir():
50 return os.environ.get("DBBASIC_DATA_DIR", "data")
51
52
53def _text(value):
54 return str(value if value is not None else "").strip()
55
56
57def _qty(value):
58 try:
59 return Decimal(_text(value) or "0")
60 except Exception:
61 return Decimal("0")
62
63
64def _get(collection, record_id, base):
65 """The row, None when absent or not installed. Raises when unreadable."""
66 if not record_id:
67 return None
68 try:
69 return object_records.get_collection_record(collection, record_id, base_dir=base)
70 except (object_records.RecordNotFoundError, object_collections.CollectionNotFoundError,
71 object_records.InvalidRecordIdError):
72 return None
73
74
75def _on_hand(product_id, base):
76 """The product's level, or None when this box keeps no stock log."""
77 import object_stock
78 try:
79 return object_stock.total_quantity(product_id, base_dir=base)
80 except object_collections.CollectionNotFoundError:
81 return None
82
83
84def _unknown(what, exc):
85 return {"status": 503,
86 "error": (f"The stock held by online orders cannot be counted right now "
87 f"({what}: {str(exc)[:120]}), so this line was not taken. Try "
88 f"again in a moment.")}
89
90
91def _fmt(value):
92 text = format(value.normalize(), "f") if isinstance(value, Decimal) else str(value)
93 return text
94
95
96def LOCKED_CHECK(request):
97 """None to allow, or a refusal. See the module docstring."""
98 if request.get("action") == "delete":
99 return None
100 record = request.get("record") or {}
101 base = request.get("base_dir") or _base_dir()
102 try:
103 order = _get("orders", _text(record.get("order_id")), base)
104 except Exception as exc: # noqa: BLE001 -- unknown is not "allowed"
105 return _unknown("orders", exc)
106 if order is None or _text(order.get("reserves_stock")).lower() not in ("true", "1", "yes", "on"):
107 return None
108 # Imported here, past the order every operator types (which never
109 # reserves): a box whose root modules predate object_reservations still
110 # writes those lines rather than failing to load this check for all of
111 # them.
112 import object_reservations
113 if not object_reservations.reserves(order):
114 return None
115 if _text(order.get("status") or "draft").lower() not in object_reservations.RESERVING_STATUSES:
116 return None
117
118 product_id = _text(record.get("product_id"))
119 try:
120 product = _get("products", product_id, base)
121 except Exception as exc: # noqa: BLE001
122 return _unknown("products", exc)
123 if product is None:
124 return None
125 name = _text(product.get("name")) or product_id
126
127 try:
128 lines = object_records.read_collection_records("order_lines", base_dir=base)
129 except Exception as exc: # noqa: BLE001
130 return _unknown("order_lines", exc)
131 line_id = _text(record.get("id"))
132 # This order's lines of this product, this one as it is about to be
133 # stored: they all have to fit, together -- on the shelf and under the
134 # product's per-order online limit.
135 wanted = _qty(record.get("quantity")) + sum(
136 (_qty(line.get("quantity")) for line in lines
137 if _text(line.get("order_id")) == _text(order.get("id"))
138 and _text(line.get("product_id")) == product_id
139 and _text(line.get("id")) != line_id), Decimal("0"))
140
141 # Sold in the shop only, or over the online limit: no online order
142 # holds it, whatever the shelf says (products.in_store_only).
143 refusal = object_reservations.online_refusal(product, wanted)
144 if refusal:
145 return {"status": 409, "error": refusal}
146
147 if not object_reservations.tracked(product):
148 return None
149 if _text(product.get("backorder_policy")).lower() == "allow":
150 return None
151
152 try:
153 on_hand = _on_hand(product_id, base)
154 if on_hand is None:
155 return None
156 mine = [_text(line.get("id")) for line in lines
157 if _text(line.get("order_id")) == _text(order.get("id"))]
158 held = object_reservations.read_holds(
159 base, exclude_line_ids=[line_id, *mine]).get(product_id, Decimal("0"))
160 except Exception as exc: # noqa: BLE001
161 return _unknown("stock", exc)
162
163 available = on_hand - held
164 if wanted <= available:
165 return None
166 left = available if available > 0 else Decimal("0")
167 return {"status": 409,
168 "error": (f"Only {_fmt(left)} of {name} can still be reserved online "
169 f"(another order took the rest); this order asked for "
170 f"{_fmt(wanted)}.")}