π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: chatbase
Nevo Davidebe3a6b66636
diff --git a/apps/backend/src/api/routes/billing.controller.ts b/apps/backend/src/api/routes/billing.controller.tsindex cb47f99cc..bfa3cf8e5 100644--- a/apps/backend/src/api/routes/billing.controller.ts+++ b/apps/backend/src/api/routes/billing.controller.ts@@ -179,6 +179,30 @@ export class BillingController {return this._stripeService.cancelSubscription(org.id);}+ @Get('/chatbase-refund/preview')+ chatbaseRefundPreview(@GetOrgFromRequest() org: Organization) {+ return this._stripeService.chatbaseRefundPreview(org.id);+ }++ @Post('/chatbase-refund')+ async chatbaseRefund(+ @GetUserFromRequest() user: User,+ @GetOrgFromRequest() org: Organization+ ) {+ const refund = await this._stripeService.chatbaseRefund(org.id);++ if (refund.refunded) {+ await this._notificationService.sendEmail(+ process.env.EMAIL_FROM_ADDRESS,+ 'Refund issued from Chatbase',+ `Organization ${org.name} received a refund of ${refund.amount} ${refund.currency} and their subscription was cancelled`,+ user.email+ );+ }++ return refund;+ }+@Post('/add-subscription')async addSubscription(@Body() body: { subscription: string },diff --git a/apps/backend/src/api/routes/users.controller.ts b/apps/backend/src/api/routes/users.controller.tsindex cd4677927..05ffc7dfc 100644--- a/apps/backend/src/api/routes/users.controller.ts+++ b/apps/backend/src/api/routes/users.controller.ts@@ -30,7 +30,10 @@ import { UserAgent } from '@gitroom/nestjs-libraries/user/user.agent';import { TrackEnum } from '@gitroom/nestjs-libraries/user/track.enum';import { TrackService } from '@gitroom/nestjs-libraries/track/track.service';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';-import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';+import {+ AuthorizationActions,+ Sections,+} from '@gitroom/backend/services/auth/permissions/permission.exception.class';@ApiTags('User')@Controller('/user')@@ -43,6 +46,29 @@ export class UsersController {private _userService: UsersService,private _trackService: TrackService) {}++ @Get('/chatbase-token')+ async getChatbaseToken(+ @GetUserFromRequest() user: User,+ @GetOrgFromRequest() organization: Organization+ ) {+ if (!process.env.CHATBASE_TOKEN) {+ throw new HttpException('Chatbase SSO is not configured', 400);+ }++ const token = sign(+ {+ user_id: organization.id,+ displayName: organization.name,+ email: user.email,+ stripe_accounts: organization.paymentId,+ },+ process.env.CHATBASE_TOKEN+ );++ return { token };+ }+@Get('/agent-media-sso')async getAgentMediaSsoUrl(@GetUserFromRequest() user: User,@@ -75,21 +101,32 @@ export class UsersController {return {...user,orgId: organization.id,- // @ts-ignore- totalChannels: !process.env.STRIPE_PUBLISHABLE_KEY ? 10000 : organization?.subscription?.totalChannels || pricing.FREE.channel,- // @ts-ignore- tier: organization?.subscription?.subscriptionTier || (!process.env.STRIPE_PUBLISHABLE_KEY ? 'ULTIMATE' : 'FREE'),+ totalChannels: !process.env.STRIPE_PUBLISHABLE_KEY+ ? 10000+ : // @ts-ignore+ organization?.subscription?.totalChannels || pricing.FREE.channel,+ tier:+ // @ts-ignore+ organization?.subscription?.subscriptionTier ||+ (!process.env.STRIPE_PUBLISHABLE_KEY ? 'ULTIMATE' : 'FREE'),// @ts-ignorerole: organization?.users[0]?.role,// @ts-ignoreisLifetime: !!organization?.subscription?.isLifetime,admin: !!user.isSuperAdmin,impersonate: !!impersonate,- isTrailing: !process.env.STRIPE_PUBLISHABLE_KEY ? false : organization?.isTrailing,+ isTrailing: !process.env.STRIPE_PUBLISHABLE_KEY+ ? false+ : organization?.isTrailing,allowTrial: organization?.allowTrial,streakSince: organization?.streakSince || null,- // @ts-ignore- publicApi: organization?.users[0]?.role === 'SUPERADMIN' || organization?.users[0]?.role === 'ADMIN' ? organization?.apiKey : '',+ publicApi:+ // @ts-ignore+ organization?.users[0]?.role === 'SUPERADMIN' ||+ // @ts-ignore+ organization?.users[0]?.role === 'ADMIN'+ ? organization?.apiKey+ : '',};}diff --git a/apps/frontend/src/app/(app)/layout.tsx b/apps/frontend/src/app/(app)/layout.tsxindex 6cc75f04b..3a46e8d6f 100644--- a/apps/frontend/src/app/(app)/layout.tsx+++ b/apps/frontend/src/app/(app)/layout.tsx@@ -62,6 +62,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {backendUrl={process.env.NEXT_PUBLIC_BACKEND_URL!}plontoKey={process.env.NEXT_PUBLIC_POLOTNO!}stripeClient={process.env.STRIPE_PUBLISHABLE_KEY!}+ isChatBase={!!process.env.CHATBASE_TOKEN}billingEnabled={!!process.env.STRIPE_PUBLISHABLE_KEY}discordUrl={process.env.NEXT_PUBLIC_DISCORD_SUPPORT!}frontEndUrl={process.env.FRONTEND_URL!}diff --git a/apps/frontend/src/app/(extension)/layout.tsx b/apps/frontend/src/app/(extension)/layout.tsxindex f711e7de6..61db27158 100644--- a/apps/frontend/src/app/(extension)/layout.tsx+++ b/apps/frontend/src/app/(extension)/layout.tsx@@ -49,6 +49,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {telegramBotName={process.env.TELEGRAM_BOT_NAME!}neynarClientId={process.env.NEYNAR_CLIENT_ID!}isSecured={!process.env.NOT_SECURED}+ isChatBase={false}disableImageCompression={!!process.env.DISABLE_IMAGE_COMPRESSION}disableXAnalytics={!!process.env.DISABLE_X_ANALYTICS}sentryDsn={process.env.NEXT_PUBLIC_SENTRY_DSN!}diff --git a/apps/frontend/src/app/(provider)/layout.tsx b/apps/frontend/src/app/(provider)/layout.tsxindex 66c6dae04..a7cf39e27 100644--- a/apps/frontend/src/app/(provider)/layout.tsx+++ b/apps/frontend/src/app/(provider)/layout.tsx@@ -51,6 +51,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {telegramBotName={process.env.TELEGRAM_BOT_NAME!}neynarClientId={process.env.NEYNAR_CLIENT_ID!}isSecured={!process.env.NOT_SECURED}+ isChatBase={false}disableImageCompression={!!process.env.DISABLE_IMAGE_COMPRESSION}disableXAnalytics={!!process.env.DISABLE_X_ANALYTICS}sentryDsn={process.env.NEXT_PUBLIC_SENTRY_DSN!}diff --git a/apps/frontend/src/components/layout/chatbase.component.tsx b/apps/frontend/src/components/layout/chatbase.component.tsxnew file mode 100644index 000000000..f69fc4042--- /dev/null+++ b/apps/frontend/src/components/layout/chatbase.component.tsx@@ -0,0 +1,158 @@+'use client';++declare global {+ interface Window {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ chatbase: any;+ }+}++import { FC, useCallback, useEffect, useState } from 'react';+import Script from 'next/script';+import { useVariables } from '@gitroom/react/helpers/variable.context';+import { useFetch } from '@gitroom/helpers/utils/custom.fetch';+import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';+import useSWR from 'swr';++export const ChatbaseComponent: FC = () => {+ const { isChatBase } = useVariables();+ if (!isChatBase) {+ return null;+ }+ return <ChatbaseComponentLoad />;+};+export const ChatbaseComponentLoad: FC = () => {+ const fetch = useFetch();++ const { data } = useSWR(+ 'chatbase-token',+ async () => {+ const { token } = await (await fetch('/user/chatbase-token')).json();++ return token;+ },+ {+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ revalidateIfStale: false,+ refreshWhenHidden: false,+ refreshWhenOffline: false,+ refreshInterval: 0,+ }+ );++ if (!data) {+ return null;+ }++ return <ChatBaseCode token={data} />;+};++const ChatBaseCode: FC<{ token: string }> = ({ token }) => {+ const fetch = useFetch();++ useEffect(() => {+ if (!window.chatbase || window.chatbase('getState') !== 'initialized') {+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignore+ window.chatbase = (...arg) => {+ if (!window.chatbase.q) {+ window.chatbase.q = [];+ }+ window.chatbase.q.push(arg);+ };+ window.chatbase = new Proxy(window.chatbase, {+ get(target, prop) {+ if (prop === 'q') {+ return target.q;+ }+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignore+ return (...args) => target(prop, ...args);+ },+ });+ }+ const onLoad = function () {+ const script = document.createElement('script');+ script.src = 'https://www.chatbase.co/embed.min.js';+ script.id = '1zVZuOz0vgFE_NLumfPPj';+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignore+ script.domain = 'www.chatbase.co';+ document.body.appendChild(script);+ };+ if (document.readyState === 'complete') {+ onLoad();+ } else {+ window.addEventListener('load', onLoad);+ }++ window.chatbase('identify', { token });++ window.chatbase('registerTools', {+ stripe_refund: async () => {+ try {+ const previewResponse = await fetch('/billing/chatbase-refund/preview');++ if (!previewResponse.ok) {+ return {+ status: 'error',+ error: 'Could not process the refund request',+ };+ }++ const preview = await previewResponse.json();++ if (!preview.eligible) {+ return {+ status: 'success',+ data: { refunded: false, reason: preview.reason },+ };+ }++ const approved = await deleteDialog(+ `You are cancelling your ${+ preview.tier || ''+ } subscription and will receive a refund of ${preview.amount} ${(+ preview.currency || ''+ ).toUpperCase()}. Do you approve?`,+ 'Yes, cancel and refund',+ 'Cancel subscription'+ );++ if (!approved) {+ return {+ status: 'success',+ data: {+ refunded: false,+ reason: 'The user declined the refund confirmation',+ },+ };+ }++ const response = await fetch('/billing/chatbase-refund', {+ method: 'POST',+ });++ if (!response.ok) {+ return {+ status: 'error',+ error: 'Could not process the refund request',+ };+ }++ return {+ status: 'success',+ data: await response.json(),+ };+ } catch (err) {+ return {+ status: 'error',+ error: 'Could not process the refund request',+ };+ }+ },+ });+ }, []);+ return null;+};diff --git a/apps/frontend/src/components/layout/support.tsx b/apps/frontend/src/components/layout/support.tsxindex 77de166bf..00279f4cf 100644--- a/apps/frontend/src/components/layout/support.tsx+++ b/apps/frontend/src/components/layout/support.tsx@@ -4,10 +4,11 @@ import { EventEmitter } from 'events';import { useEffect, useState } from 'react';import { useVariables } from '@gitroom/react/helpers/variable.context';import { useT } from '@gitroom/react/translation/get.transation.service.client';+import { ChatbaseComponent } from '@gitroom/frontend/components/layout/chatbase.component';export const supportEmitter = new EventEmitter();export const Support = () => {const [show, setShow] = useState(true);- const { discordUrl } = useVariables();+ const { discordUrl, isChatBase } = useVariables();const t = useT();useEffect(() => {@@ -16,6 +17,9 @@ export const Support = () => {supportEmitter.off('state', setShow);};}, []);+ if (isChatBase) {+ return <ChatbaseComponent />;+ }if (!discordUrl || !show) return null;return (<divdiff --git a/libraries/nestjs-libraries/src/services/stripe.service.ts b/libraries/nestjs-libraries/src/services/stripe.service.tsindex e36d74bea..235ba5996 100644--- a/libraries/nestjs-libraries/src/services/stripe.service.ts+++ b/libraries/nestjs-libraries/src/services/stripe.service.ts@@ -939,6 +939,155 @@ export class StripeService {return { cancelled: true };}+ async chatbaseRefundPreview(organizationId: string) {+ const org = await this._organizationService.getOrgById(organizationId);+ if (!org?.paymentId) {+ return {+ eligible: false as const,+ reason: '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) {+ return {+ eligible: false as const,+ reason: 'No active subscription found for this customer',+ };+ }++ const charges = (+ await stripe.charges.list({+ customer,+ limit: 100,+ })+ ).data.filter((f) => f.status === 'succeeded');++ if (charges.some((f) => f.refunded || f.amount_refunded > 0)) {+ return {+ eligible: false as const,+ reason: 'A refund was already issued for this customer',+ };+ }++ // only refund a charge that was created by the active subscription,+ // never a one-off payment+ let lastCharge: (typeof charges)[number] | undefined = undefined;+ let chargeSubscription: (typeof subscriptions)[number] | undefined =+ undefined;++ for (const charge of charges) {+ const invoiceId = (charge as any).invoice;+ if (!invoiceId || typeof invoiceId !== 'string') {+ continue;+ }++ try {+ const invoice = await stripe.invoices.retrieve(invoiceId);+ const invoiceSubscription =+ invoice.parent?.subscription_details?.subscription;+ const subscriptionId =+ typeof invoiceSubscription === 'string'+ ? invoiceSubscription+ : invoiceSubscription?.id;++ chargeSubscription = subscriptions.find(+ (f) => f.id === subscriptionId+ );++ if (chargeSubscription) {+ lastCharge = charge;+ break;+ }+ } catch {+ // ignore if invoice can't be fetched+ }+ }++ if (!lastCharge || !chargeSubscription) {+ return {+ eligible: false as const,+ reason: 'No subscription payment found for this customer',+ };+ }++ const sixtyDaysAgo = Math.floor(Date.now() / 1000) - 60 * 24 * 60 * 60;+ if (lastCharge.created < sixtyDaysAgo) {+ return {+ eligible: false as const,+ reason: 'The last subscription payment is older than 60 days',+ };+ }++ const interval =+ chargeSubscription.items?.data?.[0]?.price?.recurring?.interval;++ // maximum refund is one month worth of the subscription+ const amount =+ interval === 'year'+ ? Math.floor(lastCharge.amount / 12)+ : lastCharge.amount;++ const currentSubscription =+ await this._subscriptionService.getSubscriptionByOrganizationId(+ organizationId+ );++ return {+ eligible: true as const,+ chargeId: lastCharge.id,+ amount: amount / 100,+ currency: lastCharge.currency,+ tier: currentSubscription?.subscriptionTier || null,+ period: currentSubscription?.period || null,+ subscriptionIds: subscriptions.map((f) => f.id),+ };+ }++ async chatbaseRefund(organizationId: string) {+ const preview = await this.chatbaseRefundPreview(organizationId);+ if (!preview.eligible) {+ return {+ refunded: false,+ reason: preview.reason,+ };+ }++ const org = await this._organizationService.getOrgById(organizationId);++ await stripe.refunds.create({+ charge: preview.chargeId,+ amount: Math.round(preview.amount * 100),+ metadata: {+ reason: 'chatbase_refund',+ organizationId,+ },+ });++ for (const subscriptionId of preview.subscriptionIds) {+ await stripe.subscriptions.cancel(subscriptionId);+ }++ if (preview.subscriptionIds.length) {+ await this._subscriptionService.deleteSubscription(org?.paymentId!);+ }++ return {+ refunded: true,+ amount: preview.amount,+ currency: preview.currency,+ subscriptionCancelled: preview.subscriptionIds.length > 0,+ };+ }+async lifetimeDeal(organizationId: string, code: string) {const getCurrentSubscription =await this._subscriptionService.getSubscriptionByOrganizationId(diff --git a/libraries/react-shared-libraries/src/helpers/variable.context.tsx b/libraries/react-shared-libraries/src/helpers/variable.context.tsxindex 7a559740c..3243cf245 100644--- a/libraries/react-shared-libraries/src/helpers/variable.context.tsx+++ b/libraries/react-shared-libraries/src/helpers/variable.context.tsx@@ -4,6 +4,7 @@ import { createContext, FC, ReactNode, useContext, useEffect } from 'react';interface VariableContextInterface {stripeClient: string;billingEnabled: boolean;+ isChatBase: boolean;isGeneral: boolean;genericOauth: boolean;oauthLogoUrl: string;@@ -37,6 +38,7 @@ const VariableContext = createContext({billingEnabled: false,isGeneral: true,genericOauth: false,+ isChatBase: false,oauthLogoUrl: '',googleAdsId: '',googleAdsTrialTracking: '',