/api/administrator/subscriptions/set-subscription-coupon (PATCH)
Account information like email addresses is generated with faker-js it is not real user information.
await global.api.administrator.subscriptions.SetSubscriptionCoupon.patch(req)Returns object
{
"subscriptionid": "sub_1LEOTPHHqepMFuCXwz4PLsaQ",
"object": "subscription",
"stripeObject": {
"id": "sub_1LEOTPHHqepMFuCXwz4PLsaQ",
"object": "subscription",
"application": null,
"application_fee_percent": null,
"automatic_tax": {
"enabled": false
},
"billing_cycle_anchor": 1656123107,
"billing_thresholds": null,
"cancel_at": null,
"cancel_at_period_end": false,
"canceled_at": null,
"collection_method": "charge_automatically",
"created": 1656123107,
"current_period_end": 1658715107,
"current_period_start": 1656123107,
"customer": "cus_LwH1St1PPmCCcr",
"days_until_due": null,
"default_payment_method": "pm_1LEOTMHHqepMFuCXvilL86t0",
"default_source": null,
"default_tax_rates": [],
"description": null,
"discount": {
"id": "di_1LEOTTHHqepMFuCXUAT77fdo",
"object": "discount",
"checkout_session": null,
"coupon": {
"id": "COUPON43",
"object": "coupon",
"amount_off": 42,
"created": 1656123086,
"currency": "usd",
"duration": "repeating",
"duration_in_months": 3,
"livemode": false,
"max_redemptions": 192,
"metadata": {},
"name": "coupon name",
"percent_off": null,
"redeem_by": null,
"times_redeemed": 2,
"valid": true
},
"customer": "cus_LwH1St1PPmCCcr",
"end": 1664071911,
"invoice": null,
"invoice_item": null,
"promotion_code": null,
"start": 1656123111,
"subscription": "sub_1LEOTPHHqepMFuCXwz4PLsaQ"
},
"ended_at": null,
"items": {
"object": "list",
"data": [
{
"id": "si_LwH1G7MCY9uHZt",
"object": "subscription_item",
"billing_thresholds": null,
"created": 1656123108,
"metadata": {},
"plan": {
"id": "price_1LEOT4HHqepMFuCXa9rC4zqd",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 1000,
"amount_decimal": "1000",
"billing_scheme": "per_unit",
"created": 1656123086,
"currency": "usd",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {},
"nickname": null,
"product": "prod_LwH1dfcrGlyUgZ",
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
},
"price": {
"id": "price_1LEOT4HHqepMFuCXa9rC4zqd",
"object": "price",
"active": true,
"billing_scheme": "per_unit",
"created": 1656123086,
"currency": "usd",
"custom_unit_amount": null,
"livemode": false,
"lookup_key": null,
"metadata": {},
"nickname": null,
"product": "prod_LwH1dfcrGlyUgZ",
"recurring": {
"aggregate_usage": null,
"interval": "month",
"interval_count": 1,
"trial_period_days": null,
"usage_type": "licensed"
},
"tax_behavior": "inclusive",
"tiers_mode": null,
"transform_quantity": null,
"type": "recurring",
"unit_amount": 1000,
"unit_amount_decimal": "1000"
},
"quantity": 1,
"subscription": "sub_1LEOTPHHqepMFuCXwz4PLsaQ",
"tax_rates": []
}
],
"has_more": false,
"total_count": 1,
"url": "/v1/subscription_items?subscription=sub_1LEOTPHHqepMFuCXwz4PLsaQ"
},
"latest_invoice": "in_1LEOTPHHqepMFuCXWjdXxNx2",
"livemode": false,
"metadata": {},
"next_pending_invoice_item_invoice": null,
"pause_collection": null,
"payment_settings": {
"payment_method_options": null,
"payment_method_types": null,
"save_default_payment_method": "off"
},
"pending_invoice_item_interval": null,
"pending_setup_intent": null,
"pending_update": null,
"plan": {
"id": "price_1LEOT4HHqepMFuCXa9rC4zqd",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 1000,
"amount_decimal": "1000",
"billing_scheme": "per_unit",
"created": 1656123086,
"currency": "usd",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {},
"nickname": null,
"product": "prod_LwH1dfcrGlyUgZ",
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
},
"quantity": 1,
"schedule": null,
"start_date": 1656123107,
"status": "active",
"test_clock": null,
"transfer_data": null,
"trial_end": null,
"trial_start": null
},
"customerid": "cus_LwH1St1PPmCCcr",
"accountid": "acct_bb9408fea1663335",
"paymentmethodid": null,
"productid": null,
"priceids": [
"price_1LEOT4HHqepMFuCXa9rC4zqd"
],
"couponid": "COUPON43",
"appid": "tests_1656123085",
"createdAt": "2022-06-25T02:11:49.703Z",
"updatedAt": "2022-06-25T02:11:51.619Z"
}
Exceptions
These exceptions are thrown (NodeJS) or returned as JSON (HTTP) if you provide incorrect data or do not meet the requirements:
Exception | Circumstances |
---|---|
invalid-couponid | missing posted couponid |
invalid posted couponid | |
invalid-subscription | ineligible subscription is canceling |
ineligible subscription has coupon | |
invalid-subscriptionid | missing querystring subscriptionid |
invalid querystring subscriptionid |
NodeJS source (view on github)
const dashboard = require('@layeredapps/dashboard')
const subscriptions = require('../../../../../index.js')
const stripeCache = require('../../../../stripe-cache.js')
module.exports = {
patch: async (req) => {
if (!req.query || !req.query.subscriptionid) {
throw new Error('invalid-subscriptionid')
}
if (!req.body || !req.body.couponid) {
throw new Error('invalid-couponid')
}
const subscription = await global.api.administrator.subscriptions.Subscription.get(req)
if (!subscription) {
throw new Error('invalid-subscriptionid')
}
if (subscription.stripeObject.discount && subscription.stripeObject.discount.coupon && subscription.stripeObject.discount.coupon.id) {
throw new Error('invalid-subscription')
}
if ((subscription.stripeObject.status !== 'active' && subscription.stripeObject.status !== 'trialing') || subscription.stripeObject.cancel_at_period_end) {
throw new Error('invalid-subscription')
}
req.query.couponid = req.body.couponid
const coupon = await global.api.administrator.subscriptions.Coupon.get(req)
if (!coupon) {
throw new Error('invalid-couponid')
}
const subscriptionInfo = {
coupon: req.body.couponid
}
const subscriptionNow = await stripeCache.execute('subscriptions', 'update', req.query.subscriptionid, subscriptionInfo, req.stripeKey)
await subscriptions.Storage.Subscription.update({
stripeObject: subscriptionNow,
couponid: req.body.couponid
}, {
where: {
subscriptionid: req.query.subscriptionid,
appid: req.appid || global.appid
}
})
await dashboard.StorageCache.remove(req.query.subscriptionid)
return global.api.administrator.subscriptions.Subscription.get(req)
}
}
Test source (view on github)
/* eslint-env mocha */
const assert = require('assert')
const TestHelper = require('../../../../../test-helper.js')
const TestStripeAccounts = require('../../../../../test-stripe-accounts.js')
const DashboardTestHelper = require('@layeredapps/dashboard/test-helper.js')
describe('/api/administrator/subscriptions/set-subscription-coupon', function () {
before(TestHelper.disableMetrics)
after(TestHelper.enableMetrics)
let cachedResponses
async function bundledData (retryNumber) {
if (retryNumber > 0) {
cachedResponses = {}
}
if (cachedResponses && cachedResponses.finished) {
return
}
cachedResponses = {}
await TestHelper.setupBefore()
await DashboardTestHelper.setupBeforeEach()
await TestHelper.setupBeforeEach()
const administrator = await TestStripeAccounts.createOwnerWithPrice()
const coupon = await TestHelper.createCoupon(administrator, {
duration: 'repeating',
duration_in_months: '3'
})
// subscription is cancelling
const user = await TestStripeAccounts.createUserWithPaidSubscription(administrator.price)
await TestHelper.cancelSubscription(user)
const user2 = await TestStripeAccounts.createUserWithPaidSubscription(administrator.price)
await TestHelper.createSubscriptionDiscount(administrator, user2.subscription, administrator.coupon)
const user3 = await TestStripeAccounts.createUserWithPaidSubscription(administrator.price)
const req = TestHelper.createRequest(`/api/administrator/subscriptions/set-subscription-coupon?subscriptionid=${user.subscription.subscriptionid}`)
req.account = administrator.account
req.session = administrator.session
req.body = {
couponid: administrator.coupon.couponid
}
try {
await req.patch(req)
} catch (error) {
cachedResponses.subscriptionCanceling = error.message
}
// subscription is already discounted
const req2 = TestHelper.createRequest(`/api/administrator/subscriptions/set-subscription-coupon?subscriptionid=${user2.subscription.subscriptionid}`)
req2.account = administrator.account
req2.session = administrator.session
req2.body = {
couponid: administrator.coupon.couponid
}
try {
await req2.patch(req)
} catch (error) {
cachedResponses.subscriptionDiscounted = error.message
}
// missing and invalid coupon
const req3 = TestHelper.createRequest(`/api/administrator/subscriptions/set-subscription-coupon?subscriptionid=${user3.subscription.subscriptionid}`)
req3.account = administrator.account
req3.session = administrator.session
req3.body = {
couponid: ''
}
try {
await req3.patch(req)
} catch (error) {
cachedResponses.missingCoupon = error.message
}
const req4 = TestHelper.createRequest(`/api/administrator/subscriptions/set-subscription-coupon?subscriptionid=${user3.subscription.subscriptionid}`)
req4.account = administrator.account
req4.session = administrator.session
req4.body = {
couponid: 'invalid'
}
try {
await req4.patch(req)
} catch (error) {
cachedResponses.invalidCoupon = error.message
}
const req7 = TestHelper.createRequest(`/api/administrator/subscriptions/set-subscription-coupon?subscriptionid=${user3.subscription.subscriptionid}`)
req7.account = administrator.account
req7.session = administrator.session
req7.body = {
couponid: coupon.couponid
}
req7.filename = __filename
req7.saveResponse = true
cachedResponses.returns = await req7.patch()
cachedResponses.finished = true
}
describe('exceptions', () => {
describe('invalid-subscriptionid', () => {
it('missing querystring subscriptionid', async function () {
await bundledData(this.test.currentRetry())
const administrator = await TestHelper.createOwner()
const req = TestHelper.createRequest('/api/administrator/subscriptions/set-subscription-coupon')
req.account = administrator.account
req.session = administrator.session
req.body = {
couponid: 'fake'
}
let errorMessage
try {
await req.patch(req)
} catch (error) {
errorMessage = error.message
}
assert.strictEqual(errorMessage, 'invalid-subscriptionid')
})
it('invalid querystring subscriptionid', async function () {
await bundledData(this.test.currentRetry())
const administrator = await TestHelper.createOwner()
const req = TestHelper.createRequest('/api/administrator/subscriptions/set-subscription-coupon?subscriptionid=invalid')
req.account = administrator.account
req.session = administrator.session
req.body = {
couponid: 'fake'
}
let errorMessage
try {
await req.patch(req)
} catch (error) {
errorMessage = error.message
}
assert.strictEqual(errorMessage, 'invalid-subscriptionid')
})
})
describe('invalid-subscription', () => {
it('ineligible subscription is canceling', async function () {
await bundledData(this.test.currentRetry())
const errorMessage = cachedResponses.subscriptionCanceling
assert.strictEqual(errorMessage, 'invalid-subscription')
})
it('ineligible subscription has coupon', async function () {
await bundledData(this.test.currentRetry())
const errorMessage = cachedResponses.subscriptionDiscounted
assert.strictEqual(errorMessage, 'invalid-subscription')
})
})
describe('invalid-couponid', () => {
it('missing posted couponid', async function () {
await bundledData(this.test.currentRetry())
const errorMessage = cachedResponses.missingCoupon
assert.strictEqual(errorMessage, 'invalid-couponid')
})
it('invalid posted couponid', async function () {
await bundledData(this.test.currentRetry())
const errorMessage = cachedResponses.invalidCoupon
assert.strictEqual(errorMessage, 'invalid-couponid')
})
})
})
describe('returns', () => {
it('object', async () => {
const subscriptionNow = cachedResponses.returns
assert.strictEqual(subscriptionNow.stripeObject.discount.coupon.object, 'coupon')
})
})
})