@jskit-ai/payments-core 0.2.57 → 0.2.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `revokeGrant(scope, { reference })` takes a grant back, as a store refund does: what is left is removed, the spent part comes out of the subject's other credits, and the rest becomes a deficit that `inspect().balance` shows as negative and later grants pay off first; debits are refused meanwhile. `applyStoreSubscription(scope, { id, planId, status, periodEnd, reference })` sets an App Store or Google Play subscription's state beside web subscriptions (`active` and `grace` grant the plan's features). The account state keeps the deficit in its JSON document, so no migration is needed.
5
6
  - Prepaid top-ups. `extensions.payments.topUps` (`name`, `currency`, `minimumAmount`, `maximumAmount`, amounts in the currency's smallest unit, Stripe's floor of 50) sells one-off Stripe Checkout payments of an amount the person chooses; `plans` may be empty only beside it. A Paddle connection with top-ups fails validation at its `integrationId` (`payments.configuration.paddleTopUps`), and an inverted range at `topUps/maximumAmount` (`payments.configuration.topUpRange`). `createPaymentCheckoutService` takes `topUps: { offer, credit }` and gains `topUp({actor, subjectId, amount, requestId, email?, description?})` and `confirmTopUp({actor, subjectId, topUpId})`, both authorized as action `topUp`; its `webhook` settles the four `checkout.session.*` top-up events. The verified webhook and the return page's confirmation (which reads the session from Stripe with the server's key) settle through one path: under the top-up's row lock, only the move to paid calls the application's `credit({reference, subjectId, amount, currency}, options)` inside the same transaction, so a top-up is credited once whichever door reports it first. The subject comes from the top-up written down at checkout, never from the event. New table `payment_top_ups` (migration `payments_core_top_ups.cjs`, in the payment tables' collation on MySQL and MariaDB); the store gains `createTopUp`, `inspectTopUp` and `withTopUp`. `TOP_UP_RETURN_PARAMETER` (`"paymentTopUp"`) is exported from `@jskit-ai/payments-core/shared/topUps`.
6
7
  - **Breaking:** `createStripePaymentAdapter` requires `appEnv` (`appEnvironment(env)`) and refuses a live key (`sk_live_`, `rk_live_`) unless it is `production`, with `payment_live_key_refused` (409); test keys work everywhere. It takes `apiBaseUrl`, a stand-in for Stripe's API, in development and tests only (`payment_stand_in_refused`, 409, elsewhere).
7
8
  - `PaymentError` takes `cause` in its options; a provider failure while starting or confirming a top-up is `payment_provider_unavailable` (502) with the provider's error as its cause.
package/docs/contract.md CHANGED
@@ -195,3 +195,21 @@ carries `messageCode` and `messageParams` naming a `jskit.payments.*` message,
195
195
  and binding field errors carry `code` and `params`, so a JSKIT application can
196
196
  show them in the user's language. Other implementations may ignore these
197
197
  fields.
198
+
199
+ ## Store purchases
200
+
201
+ `@jskit-ai/store-purchases-core` grants App Store and Google Play purchases into the same accounts, so a subject has
202
+ one balance and one access check whatever it bought through.
203
+
204
+ - A store credit pack calls `grantCredits(scope, { reference: "store:<source>:<transactionId>", units })`, with the
205
+ units its product declares: the same units as its web counterpart.
206
+ - A store subscription calls `applyStoreSubscription(scope, { id, planId, status, periodEnd, reference })` once per
207
+ store event. `active` and `grace` (the store's billing retry period) grant the plan's features until `periodEnd`;
208
+ `expired` and `revoked` grant none. It sits beside web subscriptions in `inspect().subscriptions` as
209
+ `store:<id>`.
210
+ - A store refund or revocation calls `revokeGrant(scope, { reference })`, once per grant. What is left of the grant is
211
+ removed; the part already spent comes out of the subject's other unexpired credits, soonest expiring first; what they
212
+ cannot cover becomes a deficit. `inspect().balance` shows the deficit as a negative number, the next grants pay it
213
+ off before adding credits, and every debit is refused while the balance is not above zero. The application decides
214
+ what else follows a negative balance.
215
+
package/locales/en.json CHANGED
@@ -84,6 +84,12 @@
84
84
  "recoveryReviewChanged": "The recovery review changed. Inspect the current pending operation first.",
85
85
  "pendingRequestChanged": "The pending request changed.",
86
86
  "objectMismatch": "The provider object does not match the pending operation."
87
+ },
88
+ "grant": {
89
+ "missing": "No grant exists for this reference."
90
+ },
91
+ "store": {
92
+ "subscriptionInvalid": "Check the store subscription's plan and state."
87
93
  }
88
94
  }
