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
dropship_margin.py · 9.5 KB · 234 lines
1"""site_dropship_margin -- what this drop-ship actually earned.
2GET /orders/{order_id}/margin.
3
4A READ over two rows, and it is worth saying why that is the entire
5feature. The spec's claim about drop-shipping was that "margin is already
6a read because both orders carry money" -- so if this page needed a
7stored margin field, a snapshot, or a third document, the model would
8have been wrong. It needs none: the sale order says what the customer
9paid, the linked purchase order says what the vendor charged, and the
10subtraction is object_billing.margin, the same function that answers the
11same question for metered usage. Not a second implementation of it: a
12margin that rounded differently on two pages is a margin nobody trusts,
13and there is exactly one right answer to revenue minus cost.
14
15It works from EITHER end. Open it on the sale order or on the purchase
16order and it finds the other through linked_order_id, because a link
17written both ways is a link you never have to search for.
18
19**Where the two numbers come from, and what happens when they are not
20there yet.** Each order's stamped total_cents is preferred -- that is the
21document's own number, stamped by system_order_totals, and the one a
22human sees on the order itself. When it is zero the lines are folded
23instead, because order_totals is a post-commit REACTION: a purchase order
24raised ten seconds ago by action_dropship_order may not have been stamped
25yet, and quoting a margin of 100% off a total that simply has not landed
26would be a confident wrong answer at exactly the wrong moment. The page
27says which of the two it used, per order, rather than hiding the
28difference.
29
30**A missing vendor price is reported, not smoothed over.** A purchase
31order at zero produces 100% margin, which is arithmetically correct and
32commercially nonsense; the page says the cost is missing and names what
33to fill in. The alternative -- suppressing the number until somebody
34types a price -- would hide the one case where the read is most needed.
35
36The object also returns the raw figures alongside its HTML (`margin`,
37with revenue_minor / cost_minor / gross_minor / gross_pct). The HTTP
38layer reads `body` and ignores the rest, so this costs a browser nothing
39and gives anything calling the object in process the numbers without
40parsing a page for them.
41
42Requires a signed-in identity, the same gate and the same shape as
43site_pick_list: a sign-in prompt rather than a 403, and margin is a
44number about somebody's business that no visitor is entitled to.
45
46Signed in is not enough: BOTH orders must be ones the caller may read
47through the orders API, asked of the permission engine (object_access).
48The page reads storage directly, so it is the only gate, and it used to
49show any order's revenue, vendor cost and vendor name to any signed-in
50user (bug-reports/2026-11-28-06-14-29). An order the caller may not read
51is "No such order", the same answer as a mistyped id; a readable sale
52whose purchase order is not readable is "not part of a drop-ship pair",
53because the vendor's price is exactly the thing being protected.
54"""
55
56import html
57import os
58
59import object_access
60import object_billing
61import object_records
62
63
64def _base_dir():
65 return os.environ.get("DBBASIC_DATA_DIR", "data")
66
67
68def _text(value):
69 return str(value if value is not None else "").strip()
70
71
72def _esc(value):
73 return html.escape(_text(value))
74
75
76def _cents(value):
77 try:
78 return int(_text(value) or "0")
79 except ValueError:
80 return 0
81
82
83def _money(minor, currency="USD"):
84 sign = "-" if minor < 0 else ""
85 return f"{sign}{abs(minor) // 100}.{abs(minor) % 100:02d} {currency}"
86
87
88_STYLE = """
89.margin-table { width: 100%; border-collapse: collapse; margin: 0.5rem 0 1.5rem; }
90.margin-table th, .margin-table td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
91.margin-table td.num, .margin-table th.num { text-align: right; }
92.hint { color: var(--muted, #999); font-size: 0.9rem; }
93.warn { color: var(--warn, #d08a2a); }
94"""
95
96
97def _totals(base, order):
98 """(amount_minor, source) for one order.
99
100 The stamped total first -- it is the document's own number -- and the
101 lines folded only when it is zero, because the stamp is a reaction
102 that may not have landed yet.
103 """
104 stamped = _cents(order.get("total_cents"))
105 if stamped:
106 return stamped, "stamped"
107 try:
108 # access: lines of the order read through Access above
109 lines = object_records.read_collection_records("order_lines",
110 base_dir=base)
111 except Exception:
112 return 0, "unknown"
113 folded = 0
114 for line in lines:
115 if _text(line.get("order_id")) != order["id"]:
116 continue
117 folded += _cents(line.get("line_total_cents"))
118 folded += _cents(line.get("line_tax_cents"))
119 return folded, "folded" if folded else "empty"
120
121
122def _page(title, body, user_id, path):
123 who = (f"signed in as <strong>{_esc(user_id)}</strong>" if user_id
124 else f'<a href="/login?next={_esc(path)}">sign in</a>')
125 return f"""<!doctype html>
126<html lang="en">
127<head>
128<meta charset="utf-8">
129<meta name="viewport" content="width=device-width, initial-scale=1">
130<title>{_esc(title)}</title>
131<link rel="stylesheet" href="/style">
132<style>{_STYLE}</style>
133</head>
134<body>
135<div class="wrap">
136<header class="app"><h1><a href="/">DBBASIC</a></h1><div class="who">{who}</div></header>
137{body}
138</div>
139<script src="/nav"></script>
140</body>
141</html>"""
142
143
144def GET(request):
145 base = _base_dir()
146 identity = request.get("_identity") or {}
147 user_id = _text(identity.get("user_id"))
148 order_id = _text(request.get("order_id"))
149 path = f"/orders/{order_id}/margin"
150
151 if not user_id:
152 return {"content_type": "text/html; charset=utf-8",
153 "body": _page("Margin",
154 '<p class="hint">Margin is a number about '
155 'somebody\'s business. Please sign in.</p>',
156 user_id, path)}
157
158 access = object_access.Access(identity, base_dir=base)
159 try:
160 order = access.get("orders", order_id)
161 except Exception:
162 order = None
163 if not order:
164 return {"status": 404, "content_type": "text/html; charset=utf-8",
165 "body": _page("Margin",
166 '<p class="hint">No such order.</p>',
167 user_id, path)}
168
169 linked_id = _text(order.get("linked_order_id"))
170 linked = {}
171 if linked_id:
172 try:
173 linked = access.get("orders", linked_id) or {}
174 except Exception:
175 linked = {}
176
177 if not linked:
178 body = (f'<div class="pagehead"><h1>Margin</h1></div>'
179 f'<p class="hint">Order {_esc(order.get("number"))} is not '
180 f'part of a drop-ship pair, so there is no vendor cost to '
181 f'set against it. Margin here is the difference between what '
182 f'the customer paid on one order and what the vendor charged '
183 f'on the other; an order fulfilled from our own shelf needs '
184 f'inventory valuation instead, which this server does not do '
185 f'yet (see tests/test_cogs_on_sale.py).</p>')
186 return {"status": 409, "content_type": "text/html; charset=utf-8",
187 "body": _page("Margin", body, user_id, path)}
188
189 # Which of the two is the sale is a question of doc_type, never of
190 # which one the URL happened to name.
191 if _text(order.get("doc_type")) == "purchase":
192 sale, purchase = linked, order
193 else:
194 sale, purchase = order, linked
195
196 currency = _text(sale.get("currency")) or "USD"
197 revenue, revenue_source = _totals(base, sale)
198 cost, cost_source = _totals(base, purchase)
199 figures = object_billing.margin(revenue, cost)
200
201 pct = ("n/a" if figures["gross_pct"] is None
202 else f"{figures['gross_pct']}%")
203 missing = ""
204 if cost <= 0:
205 missing = ('<p class="hint warn">The purchase order carries no cost, '
206 'so this reads as pure profit and is not. Put the vendor\'s '
207 'price on the purchase order lines (or record cost_cents '
208 'on the products) and this page will be right.</p>')
209
210 body = f"""
211<div class="breadcrumb noprint"><a href="/">Home</a> / <a href="/orders">Orders</a> / Margin</div>
212<div class="pagehead"><h1>Margin on {_esc(sale.get('number'))}</h1></div>
213<p class="hint">Drop-shipped by {_esc(purchase.get('customer_name'))} on
214purchase order {_esc(purchase.get('number'))}. This is a read of the two
215orders, never a stored figure.</p>
216<table class="margin-table">
217<thead><tr><th>Line</th><th>Document</th><th class="num">Amount</th><th>Source</th></tr></thead>
218<tbody>
219<tr><td>Revenue</td><td>{_esc(sale.get('number'))}</td><td class="num">{_esc(_money(revenue, currency))}</td><td>{_esc(revenue_source)}</td></tr>
220<tr><td>Cost</td><td>{_esc(purchase.get('number'))}</td><td class="num">{_esc(_money(cost, currency))}</td><td>{_esc(cost_source)}</td></tr>
221<tr><td><strong>Gross</strong></td><td></td><td class="num"><strong>{_esc(_money(figures['gross_minor'], currency))}</strong></td><td>{_esc(pct)}</td></tr>
222</tbody>
223</table>
224{missing}
225"""
226 return {"content_type": "text/html; charset=utf-8",
227 "body": _page(f"Margin on {_text(sale.get('number'))}", body,
228 user_id, path),
229 "margin": figures,
230 "currency": currency,
231 "sale_order_id": sale["id"],
232 "purchase_order_id": purchase["id"],
233 "revenue_source": revenue_source,
234 "cost_source": cost_source}