Skip to content

πŸ“¨ The ultimate agentic social media scheduling tool πŸ€–

feat: refund and cancellation

Nevo David258378770eea
diff --git a/apps/backend/src/api/routes/billing.controller.ts b/apps/backend/src/api/routes/billing.controller.ts
index 5856898cc..3e6bcb184 100644
--- a/apps/backend/src/api/routes/billing.controller.ts
+++ b/apps/backend/src/api/routes/billing.controller.ts
@@ -1,4 +1,4 @@
-import { Body, Controller, Get, Param, Post, Req } from '@nestjs/common';
+import { Body, Controller, Get, HttpException, Param, Post, Req } from '@nestjs/common';
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
@@ -144,6 +144,43 @@ export class BillingController {
return this._stripeService.lifetimeDeal(org.id, body.code);
}
+ @Get('/charges')
+ async getCharges(
+ @GetUserFromRequest() user: User,
+ @GetOrgFromRequest() org: Organization
+ ) {
+ if (!user.isSuperAdmin) {
+ throw new HttpException('Unauthorized', 400);
+ }
+
+ return this._stripeService.getCharges(org.id);
+ }
+
+ @Post('/refund-charges')
+ async refundCharges(
+ @GetUserFromRequest() user: User,
+ @GetOrgFromRequest() org: Organization,
+ @Body() body: { chargeIds: string[] }
+ ) {
+ if (!user.isSuperAdmin) {
+ throw new HttpException('Unauthorized', 400);
+ }
+
+ return this._stripeService.refundCharges(org.id, body.chargeIds);
+ }
+
+ @Post('/cancel-subscription')
+ async cancelSubscription(
+ @GetUserFromRequest() user: User,
+ @GetOrgFromRequest() org: Organization
+ ) {
+ if (!user.isSuperAdmin) {
+ throw new HttpException('Unauthorized', 400);
+ }
+
+ return this._stripeService.cancelSubscription(org.id);
+ }
+
@Post('/add-subscription')
async addSubscription(
@Body() body: { subscription: string },
diff --git a/apps/frontend/src/components/layout/impersonate.tsx b/apps/frontend/src/components/layout/impersonate.tsx
index 89c1cab54..a05eb2d9a 100644
--- a/apps/frontend/src/components/layout/impersonate.tsx
+++ b/apps/frontend/src/components/layout/impersonate.tsx
@@ -1,5 +1,5 @@
import { Input } from '@gitroom/react/form/input';
-import { ChangeEventHandler, useCallback, useMemo, useState } from 'react';
+import { ChangeEventHandler, FC, useCallback, useMemo, useState } from 'react';
import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useUser } from '@gitroom/frontend/components/layout/user.context';
@@ -9,6 +9,223 @@ import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';
import { useVariables } from '@gitroom/react/helpers/variable.context';
import { setCookie } from '@gitroom/frontend/components/layout/layout.context';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
+import { useModals } from '@gitroom/frontend/components/layout/new-modal';
+import { Button } from '@gitroom/react/form/button';
+
+interface Charge {
+ id: string;
+ amount: number;
+ currency: string;
+ created: number;
+ status: string;
+ refunded: boolean;
+ amount_refunded: number;
+ description: string | null;
+}
+
+const useCharges = () => {
+ const fetch = useFetch();
+ return useSWR<Charge[]>('/billing/charges', async () => {
+ return (await fetch('/billing/charges')).json();
+ }, {
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ revalidateIfStale: false,
+ });
+};
+
+const ChargesModal: FC<{ close: () => void }> = ({ close }) => {
+ const fetch = useFetch();
+ const t = useT();
+ const { data: charges, mutate } = useCharges();
+ const [selected, setSelected] = useState<Set<string>>(new Set());
+ const [refunding, setRefunding] = useState(false);
+ const [cancelling, setCancelling] = useState(false);
+
+ const toggleCharge = useCallback((chargeId: string) => {
+ setSelected((prev) => {
+ const next = new Set(prev);
+ if (next.has(chargeId)) {
+ next.delete(chargeId);
+ } else {
+ next.add(chargeId);
+ }
+ return next;
+ });
+ }, []);
+
+ const handleRefund = useCallback(async () => {
+ if (!selected.size) return;
+ if (
+ !(await deleteDialog(
+ t(
+ 'refund_selected_confirm',
+ `Are you sure you want to refund ${selected.size} charge(s)? This cannot be undone.`
+ ),
+ t('yes_refund', 'Yes, refund'),
+ t('confirm_refund', 'Confirm Refund'),
+ t('no_cancel', 'No, cancel')
+ ))
+ ) {
+ return;
+ }
+ setRefunding(true);
+ try {
+ await fetch('/billing/refund-charges', {
+ method: 'POST',
+ body: JSON.stringify({ chargeIds: Array.from(selected) }),
+ });
+ setSelected(new Set());
+ await mutate();
+ } finally {
+ setRefunding(false);
+ }
+ }, [selected]);
+
+ const handleCancel = useCallback(async () => {
+ if (
+ !(await deleteDialog(
+ t(
+ 'cancel_subscription_confirm',
+ 'This will immediately cancel the subscription. The user will be downgraded to the FREE plan. This cannot be undone.'
+ ),
+ t('yes_cancel_subscription', 'Yes, cancel subscription'),
+ t('cancel_subscription_title', 'Cancel Subscription?'),
+ t('no_go_back', 'No, go back')
+ ))
+ ) {
+ return;
+ }
+ setCancelling(true);
+ try {
+ await fetch('/billing/cancel-subscription', {
+ method: 'POST',
+ });
+ close();
+ window.location.reload();
+ } catch {
+ setCancelling(false);
+ }
+ }, []);
+
+ return (
+ <div className="flex flex-col gap-[16px] min-w-[500px]">
+ <div className="max-h-[400px] overflow-y-auto">
+ {!charges?.length ? (
+ <div className="text-center py-[20px] text-newTextColor/60">
+ {t('no_charges', 'No charges found')}
+ </div>
+ ) : (
+ <table className="w-full">
+ <thead>
+ <tr className="text-left border-b border-newTableBorder">
+ <th className="p-[8px] w-[40px]" />
+ <th className="p-[8px]">{t('date', 'Date')}</th>
+ <th className="p-[8px]">{t('amount', 'Amount')}</th>
+ <th className="p-[8px]">{t('status', 'Status')}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {charges.map((charge) => (
+ <tr
+ key={charge.id}
+ className="border-b border-newTableBorder hover:bg-tableBorder cursor-pointer"
+ onClick={() => !charge.refunded && toggleCharge(charge.id)}
+ >
+ <td className="p-[8px]">
+ <div
+ className={`w-[20px] h-[20px] rounded-[4px] border-2 flex items-center justify-center ${
+ charge.refunded
+ ? 'border-newTextColor/20 opacity-40'
+ : selected.has(charge.id)
+ ? 'bg-forth border-forth'
+ : 'border-newTextColor/40'
+ }`}
+ >
+ {(selected.has(charge.id) || charge.refunded) && (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ width="14"
+ height="14"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="3"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <polyline points="20 6 9 17 4 12" />
+ </svg>
+ )}
+ </div>
+ </td>
+ <td className="p-[8px]">
+ {new Date(charge.created * 1000).toLocaleDateString()}
+ </td>
+ <td className="p-[8px]">
+ ${(charge.amount / 100).toFixed(2)}{' '}
+ {charge.currency.toUpperCase()}
+ </td>
+ <td className="p-[8px]">
+ {charge.refunded ? (
+ <span className="text-red-400">
+ {t('refunded', 'Refunded')}
+ </span>
+ ) : (
+ <span className="text-green-400">
+ {t('paid', 'Paid')}
+ </span>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ <div className="flex gap-[12px] justify-end">
+ <Button
+ onClick={handleRefund}
+ loading={refunding}
+ disabled={!selected.size}
+ className="rounded-[4px]"
+ >
+ {t('refund_selected', 'Refund Selected')}
+ {selected.size > 0 && ` (${selected.size})`}
+ </Button>
+ <Button
+ onClick={handleCancel}
+ loading={cancelling}
+ className="!bg-red-700 rounded-[4px]"
+ >
+ {t('cancel_subscription', 'Cancel Subscription')}
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+const ManageBilling = () => {
+ const { openModal } = useModals();
+ const t = useT();
+
+ const handleClick = useCallback(() => {
+ openModal({
+ title: t('manage_billing', 'Manage Billing'),
+ children: (close) => <ChargesModal close={close} />,
+ });
+ }, []);
+
+ return (
+ <div
+ className="px-[10px] rounded-[4px] bg-red-700 text-white cursor-pointer whitespace-nowrap"
+ onClick={handleClick}
+ >
+ {t('manage_billing', 'Manage Billing')}
+ </div>
+ );
+};
+
export const Subscription = () => {
const fetch = useFetch();
const t = useT();
@@ -58,7 +275,7 @@ export const Subscription = () => {
export const Impersonate = () => {
const fetch = useFetch();
const [name, setName] = useState('');
- const { isSecured } = useVariables();
+ const { isSecured, billingEnabled } = useVariables();
const user = useUser();
const load = useCallback(async () => {
if (!name) {
@@ -132,6 +349,7 @@ export const Impersonate = () => {
</div>
</div>
{user?.tier?.current === 'FREE' && <Subscription />}
+ {billingEnabled && <ManageBilling />}
</div>
) : (
<Input
diff --git a/libraries/nestjs-libraries/src/services/stripe.service.ts b/libraries/nestjs-libraries/src/services/stripe.service.ts
index 96aaa8ec4..31f336de4 100644
--- a/libraries/nestjs-libraries/src/services/stripe.service.ts
+++ b/libraries/nestjs-libraries/src/services/stripe.service.ts
@@ -820,6 +820,75 @@ export class StripeService {
return { ok: true };
}
+ async getCharges(organizationId: string) {
+ const org = await this._organizationService.getOrgById(organizationId);
+ if (!org?.paymentId) {
+ return [];
+ }
+
+ const charges = await stripe.charges.list({
+ customer: org.paymentId,
+ limit: 100,
+ });
+
+ return charges.data.map((charge) => ({
+ id: charge.id,
+ amount: charge.amount,
+ currency: charge.currency,
+ created: charge.created,
+ status: charge.status,
+ refunded: charge.refunded,
+ amount_refunded: charge.amount_refunded,
+ description: charge.description,
+ }));
+ }
+
+ async refundCharges(organizationId: string, chargeIds: string[]) {
+ const org = await this._organizationService.getOrgById(organizationId);
+ if (!org?.paymentId) {
+ throw new Error('No payment customer found for this organization');
+ }
+
+ const refunded: string[] = [];
+ const failed: string[] = [];
+
+ for (const chargeId of chargeIds) {
+ try {
+ await stripe.refunds.create({ charge: chargeId });
+ refunded.push(chargeId);
+ } catch (err) {
+ failed.push(chargeId);
+ }
+ }
+
+ return { refunded, failed };
+ }
+
+ async cancelSubscription(organizationId: string) {
+ const org = await this._organizationService.getOrgById(organizationId);
+ if (!org?.paymentId) {
+ throw new Error('No payment customer found for this organization');
+ }
+
+ const customer = org.paymentId;
+
+ const subscriptions = (
+ await stripe.subscriptions.list({
+ customer,
+ status: 'all',
+ })
+ ).data.filter((f) => f.status !== 'canceled');
+
+ if (!subscriptions.length) {
+ throw new Error('No active subscription found');
+ }
+
+ await stripe.subscriptions.cancel(subscriptions[0].id);
+ await this._subscriptionService.deleteSubscription(customer);
+
+ return { cancelled: true };
+ }
+
async lifetimeDeal(organizationId: string, code: string) {
const getCurrentSubscription =
await this._subscriptionService.getSubscriptionByOrganizationId(