89
95
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/payments-core",
3
- "version": "0.2.57",
3
+ "version": "0.2.59",
4
4
  "type": "module",
5
5
  "description": "Application-owned payment configuration, subscription access, prepaid top-ups and transactional usage credits.",
6
6
  "exports": {
@@ -24,7 +24,7 @@
24
24
  "test": "jskit test"
25
25
  },
26
26
  "dependencies": {
27
- "@jskit-ai/resource-core": "0.1.231",
27
+ "@jskit-ai/resource-core": "0.1.233",
28
28
  "@paddle/paddle-node-sdk": "3.10.0",
29
29
  "ajv": "8.20.0",
30
30
  "stripe": "22.6.2"
@@ -73,9 +73,9 @@
73
73
  }
74
74
  },
75
75
  "peerDependencies": {
76
- "@jskit-ai/database-runtime": "0.1.298",
77
- "@jskit-ai/kernel": "0.2.40",
78
- "@jskit-ai/resource-runtime": "0.2.65"
76
+ "@jskit-ai/database-runtime": "0.1.300",
77
+ "@jskit-ai/kernel": "0.2.42",
78
+ "@jskit-ai/resource-runtime": "0.2.67"
79
79
  },
80
80
  "peerDependenciesMeta": {
81
81
  "@jskit-ai/database-runtime": {
@@ -15,6 +15,21 @@ function timestamp(value) {
15
15
  }
16
16
  const unexpired = (lot, now) => lot.expiresAt === null || lot.expiresAt > now;
17
17
  const available = (lots, now) => lots.reduce((sum, lot) => sum + (unexpired(lot, now) ? lot.remaining : 0), 0);
18
+ // Credits a refunded grant took back after they were spent: the balance shows them as negative, and later grants pay
19
+ // them off first. While there is a deficit no unexpired credits remain, so every debit is refused.
20
+ const deficitOf = (state) => Number(state.deficit || 0);
21
+
22
+ /** Takes `quantity` from the unexpired lots, soonest expiring first; answers what it could not take. */
23
+ function takeFromLots(lots, quantity, now) {
24
+ let remaining = quantity;
25
+ for (const lot of lots.filter((item) => unexpired(item, now)).sort((a, b) => (a.expiresAt ?? Infinity) - (b.expiresAt ?? Infinity))) {
26
+ const taken = Math.min(remaining, lot.remaining);
27
+ lot.remaining -= taken;
28
+ remaining -= taken;
29
+ if (!remaining) break;
30
+ }
31
+ return remaining;
32
+ }
18
33
 
19
34
  async function once(tx, key, input, work) {
20
35
  const digest = fingerprint(input);
@@ -34,8 +49,10 @@ async function grant(tx, { reference: id, units: quantity, expiresAt }, now) {
34
49
  return once(tx, `grant:${id}`, [quantity, expiresAt], async () => {
35
50
  if (!Number.isSafeInteger(available(tx.state.lots, now) + quantity)) fail("payment_balance_limit", "Credit balance exceeds the supported integer range.");
36
51
  tx.state.lots = tx.state.lots.filter((lot) => unexpired(lot, now));
37
- tx.state.lots.push({ id, remaining: quantity, expiresAt });
38
- return { granted: quantity, expiresAt };
52
+ const paidOff = Math.min(deficitOf(tx.state), quantity);
53
+ tx.state.deficit = deficitOf(tx.state) - paidOff;
54
+ tx.state.lots.push({ id, remaining: quantity - paidOff, expiresAt });
55
+ return { granted: quantity, expiresAt, ...(paidOff ? { paidOff } : {}) };
39
56
  });
40
57
  }
41
58
 
@@ -77,7 +94,7 @@ function createPaymentService({ store, configuration, clock = Date.now }) {
77
94
  const features = [...new Set(subscriptions.filter((subscription) =>
78
95
  subscription.status === "active" && subscription.periodEnd > now && plans[subscription.planId])
79
96
  .flatMap((subscription) => plans[subscription.planId].features))];
80
- return { balance: available(state.lots, now), features, subscriptions };
97
+ return { balance: available(state.lots, now) - deficitOf(state), features, subscriptions };
81
98
  }
82
99
 
83
100
  async function requireFeature(scope, feature) {
@@ -130,6 +147,53 @@ function createPaymentService({ store, configuration, clock = Date.now }) {
130
147
  }));
131
148
  }
132
149
 
150
+ /**
151
+ * Takes a grant back, as a store refund or revocation does: what is left of it is removed, the part already spent
152
+ * comes out of the subject's other credits, and what they cannot cover becomes a deficit, shown as a negative
153
+ * balance and paid off first by later grants. Once per grant.
154
+ * @param {object} scope
155
+ * @param {{ reference: string }} input The grant's own reference.
156
+ */
157
+ async function revokeGrant(scope, { reference: id }) {
158
+ checkScope(scope);
159
+ reference(id);
160
+ return store.withAccount(scope, (tx) => once(tx, `revoke:${id}`, [id], async () => {
161
+ const granted = await tx.find(`grant:${id}`);
162
+ if (!granted) fail("payment_grant_missing", "No grant exists for this reference.", 404, { messageCode: "payments.grant.missing" });
163
+ const now = timestamp(clock());
164
+ const total = granted.result.granted;
165
+ const lot = tx.state.lots.find((item) => item.id === id);
166
+ const removed = lot ? lot.remaining : 0;
167
+ tx.state.lots = tx.state.lots.filter((item) => item.id !== id);
168
+ const uncovered = takeFromLots(tx.state.lots, total - removed - Number(granted.result.paidOff || 0), now);
169
+ tx.state.deficit = deficitOf(tx.state) + uncovered;
170
+ return { revoked: total, removed, deficit: uncovered, balance: available(tx.state.lots, now) - deficitOf(tx.state) };
171
+ }));
172
+ }
173
+
174
+ /**
175
+ * Sets a store subscription's state from the store's own renewal facts, once per store event: "active" and "grace"
176
+ * (the store's billing retry period) grant the plan's features until `periodEnd`; "expired" and "revoked" grant none.
177
+ * Web and store subscriptions of a subject combine in `inspect`.
178
+ * @param {object} scope
179
+ * @param {{ id: string, planId: string, status: "active" | "grace" | "expired" | "revoked", periodEnd: number, reference: string }} input
180
+ */
181
+ async function applyStoreSubscription(scope, { id, planId, status, periodEnd, reference: eventId }) {
182
+ checkScope(scope);
183
+ reference(id);
184
+ reference(eventId);
185
+ timestamp(periodEnd);
186
+ if (!["active", "grace", "expired", "revoked"].includes(status) || !Object.hasOwn(plans, planId)) {
187
+ fail("payment_provider_result_invalid", "Check the store subscription's plan and state.", 502, { messageCode: "payments.store.subscriptionInvalid" });
188
+ }
189
+ return store.withAccount(scope, (tx) => once(tx, `store-event:${eventId}`, [id, planId, status, periodEnd], async () => {
190
+ const key = `store:${id}`;
191
+ const granting = status === "active" || status === "grace";
192
+ tx.state.subscriptions[key] = { id: key, status: granting ? "active" : "canceled", planId, periodEnd, source: "store", storeStatus: status };
193
+ return { subscriptionId: key, status };
194
+ }));
195
+ }
196
+
133
197
  // Called only after provider signature/account verification. Resolve customer
134
198
  // from a server-created binding; never use a subject ID from webhook metadata.
135
199
  // Load fresh provider facts under the account lock, so reordered events cannot
@@ -170,6 +234,8 @@ function createPaymentService({ store, configuration, clock = Date.now }) {
170
234
  grantCredits,
171
235
  debitCredits,
172
236
  refundDebit,
237
+ revokeGrant,
238
+ applyStoreSubscription,
173
239
  reconcileEvent
174
240
  });
