@owlmeans/server-payment 0.1.18 → 0.1.19-rc.0

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.
@@ -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)
@@ -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', () => {
@@ -326,20 +326,26 @@ export const makeFakeStripe = (initial: Partial<FakeStripeState> = {}): { stripe
326
326
  state.creditNotePreviews.push(structuredClone(params))
327
327
  const invoice = state.invoices[params.invoice]
328
328
  if (invoice == null) throw missing('invoice')
329
- const rate = invoice.subtotal > 0 ? (invoice.tax ?? 0) / invoice.subtotal : 0
329
+ const discount = (invoice.total_discount_amounts ?? []).reduce((sum: number, item: Rec) => sum + item.amount, 0)
330
+ const net = invoice.subtotal - discount
331
+ const rate = net > 0 ? (invoice.tax ?? 0) / net : 0
330
332
  const amount = params.lines.reduce((sum: number, line: Rec) => sum + (line.amount ?? 0), 0)
331
- const tax = Math.round(amount * rate)
332
- return { id: 'cnpreview', object: 'credit_note', amount: amount + tax, total: amount + tax, subtotal: amount, currency: invoice.currency }
333
+ const discounted = amount - (invoice.subtotal > 0 ? Math.round(amount * discount / invoice.subtotal) : 0)
334
+ const tax = Math.round(discounted * rate)
335
+ return { id: 'cnpreview', object: 'credit_note', amount: discounted + tax, total: discounted + tax, subtotal: amount, currency: invoice.currency }
333
336
  },
334
337
  create: async (params: Rec, options?: Rec) => {
335
338
  call('creditNotes.create', options)
336
339
  const invoice = state.invoices[params.invoice]
337
340
  if (invoice == null) throw missing('invoice')
338
- const rate = invoice.subtotal > 0 ? (invoice.tax ?? 0) / invoice.subtotal : 0
341
+ const discount = (invoice.total_discount_amounts ?? []).reduce((sum: number, item: Rec) => sum + item.amount, 0)
342
+ const net = invoice.subtotal - discount
343
+ const rate = net > 0 ? (invoice.tax ?? 0) / net : 0
339
344
  const amount = params.lines.reduce((sum: number, line: Rec) => sum + (line.amount ?? 0), 0)
345
+ const discounted = amount - (invoice.subtotal > 0 ? Math.round(amount * discount / invoice.subtotal) : 0)
340
346
  const note = {
341
347
  id: next('cn'), object: 'credit_note', invoice: params.invoice, refund: params.refund, status: 'issued',
342
- total: amount + Math.round(amount * rate), currency: invoice.currency, memo: params.memo,
348
+ total: discounted + Math.round(discounted * rate), currency: invoice.currency, memo: params.memo,
343
349
  metadata: { ...params.metadata }, lines: structuredClone(params.lines),
344
350
  }
345
351
  state.creditNotes.push(note)