π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
faet: rc
Nevo David83c33dc32d25
diff --git a/.env.example b/.env.exampleindex 51ac5c369..87d6b9214 100644--- a/.env.example+++ b/.env.example@@ -128,6 +128,11 @@ STRIPE_PUBLISHABLE_KEY=""STRIPE_SECRET_KEY=""STRIPE_SIGNING_KEY=""STRIPE_SIGNING_KEY_CONNECT=""+# RevenueCat (App Store / Google Play subscriptions from the mobile app)+# Webhook URL: {BACKEND_URL}/payment/revenuecat, Authorization header value = REVENUECAT_WEBHOOK_SECRET+REVENUECAT_SECRET_KEY=""+REVENUECAT_WEBHOOK_SECRET=""+# IN_APP_PURCHASE_REJECT_SANDBOX=true# Developer SettingsNX_ADD_PLUGINS=falsediff --git a/apps/backend/src/api/api.module.ts b/apps/backend/src/api/api.module.tsindex f42f35b2a..e98635042 100644--- a/apps/backend/src/api/api.module.ts+++ b/apps/backend/src/api/api.module.ts@@ -5,6 +5,10 @@ import { UsersController } from '@gitroom/backend/api/routes/users.controller';import { AuthMiddleware } from '@gitroom/backend/services/auth/auth.middleware';import { StripeController } from '@gitroom/backend/api/routes/stripe.controller';import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';+import { PaymentController } from '@gitroom/backend/api/routes/payment.controller';+import { PaymentService } from '@gitroom/nestjs-libraries/services/payment/payment.service';+import { PaymentProviderManager } from '@gitroom/nestjs-libraries/services/payment/payment.provider.manager';+import { RevenueCatProvider } from '@gitroom/nestjs-libraries/services/payment/providers/revenuecat.provider';import { AnalyticsController } from '@gitroom/backend/api/routes/analytics.controller';import { PoliciesGuard } from '@gitroom/backend/services/auth/permissions/permissions.guard';import { PermissionsService } from '@gitroom/backend/services/auth/permissions/permissions.service';@@ -76,6 +80,7 @@ const authenticatedController = [: [RootController,StripeController,+ PaymentController,AuthController,PublicController,MonitorController,@@ -87,6 +92,9 @@ const authenticatedController = [providers: [AuthService,StripeService,+ PaymentService,+ PaymentProviderManager,+ RevenueCatProvider,OpenaiService,ExtractContentService,AuthMiddleware,diff --git a/apps/backend/src/api/routes/billing.controller.ts b/apps/backend/src/api/routes/billing.controller.tsindex 2c206e74f..49fe1a3c9 100644--- a/apps/backend/src/api/routes/billing.controller.ts+++ b/apps/backend/src/api/routes/billing.controller.ts@@ -1,6 +1,13 @@-import { Body, Controller, Get, HttpException, 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';import { Organization, User } from '@prisma/client';import { BillingSubscribeDto } from '@gitroom/nestjs-libraries/dtos/billing/billing.subscribe.dto';@@ -11,17 +18,25 @@ import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/nimport { Request } from 'express';import { AuthService } from '@gitroom/helpers/auth/auth.service';import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/users.service';+import { PaymentService } from '@gitroom/nestjs-libraries/services/payment/payment.service';+import { BillingSyncDto } from '@gitroom/nestjs-libraries/dtos/billing/billing.sync.dto';@ApiTags('Billing')@Controller('/billing')export class BillingController {constructor(private _subscriptionService: SubscriptionService,- private _stripeService: StripeService,private _notificationService: NotificationService,- private _usersService: UsersService+ private _usersService: UsersService,+ private _paymentService: PaymentService) {}+ // Billing routes are the web platform; the org's own provider (or the web+ // default when it has none) handles the action.+ private provider(org: Organization) {+ return this._paymentService.getProviderForOrganization(org.id, 'web');+ }+private async assertNoOtherSubscribedAccount(user: User) {const other = await this._usersService.getUserWithActiveSubscriptionByEmail(user.email,@@ -36,14 +51,14 @@ export class BillingController {@Param('id') body: string) {return {- status: await this._stripeService.checkSubscription(org.id, body),+ status: await (await this.provider(org)).checkSubscription(org.id, body),};}@Get('/check-discount')async checkDiscount(@GetOrgFromRequest() org: Organization) {return {- offerCoupon: !(await this._stripeService.checkDiscount(org.paymentId))+ offerCoupon: !(await (await this.provider(org)).checkDiscount(org))? false: AuthService.signJWT({ discount: true }),};@@ -51,13 +66,14 @@ export class BillingController {@Post('/apply-discount')async applyDiscount(@GetOrgFromRequest() org: Organization) {- await this._stripeService.applyDiscount(org.paymentId);+ await (await this.provider(org)).applyDiscount(org);}@Post('/finish-trial')async finishTrial(@GetOrgFromRequest() org: Organization) {+ const provider = await this.provider(org);try {- await this._stripeService.finishTrial(org.paymentId);+ await provider.finishTrial(org);} catch (err) {}return {finish: true,@@ -83,7 +99,7 @@ export class BillingController {}const uniqueId = req?.cookies?.track;- return this._stripeService.embedded(+ return (await this.provider(org)).embedded(uniqueId,org.id,user.id,@@ -104,7 +120,7 @@ export class BillingController {}const uniqueId = req?.cookies?.track;- return this._stripeService.subscribe(+ return (await this.provider(org)).subscribe(uniqueId,org.id,user.id,@@ -113,12 +129,30 @@ export class BillingController {);}+ @Post('/sync')+ async sync(+ @GetOrgFromRequest() org: Organization,+ @GetUserFromRequest() user: User,+ @Body() body: BillingSyncDto+ ) {+ if (await this.assertNoOtherSubscribedAccount(user)) {+ return { blocked: true };+ }+ await this._paymentService.assertCanUseProvider(org.id, body.provider);++ try {+ return await this._paymentService.syncSubscription(body.provider, org.id);+ } catch (e) {+ if (e instanceof HttpException) {+ throw e;+ }+ throw new HttpException((e as Error)?.message || 'Sync failed', 400);+ }+ }+@Get('/portal')async modifyPayment(@GetOrgFromRequest() org: Organization) {- const customer = await this._stripeService.getCustomerByOrganizationId(- org.id- );- const { url } = await this._stripeService.createBillingPortalLink(customer);+ const { url } = await (await this.provider(org)).portalLink(org.id);return {portal: url,};@@ -126,7 +160,7 @@ export class BillingController {@Get('/')getCurrentBilling(@GetOrgFromRequest() org: Organization) {- return this._subscriptionService.getSubscriptionByOrganizationId(org.id);+ return this._paymentService.getSubscription(org.id);}@Post('/cancel')@@ -142,15 +176,15 @@ export class BillingController {user.email);- return this._stripeService.setToCancel(org.id);+ return (await this.provider(org)).setToCancel(org.id);}@Post('/prorate')- prorate(+ async prorate(@GetOrgFromRequest() org: Organization,@Body() body: BillingSubscribeDto) {- return this._stripeService.prorate(org.id, body);+ return (await this.provider(org)).prorate(org.id, body);}@Get('/charges')@@ -162,7 +196,7 @@ export class BillingController {throw new HttpException('Unauthorized', 400);}- return this._stripeService.getCharges(org.id);+ return (await this.provider(org)).getCharges(org.id);}@Post('/refund-charges')@@ -175,7 +209,7 @@ export class BillingController {throw new HttpException('Unauthorized', 400);}- return this._stripeService.refundCharges(org.id, body.chargeIds);+ return (await this.provider(org)).refundCharges(org.id, body.chargeIds);}@Post('/cancel-subscription')@@ -187,7 +221,7 @@ export class BillingController {throw new HttpException('Unauthorized', 400);}- return this._stripeService.cancelSubscription(org.id);+ return (await this.provider(org)).cancelSubscription(org.id);}@Get('/coupon-info')@@ -199,7 +233,7 @@ export class BillingController {throw new HttpException('Unauthorized', 400);}- return this._stripeService.getCouponInfo(org.id);+ return (await this.provider(org)).getCouponInfo(org.id);}@Post('/apply-coupon')@@ -212,7 +246,7 @@ export class BillingController {throw new HttpException('Unauthorized', 400);}- return this._stripeService.applyCoupon(org.id, body);+ return (await this.provider(org)).applyCoupon(org.id, body);}@Post('/cancel-coupon')@@ -224,12 +258,12 @@ export class BillingController {throw new HttpException('Unauthorized', 400);}- return this._stripeService.cancelCoupon(org.id);+ return (await this.provider(org)).cancelCoupon(org.id);}@Get('/chatbase-refund/preview')- chatbaseRefundPreview(@GetOrgFromRequest() org: Organization) {- return this._stripeService.chatbaseRefundPreview(org.id);+ async chatbaseRefundPreview(@GetOrgFromRequest() org: Organization) {+ return (await this.provider(org)).chatbaseRefundPreview(org.id);}@Post('/chatbase-refund')@@ -237,7 +271,7 @@ export class BillingController {@GetUserFromRequest() user: User,@GetOrgFromRequest() org: Organization) {- const refund = await this._stripeService.chatbaseRefund(org.id);+ const refund = await (await this.provider(org)).chatbaseRefund(org.id);if (refund.refunded) {await this._notificationService.sendEmail(@@ -264,8 +298,8 @@ export class BillingController {await this._subscriptionService.addSubscription(org.id,user.id,- body.subscription+ body.subscription,+ this._paymentService.getDefaultProviderName('web'));}-}diff --git a/apps/backend/src/api/routes/payment.controller.ts b/apps/backend/src/api/routes/payment.controller.tsnew file mode 100644index 000000000..f0a9964c0--- /dev/null+++ b/apps/backend/src/api/routes/payment.controller.ts@@ -0,0 +1,36 @@+import {+ Controller,+ HttpException,+ Param,+ Post,+ RawBodyRequest,+ Req,+} from '@nestjs/common';+import { ApiTags } from '@nestjs/swagger';+import { PaymentService } from '@gitroom/nestjs-libraries/services/payment/payment.service';++@ApiTags('Payment')+@Controller('/payment')+export class PaymentController {+ constructor(private readonly _paymentService: PaymentService) {}++ @Post('/:provider')+ async webhook(+ @Param('provider') provider: string,+ @Req() req: RawBodyRequest<Request>+ ) {+ try {+ return await this._paymentService.webhook(+ provider,+ req.rawBody,+ // @ts-ignore+ req.headers+ );+ } catch (e) {+ if (e instanceof HttpException) {+ throw e;+ }+ throw new HttpException(e, 500);+ }+ }+}diff --git a/apps/backend/src/api/routes/stripe.controller.ts b/apps/backend/src/api/routes/stripe.controller.tsindex 37aadf24b..699a0b3fe 100644--- a/apps/backend/src/api/routes/stripe.controller.ts+++ b/apps/backend/src/api/routes/stripe.controller.ts@@ -5,49 +5,29 @@ import {RawBodyRequest,Req,} from '@nestjs/common';-import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';import { ApiTags } from '@nestjs/swagger';+import { PaymentService } from '@gitroom/nestjs-libraries/services/payment/payment.service';+import { STRIPE_PROVIDER } from '@gitroom/nestjs-libraries/services/payment/payment.providers';+// Legacy webhook path, kept until the Stripe dashboard points at /payment/stripe@ApiTags('Stripe')@Controller('/stripe')export class StripeController {- constructor(- private readonly _stripeService: StripeService,- ) {}+ constructor(private readonly _paymentService: PaymentService) {}@Post('/')- stripe(@Req() req: RawBodyRequest<Request>) {- const event = this._stripeService.validateRequest(- req.rawBody,- // @ts-ignore- req.headers['stripe-signature'],- process.env.STRIPE_SIGNING_KEY- );-- // Maybe it comes from another stripe webhook- if (- // eslint-disable-next-line @typescript-eslint/ban-ts-comment- // @ts-ignore- event?.data?.object?.metadata?.service !== 'gitroom' &&- event.type !== 'invoice.payment_succeeded'- ) {- return { ok: true };- }-+ async stripe(@Req() req: RawBodyRequest<Request>) {try {- switch (event.type) {- case 'invoice.payment_succeeded':- return this._stripeService.paymentSucceeded(event);- case 'customer.subscription.created':- return this._stripeService.createSubscription(event);- case 'customer.subscription.updated':- return this._stripeService.updateSubscription(event);- case 'customer.subscription.deleted':- return this._stripeService.deleteSubscription(event);- default:- return { ok: true };- }+ return await this._paymentService.webhook(+ STRIPE_PROVIDER,+ req.rawBody,+ // @ts-ignore+ req.headers+ );} catch (e) {+ if (e instanceof HttpException) {+ throw e;+ }throw new HttpException(e, 500);}}diff --git a/apps/backend/src/api/routes/users.controller.ts b/apps/backend/src/api/routes/users.controller.tsindex 896cc03b1..ca15e470e 100644--- a/apps/backend/src/api/routes/users.controller.ts+++ b/apps/backend/src/api/routes/users.controller.ts@@ -13,7 +13,7 @@ import { sign } from 'jsonwebtoken';import { Organization, User } from '@prisma/client';import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';-import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';+import { PaymentService } from '@gitroom/nestjs-libraries/services/payment/payment.service';import { Response, Request } from 'express';import { AuthService } from '@gitroom/backend/services/auth/auth.service';import { AuthService as AuthChecker } from '@gitroom/helpers/auth/auth.service';@@ -41,7 +41,7 @@ import {export class UsersController {constructor(private _subscriptionService: SubscriptionService,- private _stripeService: StripeService,+ private _paymentService: PaymentService,private _authService: AuthService,private _orgService: OrganizationService,private _userService: UsersService,@@ -214,7 +214,7 @@ export class UsersController {adminId);- await this._stripeService.syncCustomerEmailsAfterSwitch([kept, switched]);+ await this._paymentService.syncCustomerEmailsAfterSwitch([kept, switched]);return { success: true };}@@ -259,10 +259,9 @@ export class UsersController {@Get('/subscription')@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])async getSubscription(@GetOrgFromRequest() organization: Organization) {- const subscription =- await this._subscriptionService.getSubscriptionByOrganizationId(- organization.id- );+ const subscription = await this._paymentService.getSubscription(+ organization.id+ );return subscription ? { subscription } : { subscription: undefined };}@@ -270,7 +269,7 @@ export class UsersController {@Get('/subscription/tiers')@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])async tiers() {- return this._stripeService.getPackages();+ return this._paymentService.getDefaultProvider('web').getPackages();}@Post('/join-org')@@ -348,20 +347,15 @@ export class UsersController {user.id);- if (process.env.STRIPE_PUBLISHABLE_KEY) {- for (const org of ownedOrgs) {- if (!org.paymentId) {- continue;- }- try {- await this._stripeService.cancelAllSubscriptions(org.id);- } catch (err) {- console.log(err);- throw new HttpException(- 'Could not cancel your subscription, please try again or contact support',- 400- );- }+ for (const org of ownedOrgs) {+ try {+ await this._paymentService.cancelAllSubscriptions(org.id);+ } catch (err) {+ console.log(err);+ throw new HttpException(+ 'Could not cancel your subscription, please try again or contact support',+ 400+ );}}diff --git a/apps/frontend/src/components/billing/main.billing.component.tsx b/apps/frontend/src/components/billing/main.billing.component.tsxindex 523e442b8..ff75f66db 100644--- a/apps/frontend/src/components/billing/main.billing.component.tsx+++ b/apps/frontend/src/components/billing/main.billing.component.tsx@@ -29,6 +29,10 @@ import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';import { useDubClickId } from '@gitroom/frontend/components/layout/dubAnalytics';import { LogoutComponent } from '@gitroom/frontend/components/layout/logout.component';+type SubscriptionWithPlatform = Subscription & {+ platform?: 'web' | 'mobile';+};+export const Prorate: FC<{period: 'MONTHLY' | 'YEARLY';pack: 'STANDARD' | 'PRO';@@ -209,7 +213,7 @@ const Info: FC<{);};export const MainBillingComponent: FC<{- sub?: Subscription;+ sub?: SubscriptionWithPlatform;}> = (props) => {const { sub } = props;const { isGeneral } = useVariables();@@ -228,7 +232,7 @@ export const MainBillingComponent: FC<{!!queryParams.get('finishTrial'));- const [subscription, setSubscription] = useState<Subscription | undefined>(+ const [subscription, setSubscription] = useState<SubscriptionWithPlatform | undefined>(sub);const [loading, setLoading] = useState<boolean>(false);@@ -449,6 +453,30 @@ export const MainBillingComponent: FC<{router.replace('/');return null;}+ if (subscription?.platform && subscription.platform !== 'web') {+ return (+ <div className="flex flex-col gap-[16px]">+ <div className="text-[20px]">{t('plans', 'Plans')}</div>+ <div className="flex flex-col items-center gap-[8px] rounded-[8px] bg-newBgColorInner p-[24px] text-center">+ <div className="text-[18px]">+ {t('subscription_managed_by', 'Your subscription is managed by')}{' '}+ <span className="capitalize">{subscription.provider}</span>+ </div>+ <div className="text-[14px] opacity-70">+ {t(+ 'subscription_manage_on_platform',+ 'Please go to {{platform}} to manage it',+ { platform: subscription.platform }+ )}+ </div>+ </div>+ <FAQComponent />+ <div className="flex justify-center mt-[20px]">+ <LogoutComponent />+ </div>+ </div>+ );+ }return (<div className="flex flex-col gap-[16px]"><div className="flex flex-row">diff --git a/libraries/nestjs-libraries/src/database/prisma/database.module.ts b/libraries/nestjs-libraries/src/database/prisma/database.module.tsindex 252b01d39..9660d6891 100644--- a/libraries/nestjs-libraries/src/database/prisma/database.module.ts+++ b/libraries/nestjs-libraries/src/database/prisma/database.module.ts@@ -17,6 +17,9 @@ import { MediaRepository } from '@gitroom/nestjs-libraries/database/prisma/mediaimport { NotificationsRepository } from '@gitroom/nestjs-libraries/database/prisma/notifications/notifications.repository';import { EmailService } from '@gitroom/nestjs-libraries/services/email.service';import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';+import { PaymentService } from '@gitroom/nestjs-libraries/services/payment/payment.service';+import { PaymentProviderManager } from '@gitroom/nestjs-libraries/services/payment/payment.provider.manager';+import { RevenueCatProvider } from '@gitroom/nestjs-libraries/services/payment/providers/revenuecat.provider';import { ExtractContentService } from '@gitroom/nestjs-libraries/openai/extract.content.service';import { OpenaiService } from '@gitroom/nestjs-libraries/openai/openai.service';import { AgenciesService } from '@gitroom/nestjs-libraries/database/prisma/agencies/agencies.service';@@ -68,6 +71,9 @@ import { AdminStatsService } from '@gitroom/nestjs-libraries/database/prisma/admPostsService,PostsRepository,StripeService,+ PaymentService,+ PaymentProviderManager,+ RevenueCatProvider,SignatureRepository,AutopostRepository,AutopostService,diff --git a/libraries/nestjs-libraries/src/database/prisma/schema.prisma b/libraries/nestjs-libraries/src/database/prisma/schema.prismaindex a0c7ca154..623bc0c68 100644--- a/libraries/nestjs-libraries/src/database/prisma/schema.prisma+++ b/libraries/nestjs-libraries/src/database/prisma/schema.prisma@@ -288,6 +288,7 @@ model Subscription {id String @id @default(cuid())organizationId String @uniquesubscriptionTier SubscriptionTier+ provider String @default("stripe")identifier String?cancelAt DateTime?period Perioddiff --git a/libraries/nestjs-libraries/src/database/prisma/subscriptions/subscription.repository.ts b/libraries/nestjs-libraries/src/database/prisma/subscriptions/subscription.repository.tsindex afaa9b09a..1071b7fc5 100644--- a/libraries/nestjs-libraries/src/database/prisma/subscriptions/subscription.repository.ts+++ b/libraries/nestjs-libraries/src/database/prisma/subscriptions/subscription.repository.ts@@ -88,9 +88,10 @@ export class SubscriptionRepository {});}- deleteSubscriptionByCustomerId(customerId: string) {+ deleteSubscriptionByCustomerId(customerId: string, provider: string) {return this._subscription.model.subscription.deleteMany({where: {+ provider,organization: {paymentId: customerId,},@@ -98,6 +99,15 @@ export class SubscriptionRepository {});}+ deleteSubscriptionByOrgId(organizationId: string, provider: string) {+ return this._subscription.model.subscription.deleteMany({+ where: {+ organizationId,+ provider,+ },+ });+ }+updateCustomerId(organizationId: string, customerId: string) {return this._organization.model.organization.update({where: {@@ -136,6 +146,7 @@ export class SubscriptionRepository {}async createOrUpdateSubscription(+ provider: string,isTrailing: boolean,identifier: string,customerId: string,@@ -156,7 +167,7 @@ export class SubscriptionRepository {await this._subscription.model.subscription.upsert({where: {organizationId: findOrg.id,- ...(!code+ ...(!code && customerId? {organization: {paymentId: customerId,@@ -166,6 +177,7 @@ export class SubscriptionRepository {},update: {subscriptionTier: billing,+ provider,totalChannels,period,identifier,@@ -176,6 +188,7 @@ export class SubscriptionRepository {create: {organizationId: findOrg.id,subscriptionTier: billing,+ provider,isLifetime: !!code,totalChannels,period,diff --git a/libraries/nestjs-libraries/src/database/prisma/subscriptions/subscription.service.ts b/libraries/nestjs-libraries/src/database/prisma/subscriptions/subscription.service.tsindex f607e6d13..aaf2ed471 100644--- a/libraries/nestjs-libraries/src/database/prisma/subscriptions/subscription.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/subscriptions/subscription.service.ts@@ -33,14 +33,47 @@ export class SubscriptionService {return this._subscriptionRepository.getCode(code);}- async deleteSubscription(customerId: string) {+ // Customer-keyed flows must never touch a subscription owned by another provider+ private async isManagedBy(customerId: string, provider: string) {+ const current =+ await this._subscriptionRepository.getSubscriptionByCustomerId(+ customerId+ );+ return !current || current.provider === provider;+ }++ async deleteSubscription(customerId: string, provider: string) {+ if (!(await this.isManagedBy(customerId, provider))) {+ return { count: 0 };+ }await this.modifySubscription(customerId,pricing.FREE.channel || 0,'FREE');return this._subscriptionRepository.deleteSubscriptionByCustomerId(- customerId+ customerId,+ provider+ );+ }++ // Store-managed subscriptions (RevenueCat etc.) have no Stripe customer, they are keyed by org+ async deleteSubscriptionByOrgId(organizationId: string, provider: string) {+ const current = await this._subscriptionRepository.getSubscriptionByOrgId(+ organizationId+ );+ if (!current || current.provider !== provider || current.isLifetime) {+ return false;+ }++ await this.modifySubscriptionByOrg(+ organizationId,+ pricing.FREE.channel || 0,+ 'FREE'+ );+ return this._subscriptionRepository.deleteSubscriptionByOrgId(+ organizationId,+ provider);}@@ -171,6 +204,7 @@ export class SubscriptionService {}async createOrUpdateSubscription(+ provider: string,isTrailing: boolean,identifier: string,customerId: string,@@ -182,6 +216,9 @@ export class SubscriptionService {org?: string) {if (!code) {+ if (!(await this.isManagedBy(customerId, provider))) {+ return {};+ }try {const load = await this.modifySubscription(customerId,@@ -196,6 +233,7 @@ export class SubscriptionService {}}return this._subscriptionRepository.createOrUpdateSubscription(+ provider,isTrailing,identifier,customerId,@@ -208,6 +246,50 @@ export class SubscriptionService {);}+ async createOrUpdateSubscriptionByOrg(+ isTrailing: boolean,+ organizationId: string,+ provider: string,+ identifier: string,+ totalChannels: number,+ billing: 'STANDARD' | 'TEAM' | 'PRO' | 'ULTIMATE',+ period: 'MONTHLY' | 'YEARLY',+ cancelAt: number | null+ ) {+ const current = await this._subscriptionRepository.getSubscriptionByOrgId(+ organizationId+ );+ if (current && (current.isLifetime || current.provider !== provider)) {+ return {};+ }++ try {+ const load = await this.modifySubscriptionByOrg(+ organizationId,+ totalChannels,+ billing+ );+ if (!load) {+ return {};+ }+ } catch (e) {+ return {};+ }++ return this._subscriptionRepository.createOrUpdateSubscription(+ provider,+ isTrailing,+ identifier,+ '',+ totalChannels,+ billing,+ period,+ cancelAt,+ undefined,+ { id: organizationId }+ );+ }+getSubscriptionByIdentifier(identifier: string) {return this._subscriptionRepository.getSubscriptionByIdentifier(identifier);}@@ -247,9 +329,15 @@ export class SubscriptionService {};}- async addSubscription(orgId: string, userId: string, subscription: any) {+ async addSubscription(+ orgId: string,+ userId: string,+ subscription: any,+ provider: string+ ) {await this._subscriptionRepository.setCustomerId(orgId, userId);return this.createOrUpdateSubscription(+ provider,false,makeId(5),userId,diff --git a/libraries/nestjs-libraries/src/dtos/billing/billing.sync.dto.ts b/libraries/nestjs-libraries/src/dtos/billing/billing.sync.dto.tsnew file mode 100644index 000000000..f3b1bcf08--- /dev/null+++ b/libraries/nestjs-libraries/src/dtos/billing/billing.sync.dto.ts@@ -0,0 +1,7 @@+import { IsDefined, IsString } from 'class-validator';++export class BillingSyncDto {+ @IsDefined()+ @IsString()+ provider: string;+}diff --git a/libraries/nestjs-libraries/src/services/payment/payment.provider.interface.ts b/libraries/nestjs-libraries/src/services/payment/payment.provider.interface.tsnew file mode 100644index 000000000..be4be9e78--- /dev/null+++ b/libraries/nestjs-libraries/src/services/payment/payment.provider.interface.ts@@ -0,0 +1,185 @@+import { HttpException, Injectable } from '@nestjs/common';+import { Organization } 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';++export type PaymentPlatform = 'web' | 'mobile';++// Every billing use-case goes through this contract. Webhooks and `platform`+// are mandatory; everything else has a default that says "not supported on+// this platform" so a provider only implements what its platform offers+// (e.g. app stores have no hosted checkout / portal / coupons).+export abstract class PaymentProviderAbstract {+ // Where the subscription is bought / managed. An organization can only be+ // subscribed on one platform at a time, the other platform is blocked.+ abstract platform: PaymentPlatform;++ // Turn the raw webhook request into a trusted event (throw on bad signature / secret)+ abstract validateWebhook(+ rawBody: Buffer,+ headers: Record<string, string | string[] | undefined>+ ): Promise<any> | any;++ // Apply a validated webhook event to our subscriptions+ abstract processWebhook(event: any): Promise<any>;++ protected notSupported(): never {+ throw new HttpException(+ `This action is not supported on ${this.platform}`,+ 400+ );+ }++ // --- subscription lifecycle -------------------------------------------++ // Client initiated re-check of the organization subscription against the+ // provider (mobile app after purchase / restore)+ async syncSubscription(organizationId: string): Promise<{ active: boolean }> {+ return this.notSupported();+ }++ // Hosted checkout page+ async subscribe(+ uniqueId: string,+ organizationId: string,+ userId: string,+ body: BillingSubscribeDto,+ allowTrial: boolean+ ): Promise<any> {+ return this.notSupported();+ }++ // Embedded checkout (client secret rendered inside our page)+ async embedded(+ uniqueId: string,+ organizationId: string,+ userId: string,+ body: BillingSubscribeDto,+ allowTrial: boolean+ ): Promise<any> {+ return this.notSupported();+ }++ // Price difference preview when switching plans+ async prorate(+ organizationId: string,+ body: BillingSubscribeDto+ ): Promise<any> {+ return this.notSupported();+ }++ // Toggle cancel-at-period-end+ async setToCancel(organizationId: string): Promise<any> {+ return this.notSupported();+ }++ // Cancel everything right now (account deletion). Must not throw when the+ // provider has nothing to cancel server side.+ async cancelAllSubscriptions(organizationId: string): Promise<any> {+ return this.notSupported();+ }++ // Self-service portal (payment method / invoices)+ async portalLink(organizationId: string): Promise<{ url: string }> {+ return this.notSupported();+ }++ // Post-checkout poll: is this subscription id active for the org+ async checkSubscription(+ organizationId: string,+ subscriptionId: string+ ): Promise<any> {+ return this.notSupported();+ }++ // Available plans / prices+ async getPackages(): Promise<any> {+ return this.notSupported();+ }++ // --- trial & discounts --------------------------------------------------++ async finishTrial(organization: Organization): Promise<any> {+ return this.notSupported();+ }++ async checkDiscount(organization: Organization): Promise<boolean> {+ return false;+ }++ async applyDiscount(organization: Organization): Promise<any> {+ return this.notSupported();+ }++ async lifetimeDeal(organizationId: string, code: string): Promise<any> {+ return this.notSupported();+ }++ // --- admin --------------------------------------------------------------++ async getCharges(organizationId: string): Promise<any> {+ return this.notSupported();+ }++ async refundCharges(+ organizationId: string,+ chargeIds: string[]+ ): Promise<any> {+ return this.notSupported();+ }++ async cancelSubscription(organizationId: string): Promise<any> {+ return this.notSupported();+ }++ async getCouponInfo(organizationId: string): Promise<any> {+ return this.notSupported();+ }++ async applyCoupon(+ organizationId: string,+ body: AdminApplyCouponDto+ ): Promise<any> {+ return this.notSupported();+ }++ async cancelCoupon(organizationId: string): Promise<any> {+ return this.notSupported();+ }++ async chatbaseRefundPreview(organizationId: string): Promise<any> {+ return this.notSupported();+ }++ async chatbaseRefund(+ organizationId: string+ ): Promise<{ refunded: boolean; amount?: number; currency?: string }> {+ return this.notSupported();+ }++ // After a login swap, keep the provider's customer email in sync (no-op by default)+ async syncCustomerEmailsAfterSwitch(+ accounts: { id: string; email: string }[]+ ): Promise<void> {}+}++export interface PaymentProviderParams {+ provider: string;+}++export function PaymentProvider(params: PaymentProviderParams) {+ return function (target: any) {+ Injectable()(target);++ const existingMetadata =+ Reflect.getMetadata('payment-provider', PaymentProviderAbstract) || [];++ existingMetadata.push({ target, provider: params.provider });++ Reflect.defineMetadata(+ 'payment-provider',+ existingMetadata,+ PaymentProviderAbstract+ );+ };+}diff --git a/libraries/nestjs-libraries/src/services/payment/payment.provider.manager.ts b/libraries/nestjs-libraries/src/services/payment/payment.provider.manager.tsnew file mode 100644index 000000000..a5952c8b8--- /dev/null+++ b/libraries/nestjs-libraries/src/services/payment/payment.provider.manager.ts@@ -0,0 +1,47 @@+import { HttpException, Injectable } from '@nestjs/common';+import { ModuleRef } from '@nestjs/core';+import {+ PaymentPlatform,+ PaymentProviderAbstract,+} from '@gitroom/nestjs-libraries/services/payment/payment.provider.interface';++@Injectable()+export class PaymentProviderManager {+ constructor(private _moduleRef: ModuleRef) {}++ private metadata(): { target: any; provider: string }[] {+ return (+ Reflect.getMetadata('payment-provider', PaymentProviderAbstract) || []+ );+ }++ getProvider(provider: string): PaymentProviderAbstract {+ const found = this.metadata().find((m) => m.provider === provider);++ if (!found) {+ throw new HttpException(`Payment provider ${provider} not found`, 400);+ }++ return this._moduleRef.get(found.target, { strict: false });+ }++ getProviders(): { name: string; provider: PaymentProviderAbstract }[] {+ return this.metadata().map((m) => ({+ name: m.provider,+ provider: this._moduleRef.get(m.target, { strict: false }),+ }));+ }++ // First registered provider of a platform is the one new subscriptions use+ getDefaultProvider(platform: PaymentPlatform) {+ const found = this.getProviders().find(+ (p) => p.provider.platform === platform+ );++ if (!found) {+ throw new Error(`No payment provider registered for ${platform}`);+ }++ return found;+ }+}diff --git a/libraries/nestjs-libraries/src/services/payment/payment.providers.ts b/libraries/nestjs-libraries/src/services/payment/payment.providers.tsnew file mode 100644index 000000000..ddf9a2035--- /dev/null+++ b/libraries/nestjs-libraries/src/services/payment/payment.providers.ts@@ -0,0 +1,2 @@+export const STRIPE_PROVIDER = 'stripe';+export const REVENUECAT_PROVIDER = 'revenuecat';diff --git a/libraries/nestjs-libraries/src/services/payment/payment.service.ts b/libraries/nestjs-libraries/src/services/payment/payment.service.tsnew file mode 100644index 000000000..01bb75a9c--- /dev/null+++ b/libraries/nestjs-libraries/src/services/payment/payment.service.ts@@ -0,0 +1,146 @@+import { HttpException, Injectable } from '@nestjs/common';+import { PaymentProviderManager } from '@gitroom/nestjs-libraries/services/payment/payment.provider.manager';+import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';+import { PaymentPlatform } from '@gitroom/nestjs-libraries/services/payment/payment.provider.interface';++@Injectable()+export class PaymentService {+ constructor(+ private _paymentProviderManager: PaymentProviderManager,+ private _subscriptionService: SubscriptionService+ ) {}++ async webhook(+ provider: string,+ rawBody: Buffer,+ headers: Record<string, string | string[] | undefined>+ ) {+ const paymentProvider = this._paymentProviderManager.getProvider(provider);+ const event = await paymentProvider.validateWebhook(rawBody, headers);+ return paymentProvider.processWebhook(event);+ }++ syncSubscription(provider: string, organizationId: string) {+ return this._paymentProviderManager+ .getProvider(provider)+ .syncSubscription(organizationId);+ }++ getDefaultProvider(platform: PaymentPlatform) {+ return this._paymentProviderManager.getDefaultProvider(platform).provider;+ }++ getDefaultProviderName(platform: PaymentPlatform) {+ return this._paymentProviderManager.getDefaultProvider(platform).name;+ }++ // Subscription row + the platform (web / mobile) of the provider that owns it,+ // so clients can tell the user where to manage the subscription.+ async getSubscription(organizationId: string) {+ const subscription =+ await this._subscriptionService.getSubscriptionByOrganizationId(+ organizationId+ );+ if (!subscription) {+ return null;+ }++ // A dangling provider name (provider removed from the build) must not+ // break reading the subscription+ let platform: PaymentPlatform | undefined;+ try {+ platform = this._paymentProviderManager.getProvider(+ subscription.provider+ ).platform;+ } catch (err) {+ platform = undefined;+ }++ return {+ ...subscription,+ platform,+ };+ }++ // The provider that handles billing actions for this organization on the+ // given platform: the one owning the current subscription, otherwise the+ // platform default. Throws when the subscription lives on another platform.+ async getProviderForOrganization(+ organizationId: string,+ platform: PaymentPlatform+ ) {+ const subscription =+ await this._subscriptionService.getSubscriptionByOrganizationId(+ organizationId+ );++ if (!subscription) {+ return this._paymentProviderManager.getDefaultProvider(platform).provider;+ }++ const current = this._paymentProviderManager.getProvider(+ subscription.provider+ );+ if (current.platform !== platform) {+ throw new HttpException(+ `Your subscription is managed on ${current.platform}, please use ${current.platform} to manage it`,+ 400+ );+ }++ return current;+ }++ // An organization subscribed through one provider cannot checkout, sync or+ // manage the subscription through another one.+ async assertCanUseProvider(organizationId: string, provider: string) {+ const subscription =+ await this._subscriptionService.getSubscriptionByOrganizationId(+ organizationId+ );++ if (!subscription || subscription.provider === provider) {+ return;+ }++ const current = this._paymentProviderManager.getProvider(+ subscription.provider+ );+ const requested = this._paymentProviderManager.getProvider(provider);++ throw new HttpException(+ current.platform !== requested.platform+ ? `Your subscription is managed on ${current.platform}, please use ${current.platform} to manage it`+ : `Your subscription is managed by ${subscription.provider}`,+ 400+ );+ }++ // Account deletion: the provider owning the org's subscription, or - when+ // there is no row (missed webhook, cleaned up) - every provider, so nothing+ // keeps charging a deleted account. Providers no-op when they own nothing.+ async cancelAllSubscriptions(organizationId: string) {+ const subscription =+ await this._subscriptionService.getSubscriptionByOrganizationId(+ organizationId+ );++ if (subscription) {+ return this._paymentProviderManager+ .getProvider(subscription.provider)+ .cancelAllSubscriptions(organizationId);+ }++ for (const { provider } of this._paymentProviderManager.getProviders()) {+ await provider.cancelAllSubscriptions(organizationId);+ }+ }++ async syncCustomerEmailsAfterSwitch(+ accounts: { id: string; email: string }[]+ ) {+ for (const { provider } of this._paymentProviderManager.getProviders()) {+ await provider.syncCustomerEmailsAfterSwitch(accounts);+ }+ }+}diff --git a/libraries/nestjs-libraries/src/services/payment/providers/revenuecat.provider.ts b/libraries/nestjs-libraries/src/services/payment/providers/revenuecat.provider.tsnew file mode 100644index 000000000..aeded4179--- /dev/null+++ b/libraries/nestjs-libraries/src/services/payment/providers/revenuecat.provider.ts@@ -0,0 +1,186 @@+import { HttpException } from '@nestjs/common';+import dayjs from 'dayjs';+import { uniq } from 'lodash';+import {+ PaymentPlatform,+ PaymentProvider,+ PaymentProviderAbstract,+} from '@gitroom/nestjs-libraries/services/payment/payment.provider.interface';+import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';+import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';+import { pricing } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/pricing';++import { REVENUECAT_PROVIDER } from '@gitroom/nestjs-libraries/services/payment/payment.providers';++interface RevenueCatSubscription {+ expires_date: string | null;+ purchase_date: string;+ original_purchase_date: string;+ unsubscribe_detected_at: string | null;+ billing_issues_detected_at: string | null;+ is_sandbox: boolean;+ store: string;+ period_type: string;+}++// RevenueCat is the source of truth for App Store / Google Play subscriptions.+// The webhook and the app only tell us *which* subscriber to re-check; we always+// load the subscriber from the API instead of trusting the event payload.+// app_user_id === Postiz organization id (the app calls Purchases.logIn(orgId)).+// Product ids end with <tier>.<period> or <tier>_<period>, e.g. com.postiz.mob.pro.yearly+@PaymentProvider({ provider: REVENUECAT_PROVIDER })+export class RevenueCatProvider extends PaymentProviderAbstract {+ platform: PaymentPlatform = 'mobile';++ constructor(+ private _subscriptionService: SubscriptionService,+ private _organizationService: OrganizationService+ ) {+ super();+ }++ validateWebhook(+ rawBody: Buffer,+ headers: Record<string, string | string[] | undefined>+ ) {+ const secret = process.env.REVENUECAT_WEBHOOK_SECRET;+ if (!secret || headers.authorization !== secret) {+ throw new HttpException('Invalid webhook authorization', 401);+ }++ return JSON.parse(rawBody.toString('utf8'));+ }++ async processWebhook(body: any) {+ const event = body?.event;+ if (!event || event.type === 'TEST') {+ return { ok: true };+ }++ const organizations = uniq(+ [+ event.app_user_id,+ event.original_app_user_id,+ event.transferred_from,+ event.transferred_to,+ ]+ .flat()+ .filter((p: string) => p && !p.startsWith('$RCAnonymousID:'))+ ) as string[];++ for (const organizationId of organizations) {+ await this.syncSubscription(organizationId);+ }++ return { ok: true };+ }++ // Store subscriptions can only be cancelled by the user in the App Store /+ // Google Play; account deletion must not be blocked by it.+ override async cancelAllSubscriptions(organizationId: string) {+ return;+ }++ override async syncSubscription(organizationId: string) {+ const organization = await this._organizationService.getOrgById(+ organizationId+ );+ if (!organization) {+ return { active: false };+ }++ const active = await this.getActiveSubscription(organizationId);+ if (!active) {+ await this._subscriptionService.deleteSubscriptionByOrgId(+ organizationId,+ REVENUECAT_PROVIDER+ );+ return { active: false };+ }++ const { billing, period } = this.parseProductId(active.productId);++ // Store trials (intro offers) keep the same trial restrictions as a Stripe trial+ await this._subscriptionService.createOrUpdateSubscriptionByOrg(+ active.subscription.period_type === 'trial',+ organizationId,+ REVENUECAT_PROVIDER,+ active.productId,+ pricing[billing].channel!,+ billing,+ period,+ active.subscription.unsubscribe_detected_at &&+ active.subscription.expires_date+ ? dayjs(active.subscription.expires_date).unix()+ : null+ );++ return { active: true };+ }++ private async getActiveSubscription(organizationId: string) {+ if (!process.env.REVENUECAT_SECRET_KEY) {+ throw new HttpException('RevenueCat is not configured', 400);+ }++ const response = await fetch(+ `https://api.revenuecat.com/v1/subscribers/${encodeURIComponent(+ organizationId+ )}`,+ {+ headers: {+ Authorization: `Bearer ${process.env.REVENUECAT_SECRET_KEY}`,+ 'Content-Type': 'application/json',+ },+ }+ );++ if (!response.ok) {+ throw new HttpException(+ `RevenueCat subscriber request failed (${response.status})`,+ 500+ );+ }++ const { subscriber } = await response.json();+ const subscriptions: Record<string, RevenueCatSubscription> =+ subscriber?.subscriptions || {};++ const rejectSandbox = !!process.env.IN_APP_PURCHASE_REJECT_SANDBOX;++ return Object.entries(subscriptions)+ .map(([productId, subscription]) => ({ productId, subscription }))+ .filter(+ ({ subscription }) =>+ (!rejectSandbox || !subscription.is_sandbox) &&+ (!subscription.expires_date ||+ dayjs(subscription.expires_date).isAfter(dayjs()))+ )+ .sort((a, b) =>+ dayjs(b.subscription.expires_date || '2999-01-01').diff(+ dayjs(a.subscription.expires_date || '2999-01-01')+ )+ )[0];+ }++ private parseProductId(productId: string) {+ const parts = productId.split(/[._]/);+ const period = (parts.pop() || '').toUpperCase();+ const billing = (parts.pop() || '').toUpperCase();++ if (+ !['MONTHLY', 'YEARLY'].includes(period) ||+ !['STANDARD', 'TEAM', 'PRO', 'ULTIMATE'].includes(billing)+ ) {+ throw new HttpException(+ `Unknown RevenueCat product identifier: ${productId}`,+ 400+ );+ }++ return {+ billing: billing as 'STANDARD' | 'TEAM' | 'PRO' | 'ULTIMATE',+ period: period as 'MONTHLY' | 'YEARLY',+ };+ }+}diff --git a/libraries/nestjs-libraries/src/services/stripe.service.ts b/libraries/nestjs-libraries/src/services/stripe.service.tsindex 06c6559a2..1858277e9 100644--- a/libraries/nestjs-libraries/src/services/stripe.service.ts+++ b/libraries/nestjs-libraries/src/services/stripe.service.ts@@ -11,21 +11,68 @@ import { AuthService } from '@gitroom/helpers/auth/auth.service';import { TrackService } from '@gitroom/nestjs-libraries/track/track.service';import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/users.service';import { TrackEnum } from '@gitroom/nestjs-libraries/user/track.enum';+import {+ PaymentPlatform,+ PaymentProvider,+ PaymentProviderAbstract,+} from '@gitroom/nestjs-libraries/services/payment/payment.provider.interface';++import { STRIPE_PROVIDER } from '@gitroom/nestjs-libraries/services/payment/payment.providers';const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || 'sk_nothing');-@Injectable()-export class StripeService {+@PaymentProvider({ provider: STRIPE_PROVIDER })+export class StripeService extends PaymentProviderAbstract {+ platform: PaymentPlatform = 'web';+constructor(private _subscriptionService: SubscriptionService,private _organizationService: OrganizationService,private _userService: UsersService,private _trackService: TrackService- ) {}+ ) {+ super();+ }validateRequest(rawBody: Buffer, signature: string, endpointSecret: string) {return stripe.webhooks.constructEvent(rawBody, signature, endpointSecret);}+ validateWebhook(+ rawBody: Buffer,+ headers: Record<string, string | string[] | undefined>+ ) {+ return this.validateRequest(+ rawBody,+ headers['stripe-signature'] as string,+ process.env.STRIPE_SIGNING_KEY+ );+ }++ async processWebhook(event: Stripe.Event) {+ // Maybe it comes from another stripe webhook+ if (+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignore+ event?.data?.object?.metadata?.service !== 'gitroom' &&+ event.type !== 'invoice.payment_succeeded'+ ) {+ return { ok: true };+ }++ switch (event.type) {+ case 'invoice.payment_succeeded':+ return this.paymentSucceeded(event);+ case 'customer.subscription.created':+ return this.createSubscription(event);+ case 'customer.subscription.updated':+ return this.updateSubscription(event);+ case 'customer.subscription.deleted':+ return this.deleteSubscription(event);+ default:+ return { ok: true };+ }+ }+async checkValidCard(event:| Stripe.CustomerSubscriptionCreatedEvent@@ -97,11 +144,7 @@ export class StripeService {}async createSubscription(event: Stripe.CustomerSubscriptionCreatedEvent) {- const {- uniqueId,- billing,- period,- } = event.data.object.metadata as {+ const { uniqueId, billing, period } = event.data.object.metadata as {billing: 'STANDARD' | 'PRO';period: 'MONTHLY' | 'YEARLY';uniqueId: string;@@ -117,6 +160,7 @@ export class StripeService {}return this._subscriptionService.createOrUpdateSubscription(+ STRIPE_PROVIDER,event.data.object.status !== 'active',uniqueId,event.data.object.customer as string,@@ -127,11 +171,7 @@ export class StripeService {);}async updateSubscription(event: Stripe.CustomerSubscriptionUpdatedEvent) {- const {- uniqueId,- billing,- period,- } = event.data.object.metadata as {+ const { uniqueId, billing, period } = event.data.object.metadata as {billing: 'STANDARD' | 'PRO';period: 'MONTHLY' | 'YEARLY';uniqueId: string;@@ -143,6 +183,7 @@ export class StripeService {}return this._subscriptionService.createOrUpdateSubscription(+ STRIPE_PROVIDER,event.data.object.status !== 'active',uniqueId,event.data.object.customer as string,@@ -155,7 +196,8 @@ export class StripeService {async deleteSubscription(event: Stripe.CustomerSubscriptionDeletedEvent) {await this._subscriptionService.deleteSubscription(- event.data.object.customer as string+ event.data.object.customer as string,+ STRIPE_PROVIDER);}@@ -202,7 +244,10 @@ export class StripeService {const users = await this._organizationService.getTeam(organization.id);const customer = await stripe.customers.create({- email: users.users[0].user.email.indexOf('@') > -1 ? users.users[0].user.email : `${users.users[0].user.email}@postiz.com`,+ email:+ users.users[0].user.email.indexOf('@') > -1+ ? users.users[0].user.email+ : `${users.users[0].user.email}@postiz.com`,name: organization.name,});await this._subscriptionService.updateCustomerId(@@ -370,7 +415,10 @@ export class StripeService {if (hasFailedPayment) {// Payment already failed β cancel immediately and delete subscriptionawait stripe.subscriptions.cancel(sub.id);- await this._subscriptionService.deleteSubscription(customer);+ await this._subscriptionService.deleteSubscription(+ customer,+ STRIPE_PROVIDER+ );return {id,@@ -391,6 +439,9 @@ export class StripeService {}async cancelAllSubscriptions(organizationId: string) {+ if (!process.env.STRIPE_PUBLISHABLE_KEY) {+ return;+ }// getOrgById must not filter deletedAt, this can run for an organization// that was already soft deleted by an account deletionconst org = await this._organizationService.getOrgById(organizationId);@@ -410,7 +461,10 @@ export class StripeService {await stripe.subscriptions.cancel(subscription.id);}- await this._subscriptionService.deleteSubscription(org.paymentId);+ await this._subscriptionService.deleteSubscription(+ org.paymentId,+ STRIPE_PROVIDER+ );}async getCustomerByOrganizationId(organizationId: string) {@@ -490,7 +544,10 @@ export class StripeService {try {await stripe.customers.update(customer, {- email: user.email.indexOf('@') > -1 ? user.email : `${user.email}@postiz.com`,+ email:+ user.email.indexOf('@') > -1+ ? user.email+ : `${user.email}@postiz.com`,...(body.dub? {metadata: {@@ -599,10 +656,15 @@ export class StripeService {return { url };}- async finishTrial(paymentId: string) {+ async portalLink(organizationId: string) {+ const customer = await this.getCustomerByOrganizationId(organizationId);+ return this.createBillingPortalLink(customer);+ }++ async finishTrial(organization: Organization) {const list = (await stripe.subscriptions.list({- customer: paymentId,+ customer: organization.paymentId,})).data.filter((f) => f.status === 'trialing');@@ -611,8 +673,9 @@ export class StripeService {});}- async checkDiscount(customer: string) {- if (!process.env.STRIPE_DISCOUNT_ID) {+ async checkDiscount(organization: Organization) {+ const customer = organization.paymentId;+ if (!process.env.STRIPE_DISCOUNT_ID || !customer) {return false;}@@ -650,8 +713,9 @@ export class StripeService {return true;}- async applyDiscount(customer: string) {- const check = this.checkDiscount(customer);+ async applyDiscount(organization: Organization) {+ const customer = organization.paymentId;+ const check = this.checkDiscount(organization);if (!check) {return false;}@@ -993,7 +1057,10 @@ export class StripeService {}await stripe.subscriptions.cancel(subscriptions[0].id);- await this._subscriptionService.deleteSubscription(customer);+ await this._subscriptionService.deleteSubscription(+ customer,+ STRIPE_PROVIDER+ );return { cancelled: true };}@@ -1228,9 +1295,7 @@ export class StripeService {? invoiceSubscription: invoiceSubscription?.id;- chargeSubscription = subscriptions.find(- (f) => f.id === subscriptionId- );+ chargeSubscription = subscriptions.find((f) => f.id === subscriptionId);if (chargeSubscription) {lastCharge = charge;@@ -1306,7 +1371,10 @@ export class StripeService {}if (preview.subscriptionIds.length) {- await this._subscriptionService.deleteSubscription(org?.paymentId!);+ await this._subscriptionService.deleteSubscription(+ org?.paymentId!,+ STRIPE_PROVIDER+ );}return {@@ -1339,6 +1407,7 @@ export class StripeService {const findPricing = pricing[nextPackage];await this._subscriptionService.createOrUpdateSubscription(+ STRIPE_PROVIDER,false,makeId(10),organizationId,