Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/tests/test_billing_runner.py
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
test_billing_runner.py · 8.5 KB · 210 lines
1"""The period biller: decide money is owed, say so exactly once.
2
3Double-billing is the failure customers never forgive, so the property
4under test hardest here is idempotency -- a biller re-run after a crash,
5or simply run twice in a day, must raise nothing the second time. The
6other half is the status ladder, which has to climb in BOTH directions:
7a ladder that only descends leaves a customer who just paid still cut
8off.
9"""
10
11import pathlib
12
13from conftest import stage_collection
14
15import object_execution
16import object_records
17import python_object_runtime
18
19REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
20PACKAGES = REPO_ROOT / "packages"
21BILLING_OBJECTS = PACKAGES / "app-billing" / "objects"
22RUNTIME = python_object_runtime.PythonObjectRuntime()
23
24
25def setup_env(tmp_path, monkeypatch, *, settings=()):
26 data_dir = tmp_path / "data"
27 for pkg, name in (("app-billing", "billing_plans"), ("app-billing", "subscriptions"),
28 ("app-billing", "wallets"), ("app-billing", "wallet_entries"),
29 ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"),
30 ("app-finance", "denominations")):
31 stage_collection(data_dir, pkg, name, seed=(name == "denominations"))
32 rows = ""
33 for i, (k, v) in enumerate(settings):
34 rows += f"s{i}\t{k}\t{v}\t\n"
35 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
36 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
37 object_records.create_collection_record(
38 "billing_plans",
39 {"id": "plan-pro", "name": "Pro", "code": "pro", "period": "month",
40 "base_minor": "4900", "is_active": "true", "owner_id": "dan"},
41 base_dir=data_dir)
42 return data_dir
43
44
45def subscribe(data_dir, sid="sub-1", **fields):
46 record = {"id": sid, "customer_name": "Acme Ltd", "customer_email": "a@acme.test",
47 "plan_id": "plan-pro", "billing_mode": "subscription", "status": "active",
48 "current_period_start": "2026-06-01", "current_period_end": "2026-06-30",
49 "owner_id": "dan"}
50 record.update(fields)
51 return object_records.create_collection_record(
52 "subscriptions", record, base_dir=data_dir)
53
54
55def run(payload=None):
56 return object_execution.execute_object(
57 RUNTIME,
58 object_execution.ObjectExecutionRequest(
59 "system_billing_runner", method="POST", payload=payload or {}),
60 roots=[BILLING_OBJECTS]).result
61
62
63def invoices(data_dir):
64 return object_records.read_collection_records("invoices", base_dir=data_dir)
65
66
67def sub(data_dir, sid="sub-1"):
68 return object_records.get_collection_record("subscriptions", sid, base_dir=data_dir)
69
70
71# --- raising the invoice --------------------------------------------------------
72
73def test_a_closed_period_raises_one_invoice_and_advances(tmp_path, monkeypatch):
74 data_dir = setup_env(tmp_path, monkeypatch)
75 subscribe(data_dir)
76 result = run({"today": "2026-07-01"})
77 assert result["invoiced"] == 1 and result["advanced"] == 1
78
79 rows = invoices(data_dir)
80 assert len(rows) == 1
81 assert rows[0]["total_cents"] == "4900"
82 assert rows[0]["status"] == "sent"
83 assert rows[0]["customer_email"] == "a@acme.test"
84
85 lines = object_records.read_collection_records("invoice_lines", base_dir=data_dir)
86 assert len(lines) == 1 and lines[0]["line_total_cents"] == "4900"
87 assert "2026-06-01" in lines[0]["description"] # the period it covers
88
89 moved = sub(data_dir)
90 assert moved["current_period_start"] == "2026-06-30"
91 assert moved["current_period_end"] == "2026-07-30"
92
93
94def test_running_twice_never_double_bills(tmp_path, monkeypatch):
95 """The property customers never forgive us for getting wrong."""
96 data_dir = setup_env(tmp_path, monkeypatch)
97 subscribe(data_dir)
98 run({"today": "2026-07-01"})
99 # Re-run the SAME day (a crashed pass, a manual retry, a double cron).
100 again = run({"today": "2026-07-01"})
101 assert again["invoiced"] == 0
102 assert len(invoices(data_dir)) == 1
103
104
105def test_a_period_still_open_bills_nothing(tmp_path, monkeypatch):
106 data_dir = setup_env(tmp_path, monkeypatch)
107 subscribe(data_dir)
108 result = run({"today": "2026-06-15"})
109 assert result["invoiced"] == 0 and invoices(data_dir) == []
110
111
112def test_wallet_mode_gets_no_periodic_invoice(tmp_path, monkeypatch):
113 """Its money already moved when the usage did; invoicing again would
114 charge twice for one thing."""
115 data_dir = setup_env(tmp_path, monkeypatch)
116 subscribe(data_dir, billing_mode="wallet")
117 result = run({"today": "2026-07-01"})
118 assert result["invoiced"] == 0 and invoices(data_dir) == []
119
120
121def test_dry_run_says_what_it_would_do_and_writes_nothing(tmp_path, monkeypatch):
122 data_dir = setup_env(tmp_path, monkeypatch)
123 subscribe(data_dir)
124 result = run({"today": "2026-07-01", "dry_run": "true"})
125 assert invoices(data_dir) == []
126 assert any(r.get("would_invoice_period") for r in result["results"])
127 assert sub(data_dir)["current_period_end"] == "2026-06-30" # unmoved
128
129
130def test_month_end_clamps_instead_of_skipping_a_cycle(tmp_path, monkeypatch):
131 """A 31st subscriber must not skip February."""
132 data_dir = setup_env(tmp_path, monkeypatch)
133 subscribe(data_dir, current_period_start="2026-12-31",
134 current_period_end="2027-01-31")
135 run({"today": "2027-02-01"})
136 assert sub(data_dir)["current_period_end"] == "2027-02-28"
137
138
139# --- the ladder -----------------------------------------------------------------
140
141def test_a_trial_ends_into_active(tmp_path, monkeypatch):
142 data_dir = setup_env(tmp_path, monkeypatch)
143 subscribe(data_dir, status="trialing", trial_ends_on="2026-06-20",
144 current_period_end="2026-12-31")
145 run({"today": "2026-07-01"})
146 assert sub(data_dir)["status"] == "active"
147
148
149def test_unpaid_invoices_walk_active_to_past_due_to_suspended(tmp_path, monkeypatch):
150 data_dir = setup_env(tmp_path, monkeypatch,
151 settings=(("billing.past_due_grace_days", "7"),
152 ("billing.suspend_after_days", "30")))
153 subscribe(data_dir)
154 run({"today": "2026-07-01"}) # raises the invoice, due +14d
155 assert sub(data_dir)["status"] == "active"
156
157 # A week past due: still active (inside grace).
158 run({"today": "2026-07-20"})
159 assert sub(data_dir)["status"] == "active"
160 # Two weeks past due: past_due.
161 run({"today": "2026-07-30"})
162 assert sub(data_dir)["status"] == "past_due"
163 # Well past: suspended.
164 run({"today": "2026-09-01"})
165 assert sub(data_dir)["status"] == "suspended"
166
167
168def test_paying_lets_the_ladder_be_climbed_back(tmp_path, monkeypatch):
169 """A ladder that only descends leaves a paying customer cut off."""
170 data_dir = setup_env(tmp_path, monkeypatch,
171 settings=(("billing.past_due_grace_days", "7"),))
172 subscribe(data_dir)
173 run({"today": "2026-07-01"})
174 run({"today": "2026-07-30"})
175 assert sub(data_dir)["status"] == "past_due"
176
177 for row in invoices(data_dir):
178 object_records.update_collection_record(
179 "invoices", row["id"], {"status": "paid"}, base_dir=data_dir, actor="dan")
180 # Nothing is overdue now, so the runner stops pushing it down; the
181 # transition table allows past_due -> active for the operator.
182 result = run({"today": "2026-08-01"})
183 assert not any("suspended" in str(r) for r in result["results"])
184 object_records.update_collection_record(
185 "subscriptions", "sub-1", {"status": "active"}, base_dir=data_dir, actor="dan")
186 assert sub(data_dir)["status"] == "active"
187
188
189def test_cancel_at_period_end_bills_the_last_period_then_stops(tmp_path, monkeypatch):
190 """Service runs to the end of the period already paid for -- cutting it
191 off at the click would bill for time the customer cannot use."""
192 data_dir = setup_env(tmp_path, monkeypatch)
193 subscribe(data_dir, cancel_at_period_end="true")
194 result = run({"today": "2026-07-01"})
195 assert result["invoiced"] == 1 # the period served IS billed
196 assert sub(data_dir)["status"] == "canceled"
197 assert run({"today": "2026-08-01"})["invoiced"] == 0 # and never again
198
199
200def test_canceled_subscriptions_are_left_entirely_alone(tmp_path, monkeypatch):
201 data_dir = setup_env(tmp_path, monkeypatch)
202 subscribe(data_dir, status="canceled")
203 assert run({"today": "2026-07-01"})["invoiced"] == 0
204
205
206def test_billing_not_installed_is_a_graceful_skip(tmp_path, monkeypatch):
207 data_dir = tmp_path / "data"
208 data_dir.mkdir()
209 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
210 assert run()["skipped"].startswith("billing not installed")