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
disputes.py · 9.1 KB · 207 lines
1"""Pre-write hook for disputes: a dispute may not be resolved unless it
2names a resolution, and the name has to resolve.
3
4This is the one rule the whole package exists for, and it is a GATE
5rather than a convention on purpose. A convention is a sentence in a
6docstring that a busy Friday afternoon overrules; a gate is the reason
7the sentence stays true. What it prevents is specific and expensive: a
8dispute moved to `resolved` with nothing behind it, which is how a
9customer gets told "it's sorted" when no money went back, no parcel was
10raised, and nobody wrote down why not. Every part of that failure is
11invisible afterwards -- the row looks finished, the queue count goes
12down, and the only person who knows is the customer who is still
13waiting.
14
15Three checks, in the order they matter.
16
17**A resolution has to be NAMED.** status `resolved` with a blank
18resolution_kind is refused. There is no default and there deliberately
19cannot be one: guessing `no_action` would close claims nobody decided
20and guessing `refund` would claim money moved.
21
22**`no_action` has to say WHY.** It is a legitimate ending -- a claim
23outside the return window, a carrier delay nobody owes for, a parcel the
24customer found behind the bins -- and pretending otherwise would push
25operators into fake refunds to escape a gate. But "we are not
26compensating this" is a decision somebody will be asked to justify
27weeks later, usually by the customer and occasionally by a card
28processor, so it carries a sentence in resolution_note or it is not a
29decision, it is a cleared queue.
30
31**refund / replacement / credit have to point at a REAL record.** Each
32kind implies exactly one collection -- refund -> refunds, replacement ->
33orders, credit -> wallet_entries -- and the reference is parsed,
34checked against that collection, and looked up. A reference to the wrong
35collection is refused by name, and so is one naming a row that does not
36exist, because a plausible-looking pointer at nothing is strictly worse
37than a blank field: a blank field is visibly unfinished and
38`refunds/abc123` reads as done. Both refusals carry the ref, the
39collection it should have been, and the collection it actually named --
40"no" alone leaves somebody guessing which half they got wrong.
41
42Fail closed, the way every gate in this house does: a collection that
43cannot be read at all refuses the resolution rather than waving it
44through, because a gate that passes on error is not a gate. The one
45exception is a collection that does not EXIST -- wallet_entries on a
46server with no app-billing -- which is refused too, with a message
47naming the missing app, because a credit nobody can issue is not a
48resolution either.
49
50Trusted server-side writes bypass hooks by design
51(docs/validation-and-logic.md), so action_resolve_dispute carries the
52same three checks itself and reports them the friendly way. That
53duplication is deliberate and named in both files: the hook guards the
54generic HTTP write path a form or an API client uses, the action guards
55the one door that also composes the compensating record, and removing
56either opens the other's. app-receiving's hook/action pair says the same
57thing about over-receiving; this is the same shape.
58"""
59
60import os
61
62import object_collections
63import object_records
64
65RESOLVED = "resolved"
66
67# Each ending implies exactly one collection. The map IS the rule: a
68# refund that points at an order and a replacement that points at a
69# refund are both stories about something that did not happen.
70RESOLUTION_COLLECTIONS = {
71 "refund": "refunds",
72 "replacement": "orders",
73 "credit": "wallet_entries",
74}
75
76# Endings that need a record behind them, versus the one that needs a
77# sentence.
78NEEDS_A_RECORD = tuple(RESOLUTION_COLLECTIONS)
79NEEDS_A_REASON = "no_action"
80
81RESOLUTION_KINDS = NEEDS_A_RECORD + (NEEDS_A_REASON,)
82
83
84def _base_dir():
85 return os.environ.get("DBBASIC_DATA_DIR", "data")
86
87
88def _text(value):
89 return str(value if value is not None else "").strip()
90
91
92def _split_ref(ref):
93 """'refunds/abc' -> ('refunds', 'abc'). Anything else -> ('', '').
94
95 Split once from the left so an id containing a slash still round-trips
96 rather than being silently truncated into a different id.
97 """
98 if "/" not in ref:
99 return "", ""
100 collection, _, record_id = ref.partition("/")
101 return _text(collection), _text(record_id)
102
103
104def check_resolution(record, *, base_dir=None):
105 """The gate itself, as a function, so action_resolve_dispute can hold
106 the identical rule without a second vocabulary for it.
107
108 Returns a refusal dict ({"error", "status"}) or None.
109 """
110 base = base_dir or _base_dir()
111 dispute_id = _text(record.get("id")) or "(new)"
112 kind = _text(record.get("resolution_kind"))
113
114 if not kind:
115 return {"error": (
116 f"Dispute {dispute_id} cannot be resolved without saying HOW. "
117 f"Name a resolution_kind -- one of "
118 f"{', '.join(RESOLUTION_KINDS)} -- because a dispute closed "
119 f"with nothing behind it is how a customer gets told it is "
120 f"sorted when nothing happened."), "status": 400}
121
122 if kind not in RESOLUTION_KINDS:
123 return {"error": (
124 f"Unknown resolution_kind {kind!r} on dispute {dispute_id}; "
125 f"expected one of {', '.join(RESOLUTION_KINDS)}."), "status": 400}
126
127 if kind == NEEDS_A_REASON:
128 if not _text(record.get("resolution_note")):
129 return {"error": (
130 f"Dispute {dispute_id} is being resolved as no_action with "
131 f"no reason. That is a legitimate ending -- plenty of "
132 f"claims are not ours to compensate -- but it needs a "
133 f"sentence in resolution_note, because 'we are not paying "
134 f"this' is a decision somebody will be asked to justify "
135 f"weeks later, and a bare no_action is indistinguishable "
136 f"from a queue somebody cleared to make the number go "
137 f"down."), "status": 400}
138 return None
139
140 expected = RESOLUTION_COLLECTIONS[kind]
141 ref = _text(record.get("resolution_ref"))
142 if not ref:
143 return {"error": (
144 f"Dispute {dispute_id} is being resolved as {kind} with no "
145 f"resolution_ref. A {kind} resolution has to name the record "
146 f"that carries it -- '{expected}/{{id}}' -- because the "
147 f"promise to the customer is that something exists, and this "
148 f"field is the only place that can be checked."),
149 "status": 400}
150
151 named, record_id = _split_ref(ref)
152 if not named or not record_id:
153 return {"error": (
154 f"resolution_ref {ref!r} on dispute {dispute_id} is not a "
155 f"reference. It has to read '{expected}/{{id}}' so the record "
156 f"behind it can actually be looked up; a bare id names a row "
157 f"in no particular collection."), "status": 400}
158
159 if named != expected:
160 return {"error": (
161 f"Dispute {dispute_id} says {kind} but points at "
162 f"{named}/{record_id}. A {kind} resolution lives in "
163 f"{expected}, and a pointer into the wrong collection is a "
164 f"story about something that did not happen: refunds hold "
165 f"money that went back, orders hold goods that will go out, "
166 f"wallet_entries hold credit somebody can spend."),
167 "status": 409}
168
169 try:
170 object_records.get_collection_record(expected, record_id,
171 base_dir=base)
172 except object_collections.CollectionNotFoundError:
173 return {"error": (
174 f"Dispute {dispute_id} cannot be resolved as {kind}: there is "
175 f"no {expected} collection on this server, so "
176 f"{ref} names nothing. A credit needs app-billing installed; "
177 f"a refund needs app-payments. Resolve it a way this server "
178 f"can actually carry out, or say no_action and why."),
179 "status": 409}
180 except object_records.RecordNotFoundError:
181 return {"error": (
182 f"resolution_ref {ref} on dispute {dispute_id} names no record "
183 f"in {expected}. A dispute is only resolved when something "
184 f"real happened, and a pointer at a row that does not exist "
185 f"reads as done while nothing has: check the id, or resolve it "
186 f"as no_action and say why."), "status": 409}
187 except Exception:
188 return {"error": (
189 f"Dispute {dispute_id} names {ref} and {expected} could not be "
190 f"read, so this resolution cannot be verified. Refusing rather "
191 f"than closing a dispute against a record nobody can confirm "
192 f"exists."), "status": 503}
193
194 return None
195
196
197def BEFORE_WRITE(request):
198 action = _text(request.get("action"))
199 if action not in ("create", "update"):
200 return None
201 record = request.get("record") or {}
202 if _text(record.get("status")) != RESOLVED:
203 # Every other status is somebody's work in progress and this hook
204 # has no opinion about it. The gate is on the ENDING, because the
205 # ending is the thing the customer is told about.
206 return None
207 return check_resolution(record)