From 508d8c10bbb659bba7aaa5408a349af6937047f4 Mon Sep 17 00:00:00 2001 From: Priyanshubhartistm Date: Mon, 9 Nov 2026 15:17:43 +0530 Subject: [PATCH 1/3] fix(payments): do not downgrade a pubkey whose dearer plan is still running Signed-off-by: Priyanshubhartistm --- .../subscription-third-party-plan-change.md | 5 + CONFIGURATION.md | 2 +- src/services/payments-service.ts | 5 +- src/utils/subscription.ts | 30 +++++ test/unit/services/payments-service.spec.ts | 62 ++++++++++ test/unit/utils/subscription.spec.ts | 106 ++++++++++++++++++ 6 files changed, 208 insertions(+), 2 deletions(-) create mode 100644 .changeset/subscription-third-party-plan-change.md diff --git a/.changeset/subscription-third-party-plan-change.md b/.changeset/subscription-third-party-plan-change.md new file mode 100644 index 000000000..ec2c4cc6b --- /dev/null +++ b/.changeset/subscription-third-party-plan-change.md @@ -0,0 +1,5 @@ +--- +"nostream": patch +--- + +fix(payments): a payment for a cheaper plan no longer downgrades a pubkey whose dearer plan is still running diff --git a/CONFIGURATION.md b/CONFIGURATION.md index cd405d227..5a2e6b372 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -256,7 +256,7 @@ The settings below are listed in alphabetical order by name. Please keep this ta | payments.feeSchedules.admission[].whitelists.event_kinds | List of event kinds to waive admission fee. Use `[min, max]` for ranges. | | payments.feeSchedules.admission[].whitelists.pubkeys | List of pubkeys to waive admission fee. | | payments.processor | Either `zebedee`, `lnbits`, `lnurl`. | -| payments.subscriptionPlans | Recurring membership plans. Leave empty to keep the one-time admission fee. With plans and `payments.enabled`, `POST /invoices` takes a `planId` instead of a fee schedule, a payment of at least the plan price starts or extends a period (from the period end while access is still running, otherwise from now), and writes need an active subscription or grace period. Admitted users with no subscription keep access. About three days before a period ends the relay creates a renewal invoice and sends it to the subscriber in a kind 402 event, replacing it if it expires unpaid; it moves the subscription through grace to expired once the period and grace pass without payment. Users still have to pay renewal invoices themselves, since Lightning cannot be charged automatically. The invoice page lets users pick a plan. Clients see the plans in the NIP-11 document under `fees.subscription` (`id`, `amount` in msats, `unit`, `period` in seconds, and `description` when set), and with plans `limitation.restricted_writes` is true. `GET /subscriptions/status?pubkey=` returns a pubkey's `planId`, `status`, `active`, `currentPeriodEnd` and `accessEndsAt` (without a subscription `active` is false and the other fields are null), counted against `limits.invoice.rateLimits`; it answers 404 while plans are off. | +| payments.subscriptionPlans | Recurring membership plans. Leave empty to keep the one-time admission fee. With plans and `payments.enabled`, `POST /invoices` takes a `planId` instead of a fee schedule, a payment of at least the plan price starts or extends a period (from the period end while access is still running, otherwise from now), and writes need an active subscription or grace period. Admitted users with no subscription keep access. About three days before a period ends the relay creates a renewal invoice and sends it to the subscriber in a kind 402 event, replacing it if it expires unpaid; it moves the subscription through grace to expired once the period and grace pass without payment. Users still have to pay renewal invoices themselves, since Lightning cannot be charged automatically. The invoice page lets users pick a plan. Anyone can pay an invoice for any pubkey, so while a period of a dearer plan is running, a payment for a cheaper plan for that pubkey does not switch its plan: the money is credited to the plan it has, as the share of one of its periods it pays for. Paying for the same or a dearer plan, or after the running period has ended, takes effect as before. Clients see the plans in the NIP-11 document under `fees.subscription` (`id`, `amount` in msats, `unit`, `period` in seconds, and `description` when set), and with plans `limitation.restricted_writes` is true. `GET /subscriptions/status?pubkey=` returns a pubkey's `planId`, `status`, `active`, `currentPeriodEnd` and `accessEndsAt` (without a subscription `active` is false and the other fields are null), counted against `limits.invoice.rateLimits`; it answers 404 while plans are off. | | payments.subscriptionPlans[].id | Unique plan name, for example `basic`. `grandfathered` is reserved: users admitted before plans existed are moved onto it and keep access without a paid period. | | payments.subscriptionPlans[].amount | Price of one period in msats. Must be unique across plans. A payment below it does not start or extend a period. | | payments.subscriptionPlans[].intervalSeconds | Length of one paid period, in seconds. | diff --git a/src/services/payments-service.ts b/src/services/payments-service.ts index 41cfb112e..36f6ec3f3 100644 --- a/src/services/payments-service.ts +++ b/src/services/payments-service.ts @@ -219,7 +219,10 @@ export class PaymentsService implements IPaymentsService { const date = new Date() const existing = await this.userSubscriptionRepository.findByPubkey(invoice.pubkey, transaction.transaction) await this.userSubscriptionRepository.upsert( - applyPayment(invoice.pubkey, existing, plan, date), + applyPayment(invoice.pubkey, existing, plan, date, { + existingPlan: findSubscriptionPlan(currentSettings, existing?.planId), + paidMsat: amountPaidMsat, + }), transaction.transaction, ) await this.userRepository.admitUser(invoice.pubkey, date, transaction.transaction) diff --git a/src/utils/subscription.ts b/src/utils/subscription.ts index cd445aa51..1faa06dee 100644 --- a/src/utils/subscription.ts +++ b/src/utils/subscription.ts @@ -52,12 +52,18 @@ export const hasSubscriptionAccess = (subscription: UserSubscription | undefined * The subscription after a payment for `plan`. A payment made while access is still running * extends it from the current period end, so paying early costs nothing. After access has * lapsed, or on the never-ending grandfathered plan, the new period starts now. + * + * Anyone can pay an invoice for any pubkey, so a payment must not take away what the pubkey already has paid for. While + * a period of a dearer plan is running, a payment for a cheaper plan therefore does not switch the plan (its lower limits + * and shorter retention would take effect at once, and the purge would delete events the dearer plan keeps). The money + * is credited to the plan the pubkey has, as the share of one of its periods it pays for. */ export const applyPayment = ( pubkey: Pubkey, existing: UserSubscription | undefined, plan: SubscriptionPlan, now: Date, + context: { existingPlan?: SubscriptionPlan; paidMsat?: bigint } = {}, ): Omit => { const stillRunning = existing && @@ -66,6 +72,30 @@ export const applyPayment = ( (existing.status === SubscriptionStatus.ACTIVE || existing.status === SubscriptionStatus.RENEWAL_PENDING) && existing.currentPeriodEnd.getTime() > now.getTime() + const { existingPlan } = context + if ( + stillRunning && + existingPlan && + existingPlan.id === existing.planId && + BigInt(plan.amount) < BigInt(existingPlan.amount) + ) { + // The share of a period of the plan the pubkey has that the payment covers, in milliseconds. + const paidMsat = context.paidMsat ?? BigInt(plan.amount) + const creditMs = Number((BigInt(existingPlan.intervalSeconds) * 1000n * paidMsat) / BigInt(existingPlan.amount)) + const periodEnd = new Date((existing.currentPeriodEnd as Date).getTime() + creditMs) + + return { + pubkey, + planId: existing.planId, + status: SubscriptionStatus.ACTIVE, + currentPeriodStart: existing.currentPeriodStart, + currentPeriodEnd: periodEnd, + graceEndsAt: + existingPlan.graceSeconds > 0 ? new Date(periodEnd.getTime() + existingPlan.graceSeconds * 1000) : null, + cancelAtPeriodEnd: false, + } + } + const periodStart = stillRunning ? (existing.currentPeriodEnd as Date) : now const periodEnd = new Date(periodStart.getTime() + plan.intervalSeconds * 1000) diff --git a/test/unit/services/payments-service.spec.ts b/test/unit/services/payments-service.spec.ts index 2fe8ab6dd..c8a5c8135 100644 --- a/test/unit/services/payments-service.spec.ts +++ b/test/unit/services/payments-service.spec.ts @@ -567,6 +567,68 @@ describe('PaymentsService', () => { expect(subscription.currentPeriodEnd).to.deep.equal(new Date(periodEnd.getTime() + 30 * DAY)) }) + it('does not switch a pubkey from a dearer plan to a cheaper one that somebody paid for it, and credits the money to the plan it has', async () => { + const premium = { id: 'premium', amount: 25_000_000n, intervalSeconds: 2_592_000, graceSeconds: 259_200 } + settings.returns(plansSettings([plan, premium])) + const periodEnd = new Date(Date.now() + 5 * DAY) + userSubscriptionRepository.findByPubkey.resolves({ + pubkey: 'pubkey1234', + planId: 'premium', + status: 'active', + currentPeriodStart: new Date(Date.now() - 25 * DAY), + currentPeriodEnd: periodEnd, + graceEndsAt: null, + cancelAtPeriodEnd: false, + }) + + await service.confirmInvoice(makeCompletedInvoice({ amountPaid: 5_000_000n })) + + const [subscription] = userSubscriptionRepository.upsert.firstCall.args + expect(subscription.planId).to.equal('premium') + // the cheaper plan costs a fifth of premium, so it buys a fifth of a premium period: six days + expect(subscription.currentPeriodEnd).to.deep.equal(new Date(periodEnd.getTime() + 6 * DAY)) + expect(userSubscriptionRepository.upsert).to.have.been.calledOnce + }) + + it('credits what was actually paid, converted to msats, not the price of the plan', async () => { + const premium = { id: 'premium', amount: 25_000_000n, intervalSeconds: 2_592_000, graceSeconds: 259_200 } + settings.returns(plansSettings([plan, premium])) + const periodEnd = new Date(Date.now() + 5 * DAY) + userSubscriptionRepository.findByPubkey.resolves({ + pubkey: 'pubkey1234', + planId: 'premium', + status: 'active', + currentPeriodStart: new Date(Date.now() - 25 * DAY), + currentPeriodEnd: periodEnd, + graceEndsAt: null, + cancelAtPeriodEnd: false, + }) + + // 10,000 sats = 10,000,000 msats, twice the price of the cheaper plan + await service.confirmInvoice(makeCompletedInvoice({ unit: InvoiceUnit.SATS, amountPaid: 10_000n })) + + const [subscription] = userSubscriptionRepository.upsert.firstCall.args + expect(subscription.currentPeriodEnd).to.deep.equal(new Date(periodEnd.getTime() + 12 * DAY)) + }) + + it('moves a pubkey up to a dearer plan that somebody paid for it', async () => { + const lite = { id: 'lite', amount: 1_000_000n, intervalSeconds: 2_592_000, graceSeconds: 259_200 } + settings.returns(plansSettings([lite, plan])) + userSubscriptionRepository.findByPubkey.resolves({ + pubkey: 'pubkey1234', + planId: 'lite', + status: 'active', + currentPeriodStart: new Date(Date.now() - 25 * DAY), + currentPeriodEnd: new Date(Date.now() + 5 * DAY), + graceEndsAt: null, + cancelAtPeriodEnd: false, + }) + + await service.confirmInvoice(makeCompletedInvoice({ amountPaid: 5_000_000n })) + + expect(userSubscriptionRepository.upsert.firstCall.args[0].planId).to.equal('basic') + }) + it('does not extend the subscription again for a repeated callback of an invoice that was already confirmed', async () => { invoiceRepository.findById.resolves(stubInvoice({ planId: 'basic', confirmedAt: new Date() })) diff --git a/test/unit/utils/subscription.spec.ts b/test/unit/utils/subscription.spec.ts index 901de7b9e..4a1c33e3f 100644 --- a/test/unit/utils/subscription.spec.ts +++ b/test/unit/utils/subscription.spec.ts @@ -211,6 +211,112 @@ describe('subscription utils', () => { expect(result.graceEndsAt).to.equal(null) }) + describe('a payment for a cheaper plan while a dearer plan is running', () => { + // premium costs five times basic, over the same 30 days + const premium: SubscriptionPlan = { ...plan, id: 'premium', amount: 5_000_000n, graceSeconds: 5 * 86_400 } + const running = subscription({ + planId: 'premium', + currentPeriodStart: at(-25 * DAY), + currentPeriodEnd: at(5 * DAY), + graceEndsAt: at(10 * DAY), + }) + const paidFor = (paid: bigint = plan.amount) => + applyPayment(pubkey, running, plan, NOW, { existingPlan: premium, paidMsat: paid }) + + it('keeps the plan the pubkey has, whoever paid', () => { + expect(paidFor().planId).to.equal('premium') + }) + + it('credits what was paid as the share of a premium period it covers, after the running period', () => { + // a fifth of the price of premium is a fifth of its 30 days: 6 days + expect(paidFor().currentPeriodEnd).to.deep.equal(at(5 * DAY + 6 * DAY)) + }) + + it('credits more for paying more than the price of the cheaper plan', () => { + expect(paidFor(2_000_000n).currentPeriodEnd).to.deep.equal(at(5 * DAY + 12 * DAY)) + }) + + it('moves the grace along with the end, by the grace of the plan the pubkey has', () => { + expect(paidFor().graceEndsAt).to.deep.equal(at(5 * DAY + 6 * DAY + 5 * DAY)) + }) + + it('leaves the start of the running period where it is', () => { + expect(paidFor().currentPeriodStart).to.deep.equal(at(-25 * DAY)) + }) + + it('does not take the plan away from a pubkey whose renewal is pending either', () => { + const pending = { ...running, status: SubscriptionStatus.RENEWAL_PENDING } + + const result = applyPayment(pubkey, pending, plan, NOW, { existingPlan: premium, paidMsat: plan.amount }) + + expect(result.planId).to.equal('premium') + expect(result.status).to.equal(SubscriptionStatus.ACTIVE) + }) + + it('gives a plan with no grace no grace end', () => { + const result = applyPayment(pubkey, running, plan, NOW, { + existingPlan: { ...premium, graceSeconds: 0 }, + paidMsat: plan.amount, + }) + + expect(result.graceEndsAt).to.equal(null) + }) + + it('never shortens what the pubkey has', () => { + expect(paidFor(0n).currentPeriodEnd).to.deep.equal(running.currentPeriodEnd) + expect(paidFor().currentPeriodEnd!.getTime()).to.be.greaterThan(running.currentPeriodEnd!.getTime()) + }) + + it('assumes the price of the plan when it is not told what was paid', () => { + const result = applyPayment(pubkey, running, plan, NOW, { existingPlan: premium }) + + expect(result.currentPeriodEnd).to.deep.equal(at(5 * DAY + 6 * DAY)) + }) + + it('still switches once the running period has ended, since nothing paid for is taken away', () => { + const lapsed = { ...running, status: SubscriptionStatus.PAST_DUE, currentPeriodEnd: at(-DAY) } + + const result = applyPayment(pubkey, lapsed, plan, NOW, { existingPlan: premium, paidMsat: plan.amount }) + + expect(result.planId).to.equal('basic') + expect(result.currentPeriodStart).to.deep.equal(NOW) + }) + + it('still switches when the pubkey has no running plan to protect', () => { + const result = applyPayment(pubkey, undefined, plan, NOW, { existingPlan: premium, paidMsat: plan.amount }) + + expect(result.planId).to.equal('basic') + }) + + it('still switches when the plan the pubkey had was removed from the settings, since there is nothing to compare', () => { + const result = applyPayment(pubkey, running, plan, NOW, { paidMsat: plan.amount }) + + expect(result.planId).to.equal('basic') + }) + }) + + describe('a payment for a dearer plan, or for the plan the pubkey has', () => { + const premium: SubscriptionPlan = { ...plan, id: 'premium', amount: 5_000_000n } + const runningBasic = subscription({ currentPeriodStart: at(-25 * DAY), currentPeriodEnd: at(5 * DAY) }) + + it('moves up to the dearer plan, which takes nothing away', () => { + const result = applyPayment(pubkey, runningBasic, premium, NOW, { + existingPlan: plan, + paidMsat: premium.amount, + }) + + expect(result.planId).to.equal('premium') + expect(result.currentPeriodStart).to.deep.equal(at(5 * DAY)) + }) + + it('extends the plan the pubkey has from the end of its period', () => { + const result = applyPayment(pubkey, runningBasic, plan, NOW, { existingPlan: plan, paidMsat: plan.amount }) + + expect(result.planId).to.equal('basic') + expect(result.currentPeriodEnd).to.deep.equal(at(35 * DAY)) + }) + }) + it('uses the paid plan, so a plan change takes effect on payment', () => { const premium = { ...plan, id: 'premium', intervalSeconds: 7 * 86_400 } From 6b4fd7956e203bc7e9124f79f7aa9c7c9dfbe444 Mon Sep 17 00:00:00 2001 From: Priyanshubhartistm Date: Mon, 9 Nov 2026 16:27:25 +0530 Subject: [PATCH 2/3] fix(payments): keep a pending renewal pending when a cheaper plan is credited Signed-off-by: Priyanshubhartistm --- src/utils/subscription.ts | 4 +++- test/unit/utils/subscription.spec.ts | 8 ++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/utils/subscription.ts b/src/utils/subscription.ts index 1faa06dee..f06c77b7e 100644 --- a/src/utils/subscription.ts +++ b/src/utils/subscription.ts @@ -87,7 +87,9 @@ export const applyPayment = ( return { pubkey, planId: existing.planId, - status: SubscriptionStatus.ACTIVE, + // Not paid for the renewal that may be waiting: a pending renewal invoice is still payable, and moving the + // subscription back to active would let the next sweep issue a second one if the credit leaves the end near. + status: existing.status, currentPeriodStart: existing.currentPeriodStart, currentPeriodEnd: periodEnd, graceEndsAt: diff --git a/test/unit/utils/subscription.spec.ts b/test/unit/utils/subscription.spec.ts index 4a1c33e3f..3ceeef6c0 100644 --- a/test/unit/utils/subscription.spec.ts +++ b/test/unit/utils/subscription.spec.ts @@ -244,13 +244,17 @@ describe('subscription utils', () => { expect(paidFor().currentPeriodStart).to.deep.equal(at(-25 * DAY)) }) - it('does not take the plan away from a pubkey whose renewal is pending either', () => { + it('keeps a pending renewal pending, since its invoice is still payable and a second one must not be issued', () => { const pending = { ...running, status: SubscriptionStatus.RENEWAL_PENDING } const result = applyPayment(pubkey, pending, plan, NOW, { existingPlan: premium, paidMsat: plan.amount }) expect(result.planId).to.equal('premium') - expect(result.status).to.equal(SubscriptionStatus.ACTIVE) + expect(result.status).to.equal(SubscriptionStatus.RENEWAL_PENDING) + }) + + it('keeps an active subscription active', () => { + expect(paidFor().status).to.equal(SubscriptionStatus.ACTIVE) }) it('gives a plan with no grace no grace end', () => { From 3598b5fe3607784fb3fffaa6b875dda31dc96c90 Mon Sep 17 00:00:00 2001 From: Priyanshubhartistm Date: Mon, 9 Nov 2026 20:15:17 +0530 Subject: [PATCH 3/3] test(payments): cover paying for another plan while a subscription runs Signed-off-by: Priyanshubhartistm --- .../subscription-plan-change.feature | 46 ++++++ .../subscription-plan-change.feature.ts | 144 ++++++++++++++++++ 2 files changed, 190 insertions(+) create mode 100644 test/integration/features/subscriptions/subscription-plan-change.feature create mode 100644 test/integration/features/subscriptions/subscription-plan-change.feature.ts diff --git a/test/integration/features/subscriptions/subscription-plan-change.feature b/test/integration/features/subscriptions/subscription-plan-change.feature new file mode 100644 index 000000000..3aa1aab4b --- /dev/null +++ b/test/integration/features/subscriptions/subscription-plan-change.feature @@ -0,0 +1,46 @@ +@opennode-callback @subscription-plan-change +Feature: Paying for another plan while a subscription is running + Anyone can pay an invoice for any pubkey, so a payment for a cheaper plan must not take away + what the pubkey has already paid for. The plan limits "basic" (21000 sats) and "pro" (100000 sats) + are each one period of 30 days. + + Scenario: a cheaper plan paid for a running dearer plan is credited to the dearer plan + Given OpenNode callback processing is enabled + And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats + And a subscriber has a running "pro" plan that ends in 10 days + And a pending OpenNode invoice for the subscriber for 21000 sats on the plan "basic" exists + When I post a signed OpenNode callback with status "paid" + Then the OpenNode callback response status is 200 + And the subscriber is still on the plan "pro" + And the subscriber's plan ends 6.3 days later than before + And the subscriber has been admitted to the relay + + Scenario: a repeated callback does not credit the payment twice + Given OpenNode callback processing is enabled + And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats + And a subscriber has a running "pro" plan that ends in 10 days + And a pending OpenNode invoice for the subscriber for 21000 sats on the plan "basic" exists + When I post a signed OpenNode callback with status "paid" + And I post a signed OpenNode callback with status "paid" + Then the subscriber is still on the plan "pro" + And the subscriber's plan ends 6.3 days later than before + + Scenario: a dearer plan paid for a running cheaper plan switches the plan + Given OpenNode callback processing is enabled + And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats + And a subscriber has a running "basic" plan that ends in 10 days + And a pending OpenNode invoice for the subscriber for 100000 sats on the plan "pro" exists + When I post a signed OpenNode callback with status "paid" + Then the OpenNode callback response status is 200 + And the subscriber is on the plan "pro" + And the subscriber's plan ends 30 days later than before + + Scenario: a cheaper plan paid by a pubkey with no subscription starts that plan + Given OpenNode callback processing is enabled + And the relay sells the plans "basic" at 21000 sats and "pro" at 100000 sats + And a subscriber without a subscription + And a pending OpenNode invoice for the subscriber for 21000 sats on the plan "basic" exists + When I post a signed OpenNode callback with status "paid" + Then the OpenNode callback response status is 200 + And the subscriber is on the plan "basic" + And the subscriber has been admitted to the relay diff --git a/test/integration/features/subscriptions/subscription-plan-change.feature.ts b/test/integration/features/subscriptions/subscription-plan-change.feature.ts new file mode 100644 index 000000000..33beaa290 --- /dev/null +++ b/test/integration/features/subscriptions/subscription-plan-change.feature.ts @@ -0,0 +1,144 @@ +import { After, Given, Then } from '@cucumber/cucumber' +import { expect } from 'chai' +import { randomBytes, randomUUID } from 'crypto' + +import { getMasterDbClient } from '../../../../src/database/client' +import { SettingsStatic } from '../../../../src/utils/settings' + +const DAY_MS = 24 * 60 * 60 * 1000 +const PLAN_INTERVAL_SECONDS = 30 * 24 * 60 * 60 + +const readSubscription = async (pubkey: Buffer) => { + const row = await getMasterDbClient()('user_subscriptions') + .where('pubkey', pubkey) + .first('plan_id', 'status', 'current_period_start', 'current_period_end') + + expect(row, 'the subscriber has no subscription').to.exist + + return row +} + +Given( + 'the relay sells the plans {string} at {int} sats and {string} at {int} sats', + function (firstId: string, firstSats: number, secondId: string, secondSats: number) { + const settings = SettingsStatic._settings as any + const plan = (id: string, sats: number) => ({ + id, + amount: BigInt(sats) * 1000n, + intervalSeconds: PLAN_INTERVAL_SECONDS, + graceSeconds: DAY_MS / 1000, + }) + + // The OpenNode callback steps restore the settings they replaced once the scenario ends. + SettingsStatic._settings = { + ...settings, + payments: { + ...settings.payments, + subscriptionPlans: [plan(firstId, firstSats), plan(secondId, secondSats)], + }, + } + }, +) + +const createSubscriber = async (world: any, subscription?: { planId: string; endsInDays: number }) => { + const dbClient = getMasterDbClient() + const pubkey = randomBytes(32) + + await dbClient('users').insert({ pubkey, is_admitted: false }) + world.parameters.subscriberPubkey = pubkey + world.parameters.subscriberPubkeys = [...(world.parameters.subscriberPubkeys ?? []), pubkey] + + if (!subscription) { + return + } + + const now = Date.now() + const periodEnd = new Date(now + subscription.endsInDays * DAY_MS) + await dbClient('user_subscriptions').insert({ + pubkey, + plan_id: subscription.planId, + status: 'active', + current_period_start: new Date(now - (30 - subscription.endsInDays) * DAY_MS), + current_period_end: periodEnd, + grace_ends_at: new Date(periodEnd.getTime() + DAY_MS), + }) + await dbClient('users').where('pubkey', pubkey).update({ is_admitted: true }) + + world.parameters.subscriptionEndBefore = (await readSubscription(pubkey)).current_period_end as Date +} + +Given( + 'a subscriber has a running {string} plan that ends in {int} days', + async function (planId: string, days: number) { + await createSubscriber(this, { planId, endsInDays: days }) + }, +) + +Given('a subscriber without a subscription', async function () { + await createSubscriber(this) +}) + +Given( + 'a pending OpenNode invoice for the subscriber for {int} sats on the plan {string} exists', + async function (sats: number, planId: string) { + const invoiceId = `integration-subscription-${randomUUID()}` + + await getMasterDbClient()('invoices').insert({ + id: invoiceId, + pubkey: this.parameters.subscriberPubkey, + bolt11: 'lnbc210n1integration', + amount_requested: String(sats), + unit: 'sats', + status: 'pending', + description: 'subscription plan change integration test', + plan_id: planId, + expires_at: new Date(Date.now() + 15 * 60 * 1000), + updated_at: new Date(), + created_at: new Date(), + }) + + // The OpenNode callback steps post for, and clean up, this invoice. + this.parameters.openNodeInvoiceId = invoiceId + this.parameters.openNodeInvoiceIds = [...(this.parameters.openNodeInvoiceIds ?? []), invoiceId] + }, +) + +Then('the subscriber is still on the plan {string}', async function (planId: string) { + const subscription = await readSubscription(this.parameters.subscriberPubkey) + + expect(subscription.plan_id).to.equal(planId) + // The payment was credited to the running plan, so the subscription is neither restarted nor ended. + expect(subscription.status).to.equal('active') +}) + +Then('the subscriber is on the plan {string}', async function (planId: string) { + const subscription = await readSubscription(this.parameters.subscriberPubkey) + + expect(subscription.plan_id).to.equal(planId) + expect(subscription.status).to.equal('active') +}) + +Then("the subscriber's plan ends {float} days later than before", async function (days: number) { + const subscription = await readSubscription(this.parameters.subscriberPubkey) + const before = this.parameters.subscriptionEndBefore as Date + + expect(subscription.current_period_end.getTime() - before.getTime()).to.equal(Math.round(days * DAY_MS)) +}) + +Then('the subscriber has been admitted to the relay', async function () { + const user = await getMasterDbClient()('users').where('pubkey', this.parameters.subscriberPubkey).first('is_admitted') + + expect(user.is_admitted).to.equal(true) +}) + +After({ tags: '@subscription-plan-change' }, async function () { + const pubkeys = this.parameters.subscriberPubkeys ?? [] + if (pubkeys.length > 0) { + // The subscription goes with the user, whose row it references. + await getMasterDbClient()('users').whereIn('pubkey', pubkeys).delete() + } + + this.parameters.subscriberPubkey = undefined + this.parameters.subscriberPubkeys = [] + this.parameters.subscriptionEndBefore = undefined +})