π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat(billing): admin apply/cancel coupon for the impersonated user
Gilad Resisidce1cd0571a4
diff --git a/apps/backend/src/api/routes/billing.controller.ts b/apps/backend/src/api/routes/billing.controller.tsindex b09fb414a..2c206e74f 100644--- a/apps/backend/src/api/routes/billing.controller.ts+++ b/apps/backend/src/api/routes/billing.controller.ts@@ -4,6 +4,7 @@ import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.serviceimport { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';import { Organization, User } from '@prisma/client';import { BillingSubscribeDto } from '@gitroom/nestjs-libraries/dtos/billing/billing.subscribe.dto';+import { AdminApplyCouponDto } from '@gitroom/nestjs-libraries/dtos/billing/admin.apply.coupon.dto';import { ApiTags } from '@nestjs/swagger';import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';@@ -189,6 +190,43 @@ export class BillingController {return this._stripeService.cancelSubscription(org.id);}+ @Get('/coupon-info')+ async couponInfo(+ @GetUserFromRequest() user: User,+ @GetOrgFromRequest() org: Organization+ ) {+ if (!user.isSuperAdmin) {+ throw new HttpException('Unauthorized', 400);+ }++ return this._stripeService.getCouponInfo(org.id);+ }++ @Post('/apply-coupon')+ async applyCoupon(+ @GetUserFromRequest() user: User,+ @GetOrgFromRequest() org: Organization,+ @Body() body: AdminApplyCouponDto+ ) {+ if (!user.isSuperAdmin) {+ throw new HttpException('Unauthorized', 400);+ }++ return this._stripeService.applyCoupon(org.id, body);+ }++ @Post('/cancel-coupon')+ async cancelCoupon(+ @GetUserFromRequest() user: User,+ @GetOrgFromRequest() org: Organization+ ) {+ if (!user.isSuperAdmin) {+ throw new HttpException('Unauthorized', 400);+ }++ return this._stripeService.cancelCoupon(org.id);+ }+@Get('/chatbase-refund/preview')chatbaseRefundPreview(@GetOrgFromRequest() org: Organization) {return this._stripeService.chatbaseRefundPreview(org.id);diff --git a/apps/frontend/src/components/layout/impersonate.tsx b/apps/frontend/src/components/layout/impersonate.tsxindex 74a8349ff..358e815b5 100644--- a/apps/frontend/src/components/layout/impersonate.tsx+++ b/apps/frontend/src/components/layout/impersonate.tsx@@ -41,9 +41,292 @@ const useCharges = () => {});};+interface CouponInfo {+ tier: string | null;+ period: string | null;+ isLifetime: boolean;+ monthlyPrice: number;+ planPrice: number;+ nextPayment: number | null;+ coupons: {+ type: string;+ value: number;+ duration: string;+ durationInMonths: number | null;+ remainingMonths: number | null;+ }[];+ supported: boolean;+}++const useCouponInfo = () => {+ const fetch = useFetch();+ return useSWR<CouponInfo>('/billing/coupon-info', async () => {+ return (await fetch('/billing/coupon-info')).json();+ }, {+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ revalidateIfStale: false,+ });+};++const ApplyCouponModal: FC<{ close: () => void }> = ({ close }) => {+ const fetch = useFetch();+ const t = useT();+ const toast = useToaster();+ const { data: info, mutate } = useCouponInfo();+ const [type, setType] = useState('percentage');+ const [value, setValue] = useState('');+ const [months, setMonths] = useState('1');+ const [error, setError] = useState('');+ const [applying, setApplying] = useState(false);+ const [cancelling, setCancelling] = useState(false);++ const handleCancelCoupon = useCallback(async () => {+ if (+ !(await deleteDialog(+ t(+ 'cancel_coupon_confirm',+ 'Are you sure you want to cancel this coupon? The user will pay the full price from the next billing cycle.'+ ),+ t('yes_cancel_coupon', 'Yes, cancel coupon'),+ t('cancel_coupon_title', 'Cancel Coupon?'),+ t('no_go_back', 'No, go back')+ ))+ ) {+ return;+ }+ setCancelling(true);+ try {+ const response = await fetch('/billing/cancel-coupon', {+ method: 'POST',+ });+ const json = await response.json().catch(() => ({}));+ if (!response.ok || !json.cancelled) {+ toast.show(+ json.reason ||+ t('cancel_coupon_failed', 'Could not cancel the coupon'),+ 'warning'+ );+ return;+ }+ toast.show(t('cancel_coupon_success', 'Coupon cancelled'));+ await mutate();+ } finally {+ setCancelling(false);+ }+ }, []);++ const handleApply = useCallback(async () => {+ if (!info) {+ return;+ }+ const numberValue = Number(value);+ const numberMonths = Number(months);+ if (+ type === 'percentage' &&+ (!numberValue || numberValue < 1 || numberValue > 100)+ ) {+ setError(+ t(+ 'apply_coupon_invalid_percentage',+ 'Invalid percentage: enter a value between 1 and 100'+ )+ );+ return;+ }+ if (+ type === 'amount' &&+ (!numberValue || numberValue < 1 || numberValue > info.monthlyPrice)+ ) {+ setError(+ `${t(+ 'apply_coupon_invalid_amount',+ "Invalid amount: enter a value between 1 and the plan's monthly payment:"+ )} ${info.monthlyPrice}`+ );+ return;+ }+ if (+ !numberMonths ||+ !Number.isInteger(numberMonths) ||+ numberMonths < 1 ||+ numberMonths > 12+ ) {+ setError(+ t(+ 'apply_coupon_invalid_months',+ 'Invalid months: enter a whole number between 1 and 12'+ )+ );+ return;+ }+ setError('');+ setApplying(true);+ try {+ const response = await fetch('/billing/apply-coupon', {+ method: 'POST',+ body: JSON.stringify({+ type,+ value: numberValue,+ months: numberMonths,+ }),+ });+ const json = await response.json().catch(() => ({}));+ if (!response.ok || !json.applied) {+ toast.show(+ json.reason ||+ t('apply_coupon_failed', 'Could not apply the coupon'),+ 'warning'+ );+ return;+ }+ toast.show(t('apply_coupon_success', 'Coupon applied'));+ setValue('');+ setMonths('1');+ await mutate();+ } finally {+ setApplying(false);+ }+ }, [info, type, value, months]);++ return (+ <div className="flex flex-col gap-[16px]">+ <div className="text-newTextColor/60 text-[13px]">+ {t(+ 'apply_coupon_subtitle',+ "The coupon applied here is simply a deduction from the user's next billing cycle(s) β one or more, depending on how many months you choose to apply it for. It is NOT a refund; we use Stripe's built-in coupon mechanism and that's how it works."+ )}+ </div>+ {!info ? (+ <div className="text-center py-[20px] text-newTextColor/60">+ {t('loading', 'Loading...')}+ </div>+ ) : (+ <>+ <div className="flex flex-col gap-[4px] text-[14px]">+ <div>+ {t('apply_coupon_plan', 'Plan:')} {info.tier || 'FREE'}+ {!!info.tier && ` - $${info.planPrice}`}+ </div>+ <div>+ {t('apply_coupon_period', 'Period:')}{' '}+ {info.period === 'MONTHLY'+ ? t('monthly', 'Monthly')+ : info.period === 'YEARLY'+ ? t('annual', 'Annual')+ : '-'}+ </div>+ <div>+ {t('apply_coupon_lifetime', 'Lifetime deal:')}{' '}+ {info.isLifetime ? t('yes', 'Yes') : t('no', 'No')}+ </div>+ <div>+ {t('apply_coupon_applied', 'Applied coupons:')}{' '}+ {!info.coupons.length && t('none', 'None')}+ </div>+ {info.coupons.map((coupon, index) => (+ <div key={index} className="ps-[10px] flex items-center gap-[10px]">+ <div>+ -{' '}+ {coupon.type === 'percentage'+ ? `${coupon.value}%`+ : `$${coupon.value}`}{' '}+ {t('apply_coupon_off', 'off,')}{' '}+ {coupon.duration === 'repeating'+ ? `${coupon.durationInMonths} ${t(+ 'apply_coupon_months_total',+ 'month(s) total,'+ )} ${coupon.remainingMonths} ${t(+ 'apply_coupon_months_left',+ 'month(s) left'+ )}`+ : coupon.duration === 'forever'+ ? t('apply_coupon_forever', 'forever')+ : t('apply_coupon_once', 'next billing cycle only')}+ </div>+ <Button+ onClick={handleCancelCoupon}+ loading={cancelling}+ className="!bg-red-700 rounded-[4px] !h-[24px] !px-[10px] text-[12px]"+ >+ {t('cancel', 'Cancel')}+ </Button>+ </div>+ ))}+ <div>+ {t('apply_coupon_next_payment', 'Next Payment:')}{' '}+ {info.nextPayment !== null ? `$${info.nextPayment}` : '-'}+ </div>+ </div>+ {info.supported ? (+ <div className="grid grid-cols-3 gap-[12px]">+ <Select+ label={t('apply_coupon_type', 'Coupon type')}+ name="couponType"+ disableForm={true}+ hideErrors={true}+ value={type}+ onChange={(e) => setType(e.target.value)}+ >+ <option value="percentage">+ {t('apply_coupon_percentage', 'Percentage')}+ </option>+ <option value="amount">+ {t('apply_coupon_fixed_amount', 'Fixed dollar amount')}+ </option>+ </Select>+ <Input+ label={t('apply_coupon_value', 'Value')}+ name="couponValue"+ type="number"+ disableForm={true}+ removeError={true}+ value={value}+ onChange={(e) => setValue(e.target.value)}+ />+ <Input+ label={t('apply_coupon_months', 'Months')}+ name="couponMonths"+ type="number"+ disableForm={true}+ removeError={true}+ value={months}+ onChange={(e) => setMonths(e.target.value)}+ />+ </div>+ ) : (+ <div className="text-newTextColor/60 text-[13px]">+ {t(+ 'apply_coupon_not_supported',+ "We currently don't support applying a coupon for users either under an annual plan, with a lifetime deal or with another active coupon."+ )}+ </div>+ )}+ {!!error && <div className="text-red-400 text-[12px]">{error}</div>}+ <div className="flex gap-[12px] justify-end">+ <Button onClick={close} className="rounded-[4px]">+ {t('close', 'Close')}+ </Button>+ {info.supported && (+ <Button+ onClick={handleApply}+ loading={applying}+ className="!bg-blue-700 rounded-[4px]"+ >+ {t('apply', 'Apply')}+ </Button>+ )}+ </div>+ </>+ )}+ </div>+ );+};+const ChargesModal: FC<{ close: () => void }> = ({ close }) => {const fetch = useFetch();const t = useT();+ const { openModal } = useModals();const { data: charges, mutate } = useCharges();const [selected, setSelected] = useState<Set<string>>(new Set());const [refunding, setRefunding] = useState(false);@@ -61,6 +344,15 @@ const ChargesModal: FC<{ close: () => void }> = ({ close }) => {});}, []);+ const handleApplyCoupon = useCallback(() => {+ close();+ openModal({+ title: t('apply_coupon', 'Apply Coupon'),+ maxSize: 600,+ children: (closeCoupon) => <ApplyCouponModal close={closeCoupon} />,+ });+ }, []);+const handleRefund = useCallback(async () => {if (!selected.size) return;if (@@ -220,6 +512,12 @@ const ChargesModal: FC<{ close: () => void }> = ({ close }) => {)}</div><div className="flex gap-[12px] justify-end">+ <Button+ onClick={handleApplyCoupon}+ className="!bg-blue-700 rounded-[4px]"+ >+ {t('apply_coupon', 'Apply Coupon')}+ </Button><ButtononClick={handleRefund}loading={refunding}diff --git a/libraries/nestjs-libraries/src/dtos/billing/admin.apply.coupon.dto.ts b/libraries/nestjs-libraries/src/dtos/billing/admin.apply.coupon.dto.tsnew file mode 100644index 000000000..b300de01f--- /dev/null+++ b/libraries/nestjs-libraries/src/dtos/billing/admin.apply.coupon.dto.ts@@ -0,0 +1,18 @@+import { IsDefined, IsIn, IsInt, IsNumber, IsString, Max, Min } from 'class-validator';++export class AdminApplyCouponDto {+ @IsString()+ @IsIn(['percentage', 'amount'])+ type: string;++ @IsDefined()+ @IsNumber()+ @Min(1)+ value: number;++ @IsDefined()+ @IsInt()+ @Min(1)+ @Max(12)+ months: number;+}diff --git a/libraries/nestjs-libraries/src/services/stripe.service.ts b/libraries/nestjs-libraries/src/services/stripe.service.tsindex 61c68a896..c781c18de 100644--- a/libraries/nestjs-libraries/src/services/stripe.service.ts+++ b/libraries/nestjs-libraries/src/services/stripe.service.ts@@ -975,6 +975,176 @@ export class StripeService {return { cancelled: true };}+ private mapSubscriptionDiscounts(subscription?: Stripe.Subscription) {+ return (subscription?.discounts || [])+ .filter(+ (discount): discount is Stripe.Discount => typeof discount !== 'string'+ )+ .map((discount) => {+ const coupon =+ typeof discount.source?.coupon === 'string'+ ? null+ : discount.source?.coupon;+ return {+ type: coupon?.percent_off ? 'percentage' : 'amount',+ value: coupon?.percent_off || (coupon?.amount_off || 0) / 100,+ duration: coupon?.duration || 'once',+ durationInMonths: coupon?.duration_in_months || null,+ remainingMonths: discount.end+ ? Math.max(+ 0,+ Math.ceil(+ (discount.end - Date.now() / 1000) / (30 * 24 * 60 * 60)+ )+ )+ : null,+ };+ });+ }++ private async getActiveStripeSubscription(paymentId?: string | null) {+ if (!paymentId || !paymentId.startsWith('cus_')) {+ return undefined;+ }++ return (+ await stripe.subscriptions.list({+ customer: paymentId,+ status: 'all',+ expand: ['data.discounts.source.coupon'],+ })+ ).data.find((f) => f.status === 'active' || f.status === 'trialing');+ }++ async getCouponInfo(organizationId: string) {+ const org = await this._organizationService.getOrgById(organizationId);+ const subscription =+ await this._subscriptionService.getSubscriptionByOrganizationId(+ organizationId+ );++ const stripeSubscription = await this.getActiveStripeSubscription(+ org?.paymentId+ );++ const coupons = this.mapSubscriptionDiscounts(stripeSubscription);+ const priceData = subscription+ ? pricing[subscription.subscriptionTier]+ : undefined;+ const monthlyPrice = priceData?.month_price || 0;++ let nextPayment: number | null = null;+ if (stripeSubscription) {+ try {+ const preview = await stripe.invoices.createPreview({+ customer: org!.paymentId!,+ subscription: stripeSubscription.id,+ });+ nextPayment = preview.total / 100;+ } catch (err) {+ /* no upcoming invoice */+ }+ }++ return {+ tier: subscription?.subscriptionTier || null,+ period: subscription?.period || null,+ isLifetime: !!subscription?.isLifetime,+ monthlyPrice,+ planPrice:+ subscription?.period === 'YEARLY'+ ? priceData?.year_price || 0+ : monthlyPrice,+ nextPayment,+ coupons,+ supported:+ !!subscription &&+ !!stripeSubscription &&+ subscription.period === 'MONTHLY' &&+ !subscription.isLifetime &&+ !coupons.length,+ };+ }++ async applyCoupon(+ organizationId: string,+ body: { type: string; value: number; months: number }+ ) {+ const info = await this.getCouponInfo(organizationId);+ if (!info.supported) {+ return {+ applied: false,+ reason: 'Applying a coupon is not supported for this user',+ };+ }++ if (+ body.type === 'percentage'+ ? body.value < 1 || body.value > 100+ : body.value < 1 || body.value > info.monthlyPrice+ ) {+ return { applied: false, reason: 'Invalid coupon value' };+ }++ const org = await this._organizationService.getOrgById(organizationId);+ const stripeSubscription = await this.getActiveStripeSubscription(+ org?.paymentId+ );++ if (!stripeSubscription) {+ return {+ applied: false,+ reason: 'No active subscription found for this customer',+ };+ }++ const coupon = await stripe.coupons.create({+ name: `Admin coupon for ${org!.name}`,+ ...(body.type === 'percentage'+ ? { percent_off: body.value }+ : { amount_off: Math.round(body.value * 100), currency: 'usd' }),+ ...(body.months === 1+ ? { duration: 'once' }+ : { duration: 'repeating', duration_in_months: body.months }),+ metadata: { service: 'gitroom', organizationId },+ });++ await stripe.subscriptions.update(stripeSubscription.id, {+ discounts: [+ {+ coupon: coupon.id,+ },+ ],+ });++ return { applied: true };+ }++ async cancelCoupon(organizationId: string) {+ const org = await this._organizationService.getOrgById(organizationId);+ const stripeSubscription = await this.getActiveStripeSubscription(+ org?.paymentId+ );++ if (!stripeSubscription) {+ return {+ cancelled: false,+ reason: 'No active subscription found for this customer',+ };+ }++ if (!stripeSubscription.discounts.length) {+ return {+ cancelled: false,+ reason: 'No coupon is applied to this subscription',+ };+ }++ await stripe.subscriptions.deleteDiscount(stripeSubscription.id);++ return { cancelled: true };+ }+async chatbaseRefundPreview(organizationId: string) {const org = await this._organizationService.getOrgById(organizationId);if (!org?.paymentId) {