The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
import { useNumberFormat } from '@/localization/hooks/useNumberFormat';
import { useApplyCurrentWorkspaceBillingUpdate } from '@/settings/billing/hooks/useApplyCurrentWorkspaceBillingUpdate';
import { useGetNextResourceCreditPrice } from '@/settings/billing/hooks/useGetNextResourceCreditPrice';
import { CombinedGraphQLErrors } from '@apollo/client/errors';
import { useMutation } from '@apollo/client/react';
import { isDefined } from 'twenty-shared/utils';
import { useToast } from 'twenty-ui/components/feedback';
import {
SetResourceCreditSubscriptionPriceDocument,
SubscriptionInterval,
} from '~/generated-metadata/graphql';
import { useLingui } from '@lingui/react/macro';
export const useCreditUpgradeAction = () => {
const { t } = useLingui();
const nextPrice = useGetNextResourceCreditPrice();
const { formatNumber } = useNumberFormat();
const { enqueueToast } = useToast();
const { applyCurrentWorkspaceBillingUpdate } =
useApplyCurrentWorkspaceBillingUpdate();
const [setResourceCreditSubscriptionPrice, { loading: isUpgrading }] =
useMutation(SetResourceCreditSubscriptionPriceDocument);
const nextResourceCreditsAmount = isDefined(nextPrice)
? formatNumber(nextPrice.creditAmount ?? 0, {
abbreviate: true,
decimals: 2,
})
: null;
const nextResourceCreditPrice = isDefined(nextPrice)
? formatNumber((nextPrice.unitAmount ?? 0) / 100)
: null;
const nextTierInterval = isDefined(nextPrice)
? nextPrice.recurringInterval === SubscriptionInterval.Month
? t`month`
: t`year`
: null;
const upgradeCreditPlan = async () => {
if (!isDefined(nextPrice)) {
return;
}
try {
enqueueToast({ status: 'info', children: t`Upgrading subscription...` });
const { data } = await setResourceCreditSubscriptionPrice({
variables: { priceId: nextPrice.stripePriceId },
});
applyCurrentWorkspaceBillingUpdate(
data?.setResourceCreditSubscriptionPrice,
{
transformCurrentBillingSubscription: (
currentBillingSubscription,
) => ({
...currentBillingSubscription,
billingSubscriptionItems:
currentBillingSubscription.billingSubscriptionItems?.map(
(item) => ({
...item,
hasReachedCurrentPeriodCap: false,
}),
),
}),
},
);
enqueueToast({ status: 'success', children: t`Credit plan upgraded.` });
} catch (error) {
enqueueToast({
status: 'error',
children: t`Failed to upgrade credit plan.`,
});
if (!CombinedGraphQLErrors.is(error)) {
throw error;
}
}
};
return {
nextPrice,
nextResourceCreditsAmount,
nextResourceCreditPrice,
nextTierInterval,
upgradeCreditPlan,
isUpgrading,
};
};