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
dropship_margin.py · 8.9 KB · 222 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"""
46
47import html
48import os
49
50import object_billing
51import object_records
52
53
54def _base_dir():
55 return os.environ.get("DBBASIC_DATA_DIR", "data")
56
57
58def _text(value):
59 return str(value if value is not None else "").strip()
60
61
62def _esc(value):
63 return html.escape(_text(value))
64
65
66def _cents(value):
67 try:
68 return int(_text(value) or "0")
69 except ValueError:
70 return 0
71
72
73def _money(minor, currency="USD"):
74 sign = "-" if minor < 0 else ""
75 return f"{sign}{abs(minor) // 100}.{abs(minor) % 100:02d} {currency}"
76
77
78_STYLE = """
79.margin-table { width: 100%; border-collapse: collapse; margin: 0.5rem 0 1.5rem; }
80.margin-table th, .margin-table td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
81.margin-table td.num, .margin-table th.num { text-align: right; }
82.hint { color: var(--muted, #999); font-size: 0.9rem; }
83.warn { color: var(--warn, #d08a2a); }
84"""
85
86
87def _totals(base, order):
88 """(amount_minor, source) for one order.
89
90 The stamped total first -- it is the document's own number -- and the
91 lines folded only when it is zero, because the stamp is a reaction
92 that may not have landed yet.
93 """
94 stamped = _cents(order.get("total_cents"))
95 if stamped:
96 return stamped, "stamped"
97 try:
98 lines = object_records.read_collection_records("order_lines",
99 base_dir=base)
100 except Exception:
101 return 0, "unknown"
102 folded = 0
103 for line in lines:
104 if _text(line.get("order_id")) != order["id"]:
105 continue
106 folded += _cents(line.get("line_total_cents"))
107 folded += _cents(line.get("line_tax_cents"))
108 return folded, "folded" if folded else "empty"
109
110
111def _page(title, body, user_id, path):
112 who = (f"signed in as <strong>{_esc(user_id)}</strong>" if user_id
113 else f'<a href="/login?next={_esc(path)}">sign in</a>')
114 return f"""<!doctype html>
115<html lang="en">
116<head>
117<meta charset="utf-8">
118<meta name="viewport" content="width=device-width, initial-scale=1">
119<title>{_esc(title)}</title>
120<link rel="stylesheet" href="/style">
121<style>{_STYLE}</style>
122</head>
123<body>
124<div class="wrap">
125<header class="app"><h1><a href="/">DBBASIC</a></h1><div class="who">{who}</div></header>
126{body}
127</div>
128<script src="/nav"></script>
129</body>
130</html>"""
131
132
133def GET(request):
134 base = _base_dir()
135 identity = request.get("_identity") or {}
136 user_id = _text(identity.get("user_id"))
137 order_id = _text(request.get("order_id"))
138 path = f"/orders/{order_id}/margin"
139
140 if not user_id:
141 return {"content_type": "text/html; charset=utf-8",
142 "body": _page("Margin",
143 '<p class="hint">Margin is a number about '
144 'somebody\'s business. Please sign in.</p>',
145 user_id, path)}
146
147 try:
148 order = object_records.get_collection_record("orders", order_id,
149 base_dir=base)
150 except Exception:
151 return {"status": 404, "content_type": "text/html; charset=utf-8",
152 "body": _page("Margin",
153 '<p class="hint">No such order.</p>',
154 user_id, path)}
155
156 linked_id = _text(order.get("linked_order_id"))
157 linked = {}
158 if linked_id:
159 try:
160 linked = object_records.get_collection_record("orders", linked_id,
161 base_dir=base)
162 except Exception:
163 linked = {}
164
165 if not linked:
166 body = (f'<div class="pagehead"><h1>Margin</h1></div>'
167 f'<p class="hint">Order {_esc(order.get("number"))} is not '
168 f'part of a drop-ship pair, so there is no vendor cost to '
169 f'set against it. Margin here is the difference between what '
170 f'the customer paid on one order and what the vendor charged '
171 f'on the other; an order fulfilled from our own shelf needs '
172 f'inventory valuation instead, which this server does not do '
173 f'yet (see tests/test_cogs_on_sale.py).</p>')
174 return {"status": 409, "content_type": "text/html; charset=utf-8",
175 "body": _page("Margin", body, user_id, path)}
176
177 # Which of the two is the sale is a question of doc_type, never of
178 # which one the URL happened to name.
179 if _text(order.get("doc_type")) == "purchase":
180 sale, purchase = linked, order
181 else:
182 sale, purchase = order, linked
183
184 currency = _text(sale.get("currency")) or "USD"
185 revenue, revenue_source = _totals(base, sale)
186 cost, cost_source = _totals(base, purchase)
187 figures = object_billing.margin(revenue, cost)
188
189 pct = ("n/a" if figures["gross_pct"] is None
190 else f"{figures['gross_pct']}%")
191 missing = ""
192 if cost <= 0:
193 missing = ('<p class="hint warn">The purchase order carries no cost, '
194 'so this reads as pure profit and is not. Put the vendor\'s '
195 'price on the purchase order lines (or record cost_cents '
196 'on the products) and this page will be right.</p>')
197
198 body = f"""
199<div class="breadcrumb noprint"><a href="/">Home</a> / <a href="/orders">Orders</a> / Margin</div>
200<div class="pagehead"><h1>Margin on {_esc(sale.get('number'))}</h1></div>
201<p class="hint">Drop-shipped by {_esc(purchase.get('customer_name'))} on
202purchase order {_esc(purchase.get('number'))}. This is a read of the two
203orders, never a stored figure.</p>
204<table class="margin-table">
205<thead><tr><th>Line</th><th>Document</th><th class="num">Amount</th><th>Source</th></tr></thead>
206<tbody>
207<tr><td>Revenue</td><td>{_esc(sale.get('number'))}</td><td class="num">{_esc(_money(revenue, currency))}</td><td>{_esc(revenue_source)}</td></tr>
208<tr><td>Cost</td><td>{_esc(purchase.get('number'))}</td><td class="num">{_esc(_money(cost, currency))}</td><td>{_esc(cost_source)}</td></tr>
209<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>
210</tbody>
211</table>
212{missing}
213"""
214 return {"content_type": "text/html; charset=utf-8",
215 "body": _page(f"Margin on {_text(sale.get('number'))}", body,
216 user_id, path),
217 "margin": figures,
218 "currency": currency,
219 "sale_order_id": sale["id"],
220 "purchase_order_id": purchase["id"],
221 "revenue_source": revenue_source,
222 "cost_source": cost_source}