@owlmeans/server-payment 0.1.18 → 0.1.19
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/README.md +1 -1
- package/agent-meta/manifest.json +2 -2
- package/agent-meta/skills/server-payment/SKILL.md +74 -6
- package/build/access/types.d.ts +8 -1
- package/build/access/types.d.ts.map +1 -1
- package/build/access.d.ts.map +1 -1
- package/build/access.js +8 -2
- package/build/access.js.map +1 -1
- package/build/catalogue/types.d.ts +3 -1
- package/build/catalogue/types.d.ts.map +1 -1
- package/build/catalogue.d.ts.map +1 -1
- package/build/catalogue.js +15 -10
- package/build/catalogue.js.map +1 -1
- package/build/commit/types.d.ts +17 -2
- package/build/commit/types.d.ts.map +1 -1
- package/build/commit.d.ts.map +1 -1
- package/build/commit.js +40 -5
- package/build/commit.js.map +1 -1
- package/build/consts.d.ts +17 -0
- package/build/consts.d.ts.map +1 -1
- package/build/consts.js +19 -0
- package/build/consts.js.map +1 -1
- package/build/consumer/capture.d.ts.map +1 -1
- package/build/consumer/capture.js +2 -1
- package/build/consumer/capture.js.map +1 -1
- package/build/consumer/reconcile.d.ts.map +1 -1
- package/build/consumer/reconcile.js +2 -1
- package/build/consumer/reconcile.js.map +1 -1
- package/build/entitlement.d.ts.map +1 -1
- package/build/entitlement.js +7 -1
- package/build/entitlement.js.map +1 -1
- package/build/grant-fold/types.d.ts +41 -0
- package/build/grant-fold/types.d.ts.map +1 -0
- package/build/grant-fold/types.js +2 -0
- package/build/grant-fold/types.js.map +1 -0
- package/build/grant-fold.d.ts +4 -0
- package/build/grant-fold.d.ts.map +1 -0
- package/build/grant-fold.js +64 -0
- package/build/grant-fold.js.map +1 -0
- package/build/grants/types.d.ts +39 -0
- package/build/grants/types.d.ts.map +1 -0
- package/build/grants/types.js +2 -0
- package/build/grants/types.js.map +1 -0
- package/build/grants.d.ts +6 -0
- package/build/grants.d.ts.map +1 -0
- package/build/grants.js +141 -0
- package/build/grants.js.map +1 -0
- package/build/index.d.ts +4 -0
- package/build/index.d.ts.map +1 -1
- package/build/index.js +2 -0
- package/build/index.js.map +1 -1
- package/build/observer.d.ts +3 -0
- package/build/observer.d.ts.map +1 -1
- package/build/observer.js +6 -0
- package/build/observer.js.map +1 -1
- package/build/plugins/events.d.ts.map +1 -1
- package/build/plugins/events.js +5 -2
- package/build/plugins/events.js.map +1 -1
- package/build/plugins/session/types.d.ts +2 -0
- package/build/plugins/session/types.d.ts.map +1 -1
- package/build/plugins/session.d.ts.map +1 -1
- package/build/plugins/session.js +15 -2
- package/build/plugins/session.js.map +1 -1
- package/build/plugins/stripe.js +3 -3
- package/build/plugins/stripe.js.map +1 -1
- package/build/reconcile/types.d.ts +4 -2
- package/build/reconcile/types.d.ts.map +1 -1
- package/build/reconcile.d.ts.map +1 -1
- package/build/reconcile.js +3 -1
- package/build/reconcile.js.map +1 -1
- package/build/resource.d.ts +2 -1
- package/build/resource.d.ts.map +1 -1
- package/build/resource.js +10 -2
- package/build/resource.js.map +1 -1
- package/build/schemas.d.ts +2 -1
- package/build/schemas.d.ts.map +1 -1
- package/build/schemas.js +16 -2
- package/build/schemas.js.map +1 -1
- package/build/service.d.ts +3 -3
- package/build/service.d.ts.map +1 -1
- package/build/service.js +7 -5
- package/build/service.js.map +1 -1
- package/build/subscription/types.d.ts +12 -2
- package/build/subscription/types.d.ts.map +1 -1
- package/build/subscription.d.ts.map +1 -1
- package/build/subscription.js +14 -3
- package/build/subscription.js.map +1 -1
- package/build/types.d.ts +129 -0
- package/build/types.d.ts.map +1 -1
- package/build/usage/types.d.ts +25 -8
- package/build/usage/types.d.ts.map +1 -1
- package/build/usage.d.ts.map +1 -1
- package/build/usage.js +201 -46
- package/build/usage.js.map +1 -1
- package/build/utils/types.d.ts +5 -0
- package/build/utils/types.d.ts.map +1 -1
- package/build/utils.d.ts.map +1 -1
- package/build/utils.js +4 -2
- package/build/utils.js.map +1 -1
- package/package.json +22 -22
- package/src/access/types.ts +8 -1
- package/src/access.ts +12 -3
- package/src/catalogue/types.ts +3 -1
- package/src/catalogue.ts +17 -13
- package/src/commit/types.ts +17 -2
- package/src/commit.ts +47 -6
- package/src/consts.ts +20 -0
- package/src/consumer/capture.ts +2 -1
- package/src/consumer/reconcile.ts +2 -1
- package/src/entitlement.ts +8 -1
- package/src/grant-fold/types.ts +42 -0
- package/src/grant-fold.ts +89 -0
- package/src/grants/types.ts +42 -0
- package/src/grants.ts +171 -0
- package/src/index.ts +4 -0
- package/src/observer.ts +8 -1
- package/src/plugins/events.ts +5 -2
- package/src/plugins/session/types.ts +2 -0
- package/src/plugins/session.ts +15 -2
- package/src/plugins/stripe.ts +3 -3
- package/src/reconcile/types.ts +4 -2
- package/src/reconcile.ts +3 -1
- package/src/resource.ts +20 -7
- package/src/schemas.ts +20 -5
- package/src/service.ts +9 -6
- package/src/subscription/types.ts +12 -2
- package/src/subscription.ts +15 -2
- package/src/types.ts +133 -0
- package/src/usage/types.ts +25 -8
- package/src/usage.ts +235 -48
- package/src/utils/types.ts +5 -0
- package/src/utils.ts +6 -2
- package/tests/checkout.spec.ts +62 -0
- package/tests/consumer-fixtures.ts +7 -0
- package/tests/consumer-ops.spec.ts +12 -1
- package/tests/consumer-rights.spec.ts +35 -1
- package/tests/events.spec.ts +10 -0
- package/tests/fake-stripe.ts +35 -12
- package/tests/grants.spec.ts +276 -0
- package/tests/internal-plan.spec.ts +112 -0
- package/tests/usage.integration.spec.ts +32 -0
package/src/usage.ts
CHANGED
|
@@ -1,17 +1,24 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
LimitExhausted, LimitKind, LimitMisdeclared, LimitUnknown, LimitWindow, OCCUPANCY_WINDOW, PlanRequired,
|
|
3
|
+
SUBSCRIPTION_WEEK_MS, SUBSCRIPTION_WEEK_PREFIX, type LimitDeclaration, type LimitView, entitlementViewHelper,
|
|
4
|
+
planLimitHelper, promoHelper,
|
|
5
|
+
} from '@owlmeans/payment'
|
|
2
6
|
import { UnsupportedArgumentError } from '@owlmeans/resource'
|
|
3
7
|
import type { Context as ApiContext } from '@owlmeans/server-api'
|
|
4
8
|
import { memoHelper } from '@owlmeans/context'
|
|
5
9
|
import type {
|
|
6
|
-
ConsumeRequest, CounterReconciliation, EffectivePlan, LimitOutcome, OccupancyOutcome,
|
|
7
|
-
PaymentUsageRecord, ReleaseRequest,
|
|
10
|
+
ConsumeRequest, CounterReconciliation, EffectivePlan, LimitOutcome, OccupancyOutcome, PaymentGrantRecord,
|
|
11
|
+
PaymentUsageCounterRecord, PaymentUsageRecord, ReleaseRequest,
|
|
8
12
|
} from './types.js'
|
|
9
13
|
import { log } from './log.js'
|
|
14
|
+
import { EntitlementGrantKind, EntitlementGrantStatus } from './consts.js'
|
|
10
15
|
import { DAY_WINDOW, MONTH_WINDOW } from './consts.local.js'
|
|
11
16
|
import type { CounterKey, LedgerSum, UsageHelper } from './usage/types.js'
|
|
12
17
|
import { paymentAccessOf } from './access.js'
|
|
13
18
|
import { paymentUtils } from './utils.js'
|
|
14
19
|
import { catalogueOf } from './catalogue.js'
|
|
20
|
+
import { grantFoldHelper } from './grant-fold.js'
|
|
21
|
+
import { entitlementGrantsOf } from './grants.js'
|
|
15
22
|
|
|
16
23
|
/**
|
|
17
24
|
* The usage ledger and its counters.
|
|
@@ -22,6 +29,13 @@ import { catalogueOf } from './catalogue.js'
|
|
|
22
29
|
* counter may over-count, never over-admit.** A crash between the two leaves a unit counted that no
|
|
23
30
|
* event spent, which `reconcileCounters` repairs from the ledger; the opposite order would let two
|
|
24
31
|
* concurrent requests both read "room left" and both spend it.
|
|
32
|
+
*
|
|
33
|
+
* Entitlement grants of `units` extend a limit beyond its plan. A unit is taken from a grant only
|
|
34
|
+
* when the plan's own counter has no room: a conditional increment of the grant's `used` (room for
|
|
35
|
+
* the unit AND for whatever the plan counter holds over its own ceiling), then the event in the
|
|
36
|
+
* window `grant:<grantId>` — the same order, the same invariant. A release returns the unit to the
|
|
37
|
+
* grant it was taken from; reconciliation rebuilds a grant's `used` from its events and never folds
|
|
38
|
+
* them into a counter window.
|
|
25
39
|
*/
|
|
26
40
|
|
|
27
41
|
/** When a stored window renews: the first instant of the next day, month or subscription week. */
|
|
@@ -78,20 +92,67 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
|
|
|
78
92
|
const readCounter = async (key: CounterKey): Promise<PaymentUsageCounterRecord | null> =>
|
|
79
93
|
await access.usageCounters().load({ entityId: key.entityId, limitKey: key.limitKey, window: key.window })
|
|
80
94
|
|
|
95
|
+
/**
|
|
96
|
+
* A limit's numbers after a ledger operation: the counter of `key` (its ceiling `limit`, else the
|
|
97
|
+
* counter's own) with the grants `units` folded in. `window` is where the event lives — the
|
|
98
|
+
* counter's, or a grant's.
|
|
99
|
+
*/
|
|
81
100
|
const outcomeOf = async (
|
|
82
101
|
key: CounterKey, eventKey: string, flags: { admitted: boolean, replayed: boolean }, limit?: number,
|
|
102
|
+
units: readonly PaymentGrantRecord[] = [], window: string = key.window,
|
|
83
103
|
): Promise<LimitOutcome> => {
|
|
84
104
|
const counter = await readCounter(key)
|
|
85
|
-
const used = Math.max(0, counter?.used ?? 0)
|
|
86
|
-
const ceiling = limit ?? counter?.limit ?? 0
|
|
105
|
+
const used = Math.max(0, counter?.used ?? 0) + grantFoldHelper.unitsFold(units).used
|
|
106
|
+
const ceiling = (limit ?? counter?.limit ?? 0) + grantFoldHelper.unitsFold(units).amount
|
|
87
107
|
const resetsAt = resetsAtOfWindow(key.window)
|
|
88
108
|
|
|
89
109
|
return {
|
|
90
|
-
...flags, limitKey: key.limitKey, window
|
|
110
|
+
...flags, limitKey: key.limitKey, window, used, limit: ceiling,
|
|
91
111
|
remaining: Math.max(0, ceiling - used), ...(resetsAt != null ? { resetsAt } : {}), eventKey,
|
|
92
112
|
}
|
|
93
113
|
}
|
|
94
114
|
|
|
115
|
+
/**
|
|
116
|
+
* Take `amount` units from the first grant (in consumption order) that has room for them AND for
|
|
117
|
+
* what the plan counter holds over its own ceiling — so the folded total never exceeds the folded
|
|
118
|
+
* ceiling. One conditional increment per grant, guarded by `used` and the status: never over-admits.
|
|
119
|
+
*/
|
|
120
|
+
const holdOnGrant = async (
|
|
121
|
+
key: CounterKey, units: readonly PaymentGrantRecord[], amount: number, limit: number,
|
|
122
|
+
): Promise<PaymentGrantRecord | null> => {
|
|
123
|
+
if (units.length === 0) {
|
|
124
|
+
return null
|
|
125
|
+
}
|
|
126
|
+
const overflow = Math.max(0, ((await readCounter(key))?.used ?? 0) - limit)
|
|
127
|
+
const grants = access.grantRecords().collection
|
|
128
|
+
for (const grant of units) {
|
|
129
|
+
const room = (grant.amount ?? 0) - amount - overflow
|
|
130
|
+
if (grant.id == null || room < 0) {
|
|
131
|
+
continue
|
|
132
|
+
}
|
|
133
|
+
const doc = await grants.findOneAndUpdate(
|
|
134
|
+
paymentUtils.idCriteria(grant.id, { status: EntitlementGrantStatus.Active, used: { $lte: room } }),
|
|
135
|
+
{ $inc: { used: amount } }, { returnDocument: 'after' },
|
|
136
|
+
) as { used?: number } | null
|
|
137
|
+
if (doc != null) {
|
|
138
|
+
return { ...grant, used: doc.used ?? (grant.used ?? 0) + amount }
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return null
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Give `amount` units back to a grant, never below zero. */
|
|
146
|
+
const returnToGrant = async (grantId: string, amount: number): Promise<void> => {
|
|
147
|
+
const grants = access.grantRecords().collection
|
|
148
|
+
const doc = await grants.findOneAndUpdate(
|
|
149
|
+
paymentUtils.idCriteria(grantId, { used: { $gte: amount } }), { $inc: { used: -amount } },
|
|
150
|
+
)
|
|
151
|
+
if (doc == null) {
|
|
152
|
+
await grants.updateOne(paymentUtils.idCriteria(grantId), { $set: { used: 0 } })
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
95
156
|
/** The counter increment that IS the admission decision. `null` when there is no room. */
|
|
96
157
|
const admit = async (
|
|
97
158
|
key: CounterKey, amount: number, limit: number, planSku: string, at: Date,
|
|
@@ -146,56 +207,131 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
|
|
|
146
207
|
const key: CounterKey = {
|
|
147
208
|
entityId: req.entityId, limitKey: req.limitKey, window: planLimitHelper.windowKeyOf(declaration.kind, declaration.window, at, effective?.subscription?.createdAt),
|
|
148
209
|
}
|
|
210
|
+
// The limit's grants in force: consumed only once the plan's own counter has no room.
|
|
211
|
+
const units = grantFoldHelper.unitsOf(effective.grants ?? [], req.limitKey)
|
|
149
212
|
const ledger = access.usageEvents()
|
|
150
213
|
|
|
214
|
+
/**
|
|
215
|
+
* What an event already written answers: the limit as it stands now when the event is of the
|
|
216
|
+
* current window or of a grant; its own window's counter otherwise (`ceiling`, else the counter's).
|
|
217
|
+
*/
|
|
218
|
+
const replay = async (event: PaymentUsageRecord | null, ceiling?: number): Promise<LimitOutcome> => {
|
|
219
|
+
const window = event?.window ?? key.window
|
|
220
|
+
const flags = { admitted: isActiveConsumption(event), replayed: true }
|
|
221
|
+
|
|
222
|
+
return window === key.window || grantFoldHelper.grantIdOf(window) != null
|
|
223
|
+
? await outcomeOf(key, req.eventKey, flags, limit, units, window)
|
|
224
|
+
: await outcomeOf({ ...key, window }, req.eventKey, flags, ceiling)
|
|
225
|
+
}
|
|
226
|
+
|
|
151
227
|
// A retry of an event already written answers from the ledger before admission is asked: at the
|
|
152
228
|
// ceiling, admission would refuse the very unit this key already holds. A released key is final.
|
|
153
229
|
const earlier = await ledger.load({ entityId: req.entityId, limitKey: req.limitKey, eventKey: req.eventKey })
|
|
154
230
|
if (earlier != null) {
|
|
155
|
-
return await
|
|
156
|
-
|
|
157
|
-
|
|
231
|
+
return await replay(earlier)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const append = async (window: string, undo: () => Promise<void>): Promise<LimitOutcome | null> => {
|
|
235
|
+
try {
|
|
236
|
+
await ledger.create({
|
|
237
|
+
...key, window, delta: amount, eventKey: req.eventKey, ref: req.ref, reason: req.reason,
|
|
238
|
+
planSku: effective.plan.sku, createdAt: at,
|
|
239
|
+
})
|
|
240
|
+
} catch (error) {
|
|
241
|
+
// Undo the admission. Should the undo itself fail, the count is over — never over-admitted.
|
|
242
|
+
await undo().catch(failure => { log.error('Usage undo failed', failure) })
|
|
243
|
+
if (!paymentUtils.isDuplicateKey(error)) {
|
|
244
|
+
throw error
|
|
245
|
+
}
|
|
246
|
+
// A concurrent consume of the same key won the event: replay its outcome.
|
|
247
|
+
const winner = await ledger.load({ entityId: req.entityId, limitKey: req.limitKey, eventKey: req.eventKey })
|
|
248
|
+
return await replay(winner, limit)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return null
|
|
158
252
|
}
|
|
159
253
|
|
|
160
254
|
const counter = await admit(key, amount, limit, effective.plan.sku, at)
|
|
161
|
-
if (counter
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
255
|
+
if (counter != null) {
|
|
256
|
+
const replayed = await append(key.window, async () => { await decrement(key, amount, at) })
|
|
257
|
+
if (replayed != null) {
|
|
258
|
+
return replayed
|
|
259
|
+
}
|
|
260
|
+
const fold = grantFoldHelper.unitsFold(units)
|
|
261
|
+
const used = Math.max(0, counter.used) + fold.used
|
|
262
|
+
const ceiling = limit + fold.amount
|
|
263
|
+
const resetsAt = resetsAtOfWindow(key.window)
|
|
264
|
+
|
|
265
|
+
return {
|
|
266
|
+
admitted: true, replayed: false, limitKey: req.limitKey, window: key.window, used, limit: ceiling,
|
|
267
|
+
remaining: Math.max(0, ceiling - used), ...(resetsAt != null ? { resetsAt } : {}), eventKey: req.eventKey,
|
|
168
268
|
}
|
|
169
|
-
const current = await readCounter(key)
|
|
170
|
-
const resetsAt = declaration.kind === LimitKind.Window && declaration.window != null
|
|
171
|
-
? planLimitHelper.windowBoundsOf(declaration.window, at, effective?.subscription?.createdAt).resetsAt : undefined
|
|
172
|
-
throw new LimitExhausted({ key: req.limitKey, used: current?.used ?? 0, limit, resetsAt })
|
|
173
269
|
}
|
|
174
270
|
|
|
271
|
+
// A concurrent consume of this very key may hold the last unit: that is a replay, not a refusal.
|
|
272
|
+
const concurrent = await ledger.load({ entityId: req.entityId, limitKey: req.limitKey, eventKey: req.eventKey })
|
|
273
|
+
if (concurrent != null) {
|
|
274
|
+
return await replay(concurrent)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// The plan's own allowance has no room: a unit of a grant of this limit, when one has room.
|
|
278
|
+
const held = await holdOnGrant(key, units, amount, limit)
|
|
279
|
+
if (held != null) {
|
|
280
|
+
const window = grantFoldHelper.windowOf(held.id!)
|
|
281
|
+
const replayed = await append(window, async () => { await returnToGrant(held.id!, amount) })
|
|
282
|
+
if (replayed != null) {
|
|
283
|
+
return replayed
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return await outcomeOf(key, req.eventKey, { admitted: true, replayed: false }, limit,
|
|
287
|
+
units.map(grant => grant.id === held.id ? held : grant), window)
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const current = await readCounter(key)
|
|
291
|
+
const fold = grantFoldHelper.unitsFold(units)
|
|
292
|
+
const resetsAt = declaration.kind === LimitKind.Window && declaration.window != null
|
|
293
|
+
? planLimitHelper.windowBoundsOf(declaration.window, at, effective?.subscription?.createdAt).resetsAt : undefined
|
|
294
|
+
throw new LimitExhausted({
|
|
295
|
+
key: req.limitKey, used: (current?.used ?? 0) + fold.used, limit: limit + fold.amount, resetsAt,
|
|
296
|
+
})
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* What a release answers: the counter of the event's window with the limit's grants in force
|
|
301
|
+
* folded in; for a unit held on a grant, the limit as it stands now (its current window).
|
|
302
|
+
*/
|
|
303
|
+
const releaseOutcomeOf = async (
|
|
304
|
+
req: ReleaseRequest, consumed: PaymentUsageRecord, flags: { admitted: boolean, replayed: boolean },
|
|
305
|
+
): Promise<LimitOutcome> => {
|
|
306
|
+
const at = new Date()
|
|
307
|
+
if (grantFoldHelper.grantIdOf(consumed.window) == null) {
|
|
308
|
+
const units = grantFoldHelper.unitsOf(await entitlementGrantsOf(ctx).inForce(req.entityId, at), req.limitKey)
|
|
309
|
+
return await outcomeOf({ entityId: req.entityId, limitKey: req.limitKey, window: consumed.window }, req.eventKey,
|
|
310
|
+
flags, undefined, units)
|
|
311
|
+
}
|
|
175
312
|
try {
|
|
176
|
-
await
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
313
|
+
const effective = await catalogueOf(ctx).resolveEffectivePlan(req.entityId, at)
|
|
314
|
+
const declaration = declarationOf(effective, req.limitKey)
|
|
315
|
+
const key: CounterKey = {
|
|
316
|
+
entityId: req.entityId, limitKey: req.limitKey,
|
|
317
|
+
window: planLimitHelper.windowKeyOf(declaration.kind, declaration.window, at, effective.subscription?.createdAt),
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return await outcomeOf(key, req.eventKey, flags, ceilingOf(declaration, effective, at),
|
|
321
|
+
grantFoldHelper.unitsOf(effective.grants ?? [], req.limitKey), consumed.window)
|
|
180
322
|
} catch (error) {
|
|
181
|
-
|
|
182
|
-
await decrement(key, amount, at).catch(undo => { log.error('Usage undo failed', undo) })
|
|
183
|
-
if (!paymentUtils.isDuplicateKey(error)) {
|
|
323
|
+
if (!(error instanceof LimitUnknown) && !(error instanceof PlanRequired)) {
|
|
184
324
|
throw error
|
|
185
325
|
}
|
|
186
|
-
//
|
|
187
|
-
const
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
}, limit)
|
|
191
|
-
}
|
|
326
|
+
// No plan declares the limit any more: only its grants are left to report.
|
|
327
|
+
const fold = grantFoldHelper.unitsFold(
|
|
328
|
+
grantFoldHelper.unitsOf(await entitlementGrantsOf(ctx).inForce(req.entityId, at), req.limitKey),
|
|
329
|
+
)
|
|
192
330
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
admitted: true, replayed: false, limitKey: req.limitKey, window: key.window, used, limit,
|
|
198
|
-
remaining: Math.max(0, limit - used), ...(resetsAt != null ? { resetsAt } : {}), eventKey: req.eventKey,
|
|
331
|
+
return {
|
|
332
|
+
...flags, limitKey: req.limitKey, window: consumed.window, used: fold.used, limit: fold.amount,
|
|
333
|
+
remaining: Math.max(0, fold.amount - fold.used), eventKey: req.eventKey,
|
|
334
|
+
}
|
|
199
335
|
}
|
|
200
336
|
}
|
|
201
337
|
|
|
@@ -209,8 +345,10 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
|
|
|
209
345
|
}
|
|
210
346
|
}
|
|
211
347
|
const key: CounterKey = { entityId: req.entityId, limitKey: req.limitKey, window: consumed.window }
|
|
348
|
+
// A unit held on a grant goes back to that grant, never to a counter.
|
|
349
|
+
const grantId = grantFoldHelper.grantIdOf(consumed.window)
|
|
212
350
|
if (consumed.releasedAt != null) {
|
|
213
|
-
return await
|
|
351
|
+
return await releaseOutcomeOf(req, consumed, { admitted: true, replayed: true })
|
|
214
352
|
}
|
|
215
353
|
const amount = Math.min(req.amount ?? consumed.delta, consumed.delta)
|
|
216
354
|
if (!Number.isSafeInteger(amount) || amount < 1) {
|
|
@@ -228,15 +366,19 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
|
|
|
228
366
|
if (!paymentUtils.isDuplicateKey(error)) {
|
|
229
367
|
throw error
|
|
230
368
|
}
|
|
231
|
-
// An earlier attempt appended the release and
|
|
369
|
+
// An earlier attempt appended the release and gave the unit back; only the stamp is missing.
|
|
232
370
|
appended = false
|
|
233
371
|
}
|
|
234
372
|
if (appended) {
|
|
235
|
-
|
|
373
|
+
if (grantId != null) {
|
|
374
|
+
await returnToGrant(grantId, amount)
|
|
375
|
+
} else {
|
|
376
|
+
await decrement(key, amount, at)
|
|
377
|
+
}
|
|
236
378
|
}
|
|
237
379
|
await ledger.update({ ...consumed, releasedAt: at })
|
|
238
380
|
|
|
239
|
-
return await
|
|
381
|
+
return await releaseOutcomeOf(req, consumed, { admitted: true, replayed: false })
|
|
240
382
|
}
|
|
241
383
|
|
|
242
384
|
const consumptionOf = async (
|
|
@@ -262,7 +404,7 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
|
|
|
262
404
|
const counter = await readCounter({ entityId, limitKey, window })
|
|
263
405
|
const [view] = entitlementViewHelper.limitViewsOf({ limits: { [limitKey]: declaration } }, counter != null ? [{ key: limitKey, window, used: counter.used }] : [], effective.subscription?.createdAt, at)
|
|
264
406
|
|
|
265
|
-
return view
|
|
407
|
+
return grantFoldHelper.foldLimitView(view, effective.grants ?? [])
|
|
266
408
|
}
|
|
267
409
|
|
|
268
410
|
const ledgerSums = async (match: Partial<CounterKey>): Promise<LedgerSum[]> => {
|
|
@@ -313,11 +455,16 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
|
|
|
313
455
|
if (declaration.kind !== LimitKind.Occupancy) {
|
|
314
456
|
throw new LimitMisdeclared(`${limitKey}:not-occupancy`)
|
|
315
457
|
}
|
|
316
|
-
const
|
|
458
|
+
const ceiling = ceilingOf(declaration, effective, at)
|
|
317
459
|
const key: CounterKey = { entityId, limitKey, window: OCCUPANCY_WINDOW }
|
|
460
|
+
// What the grants in force hold is theirs; the plan counter holds the rest of what exists. A
|
|
461
|
+
// revoked or ended grant's units fall back on the plan counter here — over its ceiling, flagged.
|
|
462
|
+
const fold = grantFoldHelper.unitsFold(grantFoldHelper.unitsOf(effective.grants ?? [], limitKey))
|
|
463
|
+
const held = Math.max(0, actual - fold.used)
|
|
464
|
+
const limit = ceiling + fold.amount
|
|
318
465
|
|
|
319
466
|
const [sum] = await ledgerSums(key)
|
|
320
|
-
const delta =
|
|
467
|
+
const delta = held - (sum?.used ?? 0)
|
|
321
468
|
if (delta !== 0) {
|
|
322
469
|
const eventKey = `reconcile:${limitKey}:${planLimitHelper.windowKeyOf(LimitKind.Window, LimitWindow.Day, at)}`
|
|
323
470
|
try {
|
|
@@ -336,13 +483,47 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
|
|
|
336
483
|
const over = Math.max(0, actual - limit)
|
|
337
484
|
const overSince = over > 0 ? (counter?.overSince != null ? new Date(counter.overSince) : at) : undefined
|
|
338
485
|
await setCounter(key, {
|
|
339
|
-
used:
|
|
486
|
+
used: held, limit: ceiling, planSku: effective.plan.sku, updatedAt: at, reconciledAt: at,
|
|
340
487
|
...(overSince != null ? { overSince } : {}),
|
|
341
488
|
}, overSince == null ? ['overSince'] : [])
|
|
342
489
|
|
|
343
490
|
return { limitKey, used: actual, limit, over, ...(overSince != null ? { overSince } : {}) }
|
|
344
491
|
}
|
|
345
492
|
|
|
493
|
+
/**
|
|
494
|
+
* Rebuild every units grant's `used` of an entity from its events (`sums` of its `grant:<id>`
|
|
495
|
+
* windows); a grant without events holds nothing.
|
|
496
|
+
*/
|
|
497
|
+
const reconcileGrants = async (entityId: string, sums: readonly LedgerSum[]): Promise<CounterReconciliation> => {
|
|
498
|
+
const records = access.grantRecordsOf()
|
|
499
|
+
if (records == null) {
|
|
500
|
+
return { counters: 0, repaired: 0 }
|
|
501
|
+
}
|
|
502
|
+
const byGrant = new Map<string, number>()
|
|
503
|
+
for (const sum of sums) {
|
|
504
|
+
const grantId = grantFoldHelper.grantIdOf(sum.window)
|
|
505
|
+
if (grantId != null) {
|
|
506
|
+
byGrant.set(grantId, (byGrant.get(grantId) ?? 0) + sum.used)
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
const { items } = await records.list({ entityId, kind: EntitlementGrantKind.Units }, { size: 0 })
|
|
510
|
+
let counters = 0
|
|
511
|
+
let repaired = 0
|
|
512
|
+
for (const grant of items) {
|
|
513
|
+
if (grant.id == null) {
|
|
514
|
+
continue
|
|
515
|
+
}
|
|
516
|
+
const used = Math.max(0, byGrant.get(grant.id) ?? 0)
|
|
517
|
+
counters++
|
|
518
|
+
if (used !== (grant.used ?? 0)) {
|
|
519
|
+
repaired++
|
|
520
|
+
await records.collection.updateOne(paymentUtils.idCriteria(grant.id), { $set: { used } })
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
return { counters, repaired }
|
|
525
|
+
}
|
|
526
|
+
|
|
346
527
|
const reconcileLedgerCounters = async (entityId?: string): Promise<CounterReconciliation> => {
|
|
347
528
|
const at = new Date()
|
|
348
529
|
const sums = await ledgerSums(entityId != null ? { entityId } : {})
|
|
@@ -365,7 +546,9 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
|
|
|
365
546
|
return declaration != null && effective != null ? ceilingOf(declaration, effective, at) : fallback
|
|
366
547
|
}
|
|
367
548
|
|
|
368
|
-
|
|
549
|
+
// A grant's events rebuild that grant, never a counter window.
|
|
550
|
+
const own = sums.filter(sum => sum.entityId === entity)
|
|
551
|
+
const ledger = new Map(own.filter(sum => grantFoldHelper.grantIdOf(sum.window) == null)
|
|
369
552
|
.map(sum => [`${sum.limitKey}${sum.window}`, sum.used]))
|
|
370
553
|
const { items: stored } = await access.usageCounters().list({ entityId: entity }, { size: 0 })
|
|
371
554
|
const seen = new Set<string>()
|
|
@@ -417,6 +600,10 @@ export const makeUsageHelper = (ctx: ApiContext): UsageHelper => {
|
|
|
417
600
|
used: 0, limit: limitOf(limitKey, 0), planSku: effective?.plan.sku, updatedAt: at, reconciledAt: at,
|
|
418
601
|
})
|
|
419
602
|
}
|
|
603
|
+
|
|
604
|
+
const grants = await reconcileGrants(entity, own)
|
|
605
|
+
counters += grants.counters
|
|
606
|
+
repaired += grants.repaired
|
|
420
607
|
}
|
|
421
608
|
|
|
422
609
|
return { counters, repaired }
|
package/src/utils/types.ts
CHANGED
|
@@ -25,6 +25,11 @@ export interface PaymentUtils {
|
|
|
25
25
|
) => Promise<boolean>
|
|
26
26
|
/** A conditional single-document delete — `true` when the filter matched (the guard held). */
|
|
27
27
|
conditionalDelete: (resource: CollectionHolder, filter: Record<string, unknown>) => Promise<boolean>
|
|
28
|
+
/**
|
|
29
|
+
* A raw collection filter addressing ONE record by its id (`_id`), plus `filter` — what a
|
|
30
|
+
* conditional raw write (`$inc` guarded by a value) of a record known by id matches on.
|
|
31
|
+
*/
|
|
32
|
+
idCriteria: (id: string, filter?: Record<string, unknown>) => Record<string, unknown>
|
|
28
33
|
/** An error's message for an audit record, never a stack. */
|
|
29
34
|
errorText: (error: unknown) => string
|
|
30
35
|
}
|
package/src/utils.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type Stripe from 'stripe'
|
|
2
|
-
import { MONGO_DUPLICATE_KEY } from '@owlmeans/mongo-resource'
|
|
2
|
+
import { MONGO_DUPLICATE_KEY, mongoRefHelper } from '@owlmeans/mongo-resource'
|
|
3
3
|
import { WebhookSetupError, type PaymentService } from '@owlmeans/payment'
|
|
4
4
|
import type { Context as ApiContext } from '@owlmeans/server-api'
|
|
5
5
|
import { CONSUMER_RIGHTS_SERVICE } from './consts.js'
|
|
@@ -55,11 +55,15 @@ export const createPaymentUtils = (): PaymentUtils => {
|
|
|
55
55
|
return (result.deletedCount ?? 0) > 0
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
+
const idCriteria = (id: string, filter: Record<string, unknown> = {}): Record<string, unknown> =>
|
|
59
|
+
mongoRefHelper.marshalCriteria({ ...filter, id }, new Map()) as Record<string, unknown>
|
|
60
|
+
|
|
58
61
|
const errorText = (error: unknown): string =>
|
|
59
62
|
(error instanceof Error ? error.message : String(error)).slice(0, 1000)
|
|
60
63
|
|
|
61
64
|
return {
|
|
62
|
-
apiVersionOf, isDuplicateKey, isMissingObject, idOf, dateOf, compact, conditionalSet, conditionalDelete,
|
|
65
|
+
apiVersionOf, isDuplicateKey, isMissingObject, idOf, dateOf, compact, conditionalSet, conditionalDelete,
|
|
66
|
+
idCriteria, errorText,
|
|
63
67
|
}
|
|
64
68
|
}
|
|
65
69
|
|
package/tests/checkout.spec.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { CREDITS_PRODUCT, FREE, makeFakeContext, PLANS_PRODUCT, PRO, TEAM } from
|
|
|
8
8
|
import type { FakeContext } from './fake-stripe.js'
|
|
9
9
|
import { stripeCheckoutOf } from '../src/plugins/stripe.js'
|
|
10
10
|
import { stripeSessionHelper } from '../src/plugins/session.js'
|
|
11
|
+
import { freeSession } from './consumer-fixtures.js'
|
|
11
12
|
|
|
12
13
|
const proPrice = { id: 'price_pro', product: PLANS_PRODUCT, lookup_key: PRO, active: true, recurring: { interval: 'month' } }
|
|
13
14
|
const successUrl = 'https://app.example.com/ok'
|
|
@@ -81,6 +82,24 @@ describe('Stripe checkout', () => {
|
|
|
81
82
|
})
|
|
82
83
|
|
|
83
84
|
describe('Stripe checkout — pricing policy', () => {
|
|
85
|
+
test('amount promotion codes are opt-in and never change the selected credit value or base charge', async () => {
|
|
86
|
+
for (const enabled of [undefined, false, true]) {
|
|
87
|
+
const fake = await makeFakeContext({
|
|
88
|
+
pricing: {
|
|
89
|
+
tax: { automatic: true, collectTaxId: true, estimate: false }, currency: { estimate: false },
|
|
90
|
+
...(enabled != null ? { stripe: { amountPromotionCodes: enabled } } : {}),
|
|
91
|
+
},
|
|
92
|
+
})
|
|
93
|
+
await stripeCheckoutOf(fake.ctx).createCheckoutLink(fake.stripe, {
|
|
94
|
+
productSku: CREDITS_PRODUCT, entityId: 'entity-1', service: 'app', amountMinor: 1000, successUrl,
|
|
95
|
+
})
|
|
96
|
+
const session = fake.state.checkoutSessions[0]
|
|
97
|
+
expect(session.allow_promotion_codes).toBe(enabled === true)
|
|
98
|
+
expect(session.metadata.amountMinor).toBe('1000')
|
|
99
|
+
expect(session.line_items[0].price_data.unit_amount).toBe(1021)
|
|
100
|
+
}
|
|
101
|
+
})
|
|
102
|
+
|
|
84
103
|
test('an undeclared policy reproduces exactly the session hard-coded before this policy existed', async () => {
|
|
85
104
|
const fake = await makeFakeContext({ stripe: { prices: [proPrice] } })
|
|
86
105
|
await stripeCheckoutOf(fake.ctx).createCheckoutLink(fake.stripe, {
|
|
@@ -181,6 +200,49 @@ describe('Stripe checkout — pricing policy', () => {
|
|
|
181
200
|
})
|
|
182
201
|
|
|
183
202
|
describe('Stripe checkout fulfillment', () => {
|
|
203
|
+
test('percentage and fixed discounts grant the full selected credit value once', async () => {
|
|
204
|
+
for (const discount of [511, 100]) {
|
|
205
|
+
const fake = await makeFakeContext()
|
|
206
|
+
const session = paid({
|
|
207
|
+
allow_promotion_codes: true, amount_total: 1021 - discount,
|
|
208
|
+
total_details: { amount_tax: 0, amount_discount: discount },
|
|
209
|
+
})
|
|
210
|
+
await process(fake, 'checkout.session.completed', session)
|
|
211
|
+
await process(fake, 'checkout.session.completed', session)
|
|
212
|
+
expect(fake.observed.topUp).toEqual([expect.objectContaining({ amountMinor: 1000, chargeAmountMinor: 1021 })])
|
|
213
|
+
expect(fulfillment(fake)[0].amountTotalMinor).toBe(1021 - discount)
|
|
214
|
+
}
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
test('a fully discounted completion without a payment intent retries the observer and fulfills once', async () => {
|
|
218
|
+
for (const payment_status of ['no_payment_required', 'paid']) {
|
|
219
|
+
const fake = await makeFakeContext()
|
|
220
|
+
const session = freeSession({ payment_status })
|
|
221
|
+
fake.observed.failTopUp = 1
|
|
222
|
+
await expect(process(fake, 'checkout.session.completed', session)).rejects.toThrow('ledger unavailable')
|
|
223
|
+
await process(fake, 'checkout.session.completed', session)
|
|
224
|
+
await process(fake, 'checkout.session.completed', session)
|
|
225
|
+
expect(fake.observed.topUp).toEqual([expect.objectContaining({ amountMinor: 1000, chargeAmountMinor: 919 })])
|
|
226
|
+
expect(fulfillment(fake)[0]).toEqual(expect.objectContaining({ amountTotalMinor: 0, fulfilledAt: expect.any(Date) }))
|
|
227
|
+
expect(fulfillment(fake)[0].paymentIntentId).toBeUndefined()
|
|
228
|
+
}
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
test('free fulfillment requires a completed amount session and a full authorized discount', async () => {
|
|
232
|
+
const fake = await makeFakeContext()
|
|
233
|
+
for (const patch of [
|
|
234
|
+
{ status: 'open' }, { payment_status: 'unpaid' }, { amount_total: 1 },
|
|
235
|
+
{ allow_promotion_codes: false }, { metadata: { pricingMode: 'quantity' } },
|
|
236
|
+
{ total_details: { amount_discount: 918, amount_tax: 0 } },
|
|
237
|
+
{ total_details: { amount_discount: 919, amount_tax: 1 } },
|
|
238
|
+
]) {
|
|
239
|
+
await process(fake, 'checkout.session.completed', freeSession(patch))
|
|
240
|
+
}
|
|
241
|
+
expect(fake.observed.topUp).toHaveLength(0)
|
|
242
|
+
await expect(process(fake, 'checkout.session.completed', freeSession({ metadata: { currency: 'usd' } }))).rejects.toThrow('amount-mismatch')
|
|
243
|
+
await expect(process(fake, 'checkout.session.completed', freeSession({ metadata: { chargeAmountMinor: '918' } }))).rejects.toThrow('amount-mismatch')
|
|
244
|
+
})
|
|
245
|
+
|
|
184
246
|
test('fulfills a paid amount once even when the session carries Adaptive Pricing presentment details', async () => {
|
|
185
247
|
const fake = await makeFakeContext()
|
|
186
248
|
await process(fake, 'checkout.session.completed', paid({
|
|
@@ -104,6 +104,13 @@ export const paidSession = (overrides: Rec = {}): Rec => ({
|
|
|
104
104
|
},
|
|
105
105
|
})
|
|
106
106
|
|
|
107
|
+
/** A completed 100% promotion-code redemption without a PaymentIntent or invoice. */
|
|
108
|
+
export const freeSession = (overrides: Rec = {}): Rec => paidSession({
|
|
109
|
+
payment_status: 'no_payment_required', allow_promotion_codes: true,
|
|
110
|
+
amount_total: 0, total_details: { amount_tax: 0, amount_discount: 919 },
|
|
111
|
+
payment_intent: null, invoice: null, ...overrides,
|
|
112
|
+
})
|
|
113
|
+
|
|
107
114
|
/** The post-payment invoice of `paidSession`. */
|
|
108
115
|
export const invoiceOf = (id = 'in_pl', overrides: Rec = {}): Rec => ({
|
|
109
116
|
id, object: 'invoice', number: 'INV-0001', subtotal: 919, tax: 211, total: 1130, currency: 'eur',
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
} from '@owlmeans/payment'
|
|
6
6
|
import { checkoutReadEntrypoints, consumerRightsEntrypoints } from '../src/consumer/handlers.js'
|
|
7
7
|
import {
|
|
8
|
-
ALL_ON, buyTopUp, CREDITS_PRODUCT, ENTITY, epoch, fixedMeter, makeRightsContext, paidSession, PLANS_PRODUCT, PRO,
|
|
8
|
+
ALL_ON, buyTopUp, CREDITS_PRODUCT, ENTITY, epoch, fixedMeter, freeSession, makeRightsContext, paidSession, PLANS_PRODUCT, PRO,
|
|
9
9
|
rightsOf, TEXT_VERSION,
|
|
10
10
|
} from './consumer-fixtures.js'
|
|
11
11
|
import type { FakeContext } from './fake-stripe.js'
|
|
@@ -93,6 +93,17 @@ describe('reconcile', () => {
|
|
|
93
93
|
expect((await paymentAccessOf(fake.ctx).billingProfiles().byEntity(ENTITY))?.country).toBe('PL')
|
|
94
94
|
})
|
|
95
95
|
|
|
96
|
+
test('backfills free completed amount checkouts without opening a consent or refund window', async () => {
|
|
97
|
+
const fake = await makeRightsContext()
|
|
98
|
+
fake.state.listedSessions = [freeSession()]
|
|
99
|
+
expect((await service(fake).reconcile()).backfilled).toBe(1)
|
|
100
|
+
const purchase = await paymentAccessOf(fake.ctx).purchases().load({ sessionId: 'cs_pl' })
|
|
101
|
+
expect(purchase?.amountTotalMinor).toBe(0)
|
|
102
|
+
expect(purchase?.deadline).toBeUndefined()
|
|
103
|
+
expect((await service(fake).consentView(ENTITY)).required).toBe(false)
|
|
104
|
+
expect(fake.mails).toHaveLength(0)
|
|
105
|
+
})
|
|
106
|
+
|
|
96
107
|
test('an organization that paid before the lock is locked from its paygate customer', async () => {
|
|
97
108
|
const fake = await makeRightsContext()
|
|
98
109
|
await paymentAccessOf(fake.ctx).paygateCustomers().create({ paygate: 'stripe', externalId: 'cus_n', entityId: 'entity-n', country: 'NO' })
|
|
@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'
|
|
|
2
2
|
import { CancellationKind, CancellationStatus, CancellationUnavailable, ConsentKind, LimitKind, PerformanceConsentRequired, PlanDuration, WithdrawalStatus, WithdrawalUnavailable, consumerCopyHelper } from '@owlmeans/payment'
|
|
3
3
|
import type { PaymentPlanDef, PurchaseRecord } from '../src/types.js'
|
|
4
4
|
import {
|
|
5
|
-
buyTopUp, ENTITY, fixedMeter, invoiceOf, makeRightsContext, PLANS_PRODUCT, PRO, requestStart, rightsOf, send,
|
|
5
|
+
buyTopUp, ENTITY, fixedMeter, freeSession, invoiceOf, makeRightsContext, PLANS_PRODUCT, PRO, requestStart, rightsOf, send,
|
|
6
6
|
TEXT_VERSION,
|
|
7
7
|
} from './consumer-fixtures.js'
|
|
8
8
|
import type { RecordingMeter } from './consumer-fixtures.js'
|
|
@@ -31,6 +31,21 @@ const consent = async (fake: FakeContext, purchase: PurchaseRecord, language = '
|
|
|
31
31
|
}, { ip: '198.51.100.1', userAgent: 'test-agent', ipCountry: 'PL' })
|
|
32
32
|
|
|
33
33
|
describe('consumer rights — performance consent', () => {
|
|
34
|
+
test('free top-ups retain their receipt and country lock without a consent or monetary withdrawal window', async () => {
|
|
35
|
+
const fake = await withMeter(fixedMeter({ granted: 1000, used: 0 }))
|
|
36
|
+
await send(fake, 'checkout.session.completed', freeSession())
|
|
37
|
+
const purchase = await paymentAccessOf(fake.ctx).purchases().load({ sessionId: 'cs_pl' })
|
|
38
|
+
expect(purchase).toEqual(expect.objectContaining({ amountTotalMinor: 0, netAmountMinor: 1000, country: 'PL' }))
|
|
39
|
+
expect(purchase?.deadline).toBeUndefined()
|
|
40
|
+
expect((await service(fake).profile(ENTITY))?.locked).toBe(true)
|
|
41
|
+
expect((await service(fake).consentView(ENTITY)).required).toBe(false)
|
|
42
|
+
await service(fake).assertConsent(ENTITY)
|
|
43
|
+
expect((await service(fake).purchases(ENTITY))[0].withdrawable).toBe(false)
|
|
44
|
+
expect((await service(fake).withdrawalCandidates(ENTITY)).candidates).toEqual([])
|
|
45
|
+
expect(fake.state.refunds).toHaveLength(0)
|
|
46
|
+
expect(fake.observed.topUp[0]).toEqual(expect.objectContaining({ amountMinor: 1000 }))
|
|
47
|
+
})
|
|
48
|
+
|
|
34
49
|
test('an open in-scope window needs consent; the view names the purchase, deadline and billing language', async () => {
|
|
35
50
|
const fake = await makeRightsContext()
|
|
36
51
|
const purchase = await buyTopUp(fake)
|
|
@@ -224,6 +239,25 @@ describe('consumer rights — withdrawal of a top-up', () => {
|
|
|
224
239
|
expect(fake.observed.withdrawal[0].units).toEqual({ granted: 1_000, used: 400, returned: 350 })
|
|
225
240
|
})
|
|
226
241
|
|
|
242
|
+
test('a discounted withdrawal uses actual payment and applies the invoice discount once', async () => {
|
|
243
|
+
const fake = await withMeter(fixedMeter({ granted: 1000, used: 500, usedAfter: 500 }))
|
|
244
|
+
fake.state.invoices.in_discount = invoiceOf('in_discount', {
|
|
245
|
+
subtotal: 1000, tax: 100, total: 600, total_discount_amounts: [{ amount: 500 }],
|
|
246
|
+
lines: { data: [{ id: 'il_discount', amount: 1000 }] },
|
|
247
|
+
})
|
|
248
|
+
const purchase = await buyTopUp(fake, {
|
|
249
|
+
invoice: 'in_discount', amount_subtotal: 1000, amount_total: 600,
|
|
250
|
+
total_details: { amount_tax: 100, amount_discount: 500 }, metadata: { chargeAmountMinor: '1000' },
|
|
251
|
+
})
|
|
252
|
+
await consent(fake, purchase)
|
|
253
|
+
const receipt = await service(fake).withdraw(subject, { purchaseId: purchase.purchaseId, name: 'Anna', email: 'owner@shop.eu' })
|
|
254
|
+
expect(receipt.refundMinor).toBe(300)
|
|
255
|
+
expect(fake.state.refunds[0].amount).toBe(300)
|
|
256
|
+
expect(fake.state.creditNotePreviews[0].lines[0].amount).toBe(500)
|
|
257
|
+
expect(fake.state.creditNotes[0].total).toBe(300)
|
|
258
|
+
expect(fake.observed.withdrawal[0].units?.returned).toBe(500)
|
|
259
|
+
})
|
|
260
|
+
|
|
227
261
|
test('no invoice: a plain proportional refund; a failed preview falls back to it too', async () => {
|
|
228
262
|
const meter = fixedMeter({ granted: 1_000, used: 0, usedAfter: 0 })
|
|
229
263
|
const fake = await withMeter(meter)
|
package/tests/events.spec.ts
CHANGED
|
@@ -315,11 +315,21 @@ describe('@owlmeans/server-payment — refund and dispute events', () => {
|
|
|
315
315
|
'dispute:dp_1:opened', 'dispute:dp_1:funds-withdrawn', 'dispute:dp_1:funds-reinstated', 'dispute:dp_1:closed',
|
|
316
316
|
])
|
|
317
317
|
expect(fake.observed.dispute[0]).toEqual(expect.objectContaining({
|
|
318
|
+
paidMinor: 1225,
|
|
318
319
|
target: 'fulfillment', externalId: 'cs_1', amountMinor: 1225, netAmountMinor: 1000,
|
|
319
320
|
}))
|
|
320
321
|
expect(fake.stores['payment-fulfillment'].rows[0]).toEqual(expect.objectContaining({ disputeStatus: 'won', chargeId: 'ch_1' }))
|
|
321
322
|
expect(fake.stores['payment-fulfillment'].rows[0].disputedAt).toBeInstanceOf(Date)
|
|
322
323
|
})
|
|
324
|
+
|
|
325
|
+
test('a discounted dispute resolved by payment intent carries the actual charge including tax', async () => {
|
|
326
|
+
const fake = await fulfilled()
|
|
327
|
+
fake.state.charges.ch_1.amount = 600
|
|
328
|
+
await send(fake, 'charge.dispute.funds_withdrawn', {
|
|
329
|
+
id: 'dp_discount', amount: 600, currency: 'usd', charge: 'ch_1', payment_intent: 'pi_1', status: 'needs_response',
|
|
330
|
+
})
|
|
331
|
+
expect(fake.observed.dispute[0]).toEqual(expect.objectContaining({ paidMinor: 600, netAmountMinor: 1000, chargeAmountMinor: 1021 }))
|
|
332
|
+
})
|
|
323
333
|
})
|
|
324
334
|
|
|
325
335
|
describe('@owlmeans/server-payment — resync and internal grants', () => {
|