2023-07-12 11:57:24 +08:00
|
|
|
import { type Optional } from '@silverhand/essentials';
|
2023-07-10 16:38:53 +08:00
|
|
|
import { useMemo } from 'react';
|
2023-07-17 10:36:09 +08:00
|
|
|
import useSWRImmutable from 'swr/immutable';
|
2023-07-10 16:38:53 +08:00
|
|
|
|
2023-07-17 10:36:09 +08:00
|
|
|
import { useCloudApi } from '@/cloud/hooks/use-cloud-api';
|
|
|
|
import { type SubscriptionPlanResponse } from '@/cloud/types/router';
|
2023-07-24 17:08:39 +08:00
|
|
|
import { isCloud } from '@/consts/env';
|
2023-11-20 15:45:28 +08:00
|
|
|
import { featuredPlanIdOrder } from '@/consts/subscriptions';
|
2024-01-02 11:02:16 +08:00
|
|
|
// Used in the docs
|
|
|
|
// eslint-disable-next-line unused-imports/no-unused-imports
|
|
|
|
import TenantAccess from '@/containers/TenantAccess';
|
2023-07-10 16:38:53 +08:00
|
|
|
import { type SubscriptionPlan } from '@/types/subscriptions';
|
2023-07-26 11:41:15 +08:00
|
|
|
import { sortBy } from '@/utils/sort';
|
2023-07-17 10:36:09 +08:00
|
|
|
import { addSupportQuotaToPlan } from '@/utils/subscription';
|
2023-07-10 16:38:53 +08:00
|
|
|
|
2024-01-02 11:02:16 +08:00
|
|
|
/**
|
|
|
|
* Fetch subscription plans from the cloud API.
|
|
|
|
* Note: If you want to retrieve subscription plans under the {@link TenantAccess} component, use `SubscriptionDataContext` instead.
|
|
|
|
*/
|
2023-07-10 16:38:53 +08:00
|
|
|
const useSubscriptionPlans = () => {
|
2023-07-17 10:36:09 +08:00
|
|
|
const cloudApi = useCloudApi();
|
2024-01-05 12:27:27 +08:00
|
|
|
|
2023-07-17 14:32:11 +08:00
|
|
|
const useSwrResponse = useSWRImmutable<SubscriptionPlanResponse[], Error>(
|
2023-07-24 17:08:39 +08:00
|
|
|
isCloud && '/api/subscription-plans',
|
2023-07-24 15:06:59 +08:00
|
|
|
async () => cloudApi.get('/api/subscription-plans')
|
2023-07-17 14:32:11 +08:00
|
|
|
);
|
|
|
|
|
|
|
|
const { data: subscriptionPlansResponse } = useSwrResponse;
|
2023-07-10 16:38:53 +08:00
|
|
|
|
2023-07-12 11:57:24 +08:00
|
|
|
const subscriptionPlans: Optional<SubscriptionPlan[]> = useMemo(() => {
|
|
|
|
if (!subscriptionPlansResponse) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-07-17 10:36:09 +08:00
|
|
|
return subscriptionPlansResponse
|
|
|
|
.map((plan) => addSupportQuotaToPlan(plan))
|
|
|
|
.slice()
|
2023-07-26 11:41:15 +08:00
|
|
|
.sort(({ id: previousId }, { id: nextId }) =>
|
2023-11-20 15:45:28 +08:00
|
|
|
sortBy(featuredPlanIdOrder)(previousId, nextId)
|
2023-07-26 11:41:15 +08:00
|
|
|
);
|
2023-07-12 11:57:24 +08:00
|
|
|
}, [subscriptionPlansResponse]);
|
2023-07-10 16:38:53 +08:00
|
|
|
|
|
|
|
return {
|
2023-07-17 14:32:11 +08:00
|
|
|
...useSwrResponse,
|
2023-07-10 16:38:53 +08:00
|
|
|
data: subscriptionPlans,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export default useSubscriptionPlans;
|