diff --git a/src/app/functions/server/applyCoupon.ts b/src/app/functions/server/applyCoupon.ts new file mode 100644 index 000000000..fe743dbfc --- /dev/null +++ b/src/app/functions/server/applyCoupon.ts @@ -0,0 +1,48 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +import { SubscriberRow } from "knex/types/tables"; +import { logger } from "./logging"; +import { SerializedSubscriber } from "../../../next-auth"; +import { + addCouponForSubscriber, + checkCouponForSubscriber, +} from "../../../db/tables/subscriber_coupons"; + +export async function applyCurrentCouponCode( + subscriber: SubscriberRow | SerializedSubscriber, +) { + logger.info("fxa_apply_coupon_code", { + subscriber: subscriber.id, + }); + + // current coupon + const currentCouponCode = process.env.CURRENT_COUPON_CODE; + if (!currentCouponCode) { + logger.error( + "fxa_apply_coupon_code", + "Coupon code not set. Please set the env var: CURRENT_COUPON_CODE", + ); + return { + success: false, + }; + } + + try { + if (!(await checkCouponForSubscriber(subscriber.id, currentCouponCode))) { + await addCouponForSubscriber(subscriber.id, currentCouponCode); + return { + success: true, + }; + } + } catch (ex) { + logger.error("fxa_apply_coupon_code", { + subscriber_id: subscriber.id, + exception: ex, + }); + return { + success: false, + }; + } +} diff --git a/src/utils/fxa.js b/src/utils/fxa.js index 88d7442e6..a84cb0af7 100644 --- a/src/utils/fxa.js +++ b/src/utils/fxa.js @@ -161,7 +161,7 @@ async function applyCoupon(bearerToken, couponCode) { } } if (subscriptionId) { - const applyCouponUrl = `${AppConstants.OAUTH_ACCOUNT_URI}oauth/subscriptions/coupon/apply` + const applyCouponUrl = `${AppConstants.OAUTH_ACCOUNT_URI}/oauth/subscriptions/coupon/apply` const response = await fetch(applyCouponUrl, { method: "PUT", headers: {