175
241
  }
@@ -1,7 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import knexLib from "knex";
4
- import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
3
+ import { createPackageTestKnex, requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
5
4
  import { migratePayments } from "./support/migrations.js";
6
5
  import { createPaymentService } from "../src/server/service.js";
7
6
  import { validatePaymentConfiguration } from "../src/shared/configuration.js";
@@ -14,22 +13,10 @@ import { createTestPaymentStore } from "./support/paymentStore.js";
14
13
  // that work on one account or catalogue runs one at a time and rolls back as a whole, its row's creation included; and
15
14
  // the errors it gives.
16
15
 
17
- // The runtime's own MySQL connection settings (database-runtime's resolveKnexConnectionFromEnvironment).
18
- const RUNTIME_MYSQL = Object.freeze({ supportBigNumbers: true, bigNumberStrings: true, dateStrings: ["DATE"], timezone: "Z" });
19
-
20
- /** A migrated database of the test's own, beside TEST_DB_NAME, dropped after the test. */
21
- async function ownDatabase(context, suffix) {
22
- const name = `${requireTestDatabase(process.env)}_${suffix}`;
23
- const server = { host: process.env.DB_HOST, port: Number(process.env.DB_PORT) || 3306, user: process.env.DB_USER, password: process.env.DB_PASSWORD };
24
- const admin = knexLib({ client: "mysql2", connection: server, pool: { min: 0, max: 1 } });
25
- await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
26
- await admin.raw("CREATE DATABASE ??", [name]);
27
- const knex = knexLib({ client: "mysql2", connection: { ...server, database: name, ...RUNTIME_MYSQL }, pool: { min: 0, max: 6 } });
28
- context.after(async () => {
29
- await knex.destroy();
30
- await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
31
- await admin.destroy();
32
- });
16
+
17
+ /** A lettered copy of TEST_DB_NAME the test claims (createPackageTestKnex() on MySQL), migrated, dropped after the test. */
18
+ async function ownDatabase(context) {
19
+ const knex = await createPackageTestKnex(context, { environment: { ...process.env, DB_CLIENT: "mysql2" } });
33
20
  await migratePayments(knex);
34
21
  return knex;
35
22
  }
@@ -57,7 +44,7 @@ function gate() {
57
44
 
58
45
  test("the payment table resources declare exactly the foreign keys the migration creates", async (context) => {
59
46
  requireTestDatabase(process.env);
60
- const knex = await ownDatabase(context, "da_payments_keys");
47
+ const knex = await ownDatabase(context);
61
48
  const resources = PAYMENT_TABLES.map(({ resource }) => resource);
62
49
  const tables = resources.map((resource) => resource.tableName);
63
50
  assert.deepEqual(await checkForeignKeys({ knex, resources, tables }), { missing: [], undeclared: [] });
@@ -65,7 +52,7 @@ test("the payment table resources declare exactly the foreign keys the migration
65
52
 
66
53
  test("the store refuses incomplete scopes and identities before any work runs", async (context) => {
67
54
  requireTestDatabase(process.env);
68
- const store = await createTestPaymentStore(await ownDatabase(context, "da_pay_refusals"));
55
+ const store = await createTestPaymentStore(await ownDatabase(context));
69
56
  assert.ok(Object.isFrozen(store));
70
57
  assert.deepEqual(Object.keys(store), ["inspect", "withAccount", "bindCustomer", "resolveCustomer", "inspectCatalogue", "withCatalogue", "inspectTopUp", "createTopUp", "withTopUp"]);
71
58
 
@@ -102,7 +89,7 @@ test("the store refuses incomplete scopes and identities before any work runs",
102
89
 
103
90
  test("an account starts empty, keeps the state its work leaves as JSON, and answers what the work returns", async (context) => {
104
91
  requireTestDatabase(process.env);
105
- const store = await createTestPaymentStore(await ownDatabase(context, "da_pay_account"));
92
+ const store = await createTestPaymentStore(await ownDatabase(context));
106
93
  const scope = subject("tenant-a");
107
94
 
108
95
  const fresh = await store.inspect(scope);
@@ -135,7 +122,7 @@ test("an account starts empty, keeps the state its work leaves as JSON, and answ
135
122
 
136
123
  test("entries are recorded once per reference, read back by find, and belong to their own account", async (context) => {
137
124
  requireTestDatabase(process.env);
138
- const store = await createTestPaymentStore(await ownDatabase(context, "da_pay_entries"));
125
+ const store = await createTestPaymentStore(await ownDatabase(context));
139
126
  const scope = subject("tenant-a");
140
127
 
141
128
  await store.withAccount(scope, async ({ find, record }) => {
@@ -173,7 +160,7 @@ test("entries are recorded once per reference, read back by find, and belong to
173
160
 
174
161
  test("work that fails rolls back its state and entries, and its error reaches the caller unchanged", async (context) => {
175
162
  requireTestDatabase(process.env);
176
- const knex = await ownDatabase(context, "da_pay_rollback");
163
+ const knex = await ownDatabase(context);
177
164
  const store = await createTestPaymentStore(knex);
178
165
  const scope = subject("tenant-a");
179
166
  await store.withAccount(scope, async ({ state, record }) => {
@@ -207,7 +194,7 @@ test("work that fails rolls back its state and entries, and its error reaches th
207
194
 
208
195
  test("a reference granted again answers duplicate: true, also when two first grants on a new account race", { timeout: 20_000 }, async (context) => {
209
196
  requireTestDatabase(process.env);
210
- const knex = await ownDatabase(context, "da_pay_duplicate");
197
+ const knex = await ownDatabase(context);
211
198
  const store = await createTestPaymentStore(knex);
212
199
  const configuration = validatePaymentConfiguration({
213
200
  integrations: { billing: { provider: "stripe", accountMode: "shared", authentication: { method: "api-key", secretRef: "env:STRIPE_KEY" } } },
@@ -238,7 +225,7 @@ test("a reference granted again answers duplicate: true, also when two first gra
238
225
 
239
226
  test("the hot path: inspect is one read, and work on an existing account locks it once and writes only a changed state", async (context) => {
240
227
  requireTestDatabase(process.env);
241
- const knex = await ownDatabase(context, "da_pay_statements");
228
+ const knex = await ownDatabase(context);
242
229
  const store = await createTestPaymentStore(knex);
243
230
  const scope = subject("tenant-a");
244
231
  await store.withAccount(scope, async ({ state, record }) => {
@@ -269,7 +256,7 @@ test("the hot path: inspect is one read, and work on an existing account locks i
269
256
 
270
257
  test("work on one account runs one at a time, while other accounts, the catalogue and plain reads go on", { timeout: 20_000 }, async (context) => {
271
258
  requireTestDatabase(process.env);
272
- const store = await createTestPaymentStore(await ownDatabase(context, "da_pay_serial"));
259
+ const store = await createTestPaymentStore(await ownDatabase(context));
273
260
  const scope = subject("tenant-a");
274
261
  const other = subject("tenant-b");
275
262
  await store.withAccount(scope, async ({ state }) => {
@@ -313,7 +300,7 @@ test("work on one account runs one at a time, while other accounts, the catalogu
313
300
 
314
301
  test("a provider customer binds to one subject per merchant: the first binding wins and a different one is refused", { timeout: 20_000 }, async (context) => {
315
302
  requireTestDatabase(process.env);
316
- const store = await createTestPaymentStore(await ownDatabase(context, "da_pay_customers"));
303
+ const store = await createTestPaymentStore(await ownDatabase(context));
317
304
 
318
305
  assert.equal(await store.resolveCustomer(merchant, "cus_1"), null);
319
306
  assert.equal(await store.bindCustomer(merchant, "cus_1", "tenant-a"), undefined);
@@ -353,7 +340,7 @@ test("a provider customer binds to one subject per merchant: the first binding w
353
340
 
354
341
  test("a merchant's catalogue starts empty, keeps what its work leaves, rolls back on failure and is shared by the merchant's subjects", { timeout: 20_000 }, async (context) => {
355
342
  requireTestDatabase(process.env);
356
- const store = await createTestPaymentStore(await ownDatabase(context, "da_pay_catalogue"));
343
+ const store = await createTestPaymentStore(await ownDatabase(context));
357
344
 
358
345
  const fresh = await store.inspectCatalogue(merchant);
359
346
  assert.deepEqual(fresh, EMPTY_CATALOGUE);
@@ -0,0 +1,57 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import knex from "knex";
4
+ import migration from "../migrations/payments_core_initial.cjs";
5
+ import { createTestPaymentStore } from "./support/paymentStore.js";
6
+ import { createPaymentService } from "../src/server/service.js";
7
+ import { validatePaymentConfiguration } from "../src/shared/configuration.js";
8
+
9
+ const document = {
10
+ integrations: { billing: { provider: "stripe", accountMode: "shared", authentication: { method: "api-key", secretRef: "env:STRIPE_KEY" } } },
11
+ extensions: { payments: {
12
+ version: 1,
13
+ environments: { sandbox: { integrationId: "billing", providerAccountId: "acct_test", webhookSecretRef: "env:STRIPE_WEBHOOK_SECRET", returnUrlRef: "env:APP_URL" } },
14
+ plans: { pro: { name: "Pro", amount: 1200, currency: "USD", interval: "month", features: ["export"], renewalCredits: 100 } }
15
+ } }
16
+ };
17
+ const scope = { applicationId: "app", integrationId: "billing", providerAccountId: "acct_test", environment: "sandbox", subjectId: "tenant-a" };
18
+
19
+ async function startService(t) {
20
+ const db = knex({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true, pool: { min: 1, max: 1 } });
21
+ t.after(() => db.destroy());
22
+ await migration.up(db);
23
+ let now = 1000;
24
+ const service = createPaymentService({ store: await createTestPaymentStore(db), configuration: validatePaymentConfiguration(document), clock: () => now });
25
+ return { service, setNow: (value) => { now = value; } };
26
+ }
27
+
28
+ test("taking a grant back removes what is left, takes the spent part from other credits, then leaves a deficit", async (t) => {
29
+ const { service } = await startService(t);
30
+ await service.grantCredits(scope, { reference: "store:app_store:t1", units: 100, expiresAt: null });
31
+ await service.grantCredits(scope, { reference: "web:topup-1", units: 20, expiresAt: null });
32
+ await service.debitCredits(scope, { reference: "use-1", units: 90 });
33
+ assert.equal((await service.inspect(scope)).balance, 30);
34
+
35
+ const revoked = await service.revokeGrant(scope, { reference: "store:app_store:t1" });
36
+ assert.deepEqual({ ...revoked, duplicate: undefined }, { revoked: 100, removed: 10, deficit: 70, balance: -70, duplicate: undefined });
37
+ assert.equal(revoked.duplicate, false);
38
+ assert.equal((await service.inspect(scope)).balance, -70, "the balance shows the deficit as negative");
39
+ assert.equal((await service.revokeGrant(scope, { reference: "store:app_store:t1" })).duplicate, true, "taken back once");
40
+ await assert.rejects(service.debitCredits(scope, { reference: "use-2", units: 1 }), { code: "payment_insufficient_credits" });
41
+
42
+ await service.grantCredits(scope, { reference: "web:topup-2", units: 80, expiresAt: null });
43
+ assert.equal((await service.inspect(scope)).balance, 10, "a later grant pays the deficit off first");
44
+ await assert.rejects(service.revokeGrant(scope, { reference: "never-granted" }), { code: "payment_grant_missing" });
45
+ });
46
+
47
+ test("a store subscription grants its plan's features while active or in grace, and none once expired or revoked", async (t) => {
48
+ const { service } = await startService(t);
49
+ const subscription = { id: "app_store:orig-1", planId: "pro", status: "active", periodEnd: 5000, reference: "store-event-1" };
50
+ assert.equal((await service.applyStoreSubscription(scope, subscription)).duplicate, false);
51
+ assert.deepEqual((await service.inspect(scope)).features, ["export"]);
52
+ await service.applyStoreSubscription(scope, { ...subscription, status: "grace", periodEnd: 6000, reference: "store-event-2" });
53
+ assert.deepEqual((await service.inspect(scope)).features, ["export"], "billing grace keeps access");
54
+ await service.applyStoreSubscription(scope, { ...subscription, status: "revoked", reference: "store-event-3" });
55
+ assert.deepEqual((await service.inspect(scope)).features, []);
56
+ await assert.rejects(service.applyStoreSubscription(scope, { ...subscription, planId: "unknown", reference: "store-event-4" }), { code: "payment_provider_result_invalid" });
57
+ });
@@ -1,7 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import knexLib from "knex";
4
- import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
3
+ import { createPackageTestKnex, requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
5
4
  import { startFakeStripe } from "./support/fakeStripe.js";
6
5
  import { createTopUpApp } from "./support/topUpApp.js";
7
6
 
@@ -10,22 +9,10 @@ import { createTopUpApp } from "./support/topUpApp.js";
10
9
  // top-up's row: each door moves its status to paid under that row's lock, in the transaction that writes the credit,
11
10
  // so the door that waits for the lock finds it paid.
12
11
 
13
- // The runtime's own MySQL connection settings (database-runtime's resolveKnexConnectionFromEnvironment).
14
- const RUNTIME_MYSQL = Object.freeze({ supportBigNumbers: true, bigNumberStrings: true, dateStrings: ["DATE"], timezone: "Z" });
15
12
 
16
- /** A database of the test's own, beside TEST_DB_NAME, dropped after the test. */
17
- async function ownDatabase(context, suffix) {
18
- const name = `${requireTestDatabase(process.env)}_${suffix}`;
19
- const server = { host: process.env.DB_HOST, port: Number(process.env.DB_PORT) || 3306, user: process.env.DB_USER, password: process.env.DB_PASSWORD };
20
- const admin = knexLib({ client: "mysql2", connection: server, pool: { min: 0, max: 1 } });
21
- await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
22
- await admin.raw("CREATE DATABASE ??", [name]);
23
- const knex = knexLib({ client: "mysql2", connection: { ...server, database: name, ...RUNTIME_MYSQL }, pool: { min: 0, max: 6 } });
24
- context.after(async () => {
25
- await knex.destroy();
26
- await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
27
- await admin.destroy();
28
- });
13
+ /** A lettered copy of TEST_DB_NAME the test claims (createPackageTestKnex() on MySQL), empty, dropped after the test. */
14
+ async function ownDatabase(context) {
15
+ const knex = await createPackageTestKnex(context, { environment: { ...process.env, DB_CLIENT: "mysql2" } });
29
16
  return knex;
30
17
  }
31
18
 
@@ -40,7 +27,7 @@ function gate() {
40
27
 
41
28
  test("the webhook and the return page settling one payment at the same moment credit it once", async (context) => {
42
29
  requireTestDatabase(process.env);
43
- const knex = await ownDatabase(context, "pay_top_up_race");
30
+ const knex = await ownDatabase(context);
44
31
  const stripe = await startFakeStripe();
45
32
  context.after(() => stripe.close());
46
33
  // The first door to credit stops inside its transaction, holding the top-up's row, until the other door has read it.