Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

remove analytics page + my-plan

Ahmed Essam46cf796fe327
diff --git a/packages/app/src/react/app/routeMap.tsx b/packages/app/src/react/app/routeMap.tsx
index 211eb1b5..adbb487c 100644
--- a/packages/app/src/react/app/routeMap.tsx
+++ b/packages/app/src/react/app/routeMap.tsx
@@ -1,5 +1,3 @@
-import AnalyticsPage from '@react/features/analytics/pages/AnalyticsPage';
-import MyPlanPage from '@react/features/subscriptions/pages/MyPlanPage';
import VaultPage from '@react/features/vault/pages/VaultPage';
import AgentsPage from '@src/react/features/agents/pages/AgentsPage';
import { IPageRoute } from '@src/react/shared/types/route';
@@ -150,18 +148,8 @@ export const routeMap: IPageRoute[] = [
layoutOptions: { background: 'agentsGradient' },
},
- {
- title: 'My Plan',
- path: 'my-plan',
- component: MyPlanPage,
- layoutOptions: { sidebar: true, topMenu: true },
- },
- {
- title: 'Analytics',
- path: 'analytics',
- component: AnalyticsPage,
- layoutOptions: { sidebar: true, topMenu: true },
- },
+
+
{
title: 'Vault',
path: 'vault',
diff --git a/packages/app/src/react/features/analytics/client/usageAnalytics.ts b/packages/app/src/react/features/analytics/client/usageAnalytics.ts
deleted file mode 100644
index c9cb624d..00000000
--- a/packages/app/src/react/features/analytics/client/usageAnalytics.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-export const fetchLLMAndApiUsage = async (teamId: string, date: any) => {
- const response = await fetch(
- `/api/page/quota/quota/usage/${teamId}/llm-tokens-and-api-requests?date=${date}`,
- {
- method: 'GET',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- },
- credentials: 'include',
- },
- );
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- if (errorData.message) {
- throw new Error(errorData.message);
- } else {
- throw new Error(`Failed to fetch usage data: ${response.statusText}`);
- }
- }
-
- return response.json();
-};
-
-export const fetchCurrentCycleUsage = async () => {
- const response = await fetch('/api/page/quota/quota/current-cycle/usage', {
- method: 'GET',
- headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
- credentials: 'include',
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- if (errorData.message) {
- throw new Error(errorData.message);
- } else {
- throw new Error(`Failed to fetch usage data: ${response.statusText}`);
- }
- }
-
- return response.json();
-};
diff --git a/packages/app/src/react/features/analytics/components/stacked-bar-chart.tsx b/packages/app/src/react/features/analytics/components/stacked-bar-chart.tsx
deleted file mode 100644
index 2fa0ec2e..00000000
--- a/packages/app/src/react/features/analytics/components/stacked-bar-chart.tsx
+++ /dev/null
@@ -1,219 +0,0 @@
-import { useEffect, useRef, useState } from 'react';
-import { Chart } from 'chart.js/auto';
-
-export default function StackedBarChart({ chartData }) {
- const chartRef = useRef(null);
- const [chart, setChart] = useState(null);
-
- function fillMissingDaysInMonth(chartData) {
- // 1) If no labels or empty data, just return as is
- if (!chartData || !chartData.labels || chartData.labels.length === 0) {
- return chartData;
- }
-
- // 2) Parse the "month" + "year" from the *first* label (e.g., "Feb 2")
- // We'll assume the current year for the parse.
- const firstLabel = chartData.labels[0];
- const firstDate = new Date(`${firstLabel}, ${new Date().getFullYear()}`);
- const year = firstDate.getFullYear();
- const month = firstDate.getMonth(); // 0-based
-
- // 3) Determine how many days are in that month (28..31, depending on month/year)
- const daysInMonth = new Date(year, month + 1, 0).getDate();
-
- // 4) Generate all possible day labels for that month, e.g. "Feb 1", "Feb 2", ...
- const allDates = [];
- for (let day = 1; day <= daysInMonth; day++) {
- const d = new Date(year, month, day);
- const label = d.toLocaleString('en-US', { month: 'short', day: 'numeric' });
- allDates.push(label);
- }
-
- // 5) Map existing label => index
- const existingLabelIndex = new Map();
- chartData.labels.forEach((lbl, i) => {
- existingLabelIndex.set(lbl, i);
- });
-
- // 6) For each dataset, build a new data array with zero if the day is missing
- const newDatasets = chartData.datasets.map((ds) => {
- const newData = allDates.map((dateLabel) => {
- if (existingLabelIndex.has(dateLabel)) {
- const oldIndex = existingLabelIndex.get(dateLabel);
- return ds.data[oldIndex] ?? 0; // fallback to 0 if undefined
- }
- // Missing => 0
- return 0;
- });
- return {
- ...ds,
- data: newData,
- };
- });
-
- // 7) If there's no breakdown property at all, just return updated labels/datasets
- if (!chartData.breakdown) {
- return {
- labels: allDates,
- datasets: newDatasets,
- };
- }
-
- // 8) If we do have a breakdown, fill missing days with empty arrays
- const oldBreakdown = chartData.breakdown;
- const newBreakdown = {};
- for (const dayLabel of allDates) {
- if (oldBreakdown[dayLabel]) {
- // reuse existing
- newBreakdown[dayLabel] = oldBreakdown[dayLabel];
- } else {
- // otherwise create empty arrays for each dataset label
- newBreakdown[dayLabel] = {};
- for (const ds of newDatasets) {
- newBreakdown[dayLabel][ds.label] = [];
- }
- }
- }
-
- // 9) Return the fully updated chart data
- return {
- labels: allDates,
- datasets: newDatasets,
- breakdown: newBreakdown,
- };
- }
-
- // If all datasets are empty or there's no data
- const hasNoData =
- !chartData?.datasets?.length || chartData.datasets.every((ds) => ds.data.every((v) => v === 0));
-
- // Destroy old chart instance, create a new one
- useEffect(() => {
- if (!chartRef.current) return;
- if (chart) chart.destroy();
-
- const ctx = chartRef.current.getContext('2d');
- if (!ctx) return;
-
- const newChart = new Chart(ctx, {
- type: 'bar',
- data: fillMissingDaysInMonth(chartData),
- options: {
- responsive: true,
- maintainAspectRatio: false,
- interaction: {
- mode: 'index',
- intersect: false,
- },
- scales: {
- x: {
- stacked: true,
- grid: { display: false },
- },
- y: {
- stacked: true,
- beginAtZero: true,
- ticks: {
- callback: (value) => {
- // e.g. show K, M
- if (typeof value === 'number') {
- if (value >= 1_000_000) return `${value / 1_000_000}M`;
- if (value >= 1000) return `${value / 1000}K`;
- return value;
- }
- return value;
- },
- },
- },
- },
- plugins: {
- legend: {
- position: 'bottom',
- align: 'end',
- reverse: true,
- labels: {
- usePointStyle: true,
- pointStyle: 'circle',
- padding: 20,
- boxWidth: 6,
- boxHeight: 6,
- },
- },
- tooltip: {
- itemSort: (a, b) => b.datasetIndex - a.datasetIndex,
- backgroundColor: 'rgb(0, 0, 0)',
- padding: 16,
- titleColor: '#FFF',
- titleFont: { size: 16, weight: 'normal' },
- titleAlign: 'left',
- bodySpacing: 8,
- bodyFont: { size: 14 },
- bodyColor: '#FFF',
- displayColors: true,
- boxPadding: 8,
- cornerRadius: 8,
- usePointStyle: true,
- boxWidth: 8,
- boxHeight: 8,
- callbacks: {
- title: (tooltipItems) => {
- return tooltipItems[0]?.label || '';
- },
- label: (context: any) => {
- const cat = context.dataset.label;
- const dayLabel = context.label;
- const breakdown = context.chart.data.breakdown || {};
- const childItems = breakdown?.[dayLabel]?.[cat] || [];
-
- if (!childItems.length) return;
-
- let lines = [];
- for (const child of childItems) {
- // skip zero-cost if desired
- // if (child.cost === 0) continue;
-
- // look up a friendly name
- // let displayName = friendlyNameMap[child.name] ?? child.name;
- let displayName = child.name;
-
- // you can also rename entire categories if needed
- if (cat === 'Tasks') {
- displayName = 'Agent Tasks';
- } else if (cat === 'Weaver') {
- displayName = 'Weaver';
- } else if (cat === 'Image Generation') {
- displayName = 'Image Generation';
- }
-
- lines.push(`${displayName} : $${child.cost.toFixed(5)}`);
- }
-
- if (!lines.length) return;
- return lines; // multi-line in the tooltip
- },
- },
- },
- },
- },
- });
-
- setChart(newChart);
-
- return () => {
- if (newChart) newChart.destroy();
- };
- }, [chartData]);
-
- return (
- <div className="relative">
- <div className="h-[400px] w-full">
- <canvas ref={chartRef} />
- {hasNoData && (
- <div className="absolute inset-0 flex items-center justify-center">
- <p className="text-gray-500">No data for this period</p>
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/packages/app/src/react/features/analytics/components/subscription-analytics.tsx b/packages/app/src/react/features/analytics/components/subscription-analytics.tsx
deleted file mode 100644
index 65c78bc7..00000000
--- a/packages/app/src/react/features/analytics/components/subscription-analytics.tsx
+++ /dev/null
@@ -1,956 +0,0 @@
-/* eslint-disable max-len, @typescript-eslint/no-explicit-any, react-hooks/exhaustive-deps, no-console */
-
-import {
- Card,
- CardContent,
- CardDescription,
- CardFooter,
- CardHeader,
- CardTitle,
-} from '@src/react/shared/components/ui/card';
-import { Tooltip } from 'flowbite-react';
-import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-
-import {
- fetchCurrentCycleUsage,
- fetchLLMAndApiUsage,
-} from '@react/features/analytics/client/usageAnalytics';
-import {
- useGetTeamSettings,
- useStoreTeamSettings,
-} from '@react/features/teams/hooks/useTeamSettings';
-import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
-import { formatDate } from '@src/react/shared/utils/format';
-import { teamSettingKeys } from '@src/shared/teamSettingKeys';
-import classNames from 'classnames';
-import { Loader2 } from 'lucide-react';
-import { HiOutlineArrowRight } from 'react-icons/hi';
-import { useAuthCtx } from '../../../shared/contexts/auth.context';
-
-// eslint-disable-next-line react-refresh/only-export-components
-export const ENTERPRISE_PLAN_NAMES = [
- 'Enterprise',
- 'Enterprise T1',
- 'Enterprise T2',
- 'Enterprise T3',
- 'Enterprise T4',
-] as const;
-
-const V4_PLAN_NAMES = [
- 'builder',
- 'startup',
- 'scaleup',
- 'enterprise t1',
- 'enterprise t2',
- 'enterprise t3',
- 'enterprise t4',
-];
-
-function isValid(value: number | string | null | undefined): boolean {
- return value !== undefined && value !== null && value !== 0 && value !== '';
-}
-
-interface SimpleCardProps {
- title: string;
- value: number | string | null | undefined;
- description?: string;
- dataQa?: string;
-}
-
-/**
- * A simple card component that displays a title, value, and description
- * @param props SimpleCardProps containing title, value, and description
- * @returns React component displaying card with provided information
- */
-const SimpleCard: React.FC<SimpleCardProps> = ({
- title,
- value,
- description = 'Current period',
- dataQa,
-}) => {
- // Check if description is the default value or empty
- const isDescriptionEmpty = !description || description === 'Current period';
-
- return (
- <Card>
- <CardHeader className={classNames('pb-2', { 'pt-8': isDescriptionEmpty })}>
- <CardTitle className="text-base">{title}</CardTitle>
- </CardHeader>
- <CardContent>
- <div className="text-2xl font-bold" data-qa={dataQa}>
- {value}
- </div>
- {description && <div className="text-sm text-muted-foreground">{description}</div>}
- </CardContent>
- </Card>
- );
-};
-
-interface CancelSubscriptionCardProps {
- isCancelled: boolean;
-}
-
-// Stable BillingLimitCard component defined outside the main component
-const BillingLimitCard = React.memo(
- ({
- initialBillingLimitSettings,
- storeTeamSettings,
- parentTeam,
- freeCredits,
- }: {
- initialBillingLimitSettings: any;
- storeTeamSettings: any;
- parentTeam: any;
- freeCredits: number;
- }) => {
- const [enableBillingLimit, setEnableBillingLimit] = useState(false);
- const [showSaved, setShowSaved] = useState(false);
- const [isSavingBillingLimit, setIsSavingBillingLimit] = useState(false);
- const [errorMessage, setErrorMessage] = useState<string>('');
- const [inputValue, setInputValue] = useState(freeCredits.toString());
- const [hasInputChanged, setHasInputChanged] = useState(false);
-
- const lastSavedValue = useRef(freeCredits);
- const hideTimeoutRef = useRef<NodeJS.Timeout>();
- const inputRef = useRef<HTMLInputElement>(null);
- const validationTimeoutRef = useRef<NodeJS.Timeout>();
- const isInitialized = useRef(false);
-
- // Initialize from settings only once - completely ignore subsequent changes
- const initialSettings = useRef(initialBillingLimitSettings);
- useEffect(() => {
- if (initialSettings.current && !isInitialized.current) {
- const savedValue = Math.max(
- initialSettings.current?.limitValue || freeCredits,
- freeCredits,
- );
- setEnableBillingLimit(initialSettings.current.isLimitEnabled);
- setInputValue(savedValue.toString());
- lastSavedValue.current = savedValue;
- isInitialized.current = true;
- }
- }, []); // Empty dependency array - only run once
-
- // Validation function
- const validateValue = useCallback(
- (value: number): { isValid: boolean; error: string } => {
- if (value < freeCredits) {
- return {
- isValid: false,
- error: `Your account comes with ${freeCredits} free credit! To ensure it's fully applied, please set your limit to above ${freeCredits}.`,
- };
- }
- return { isValid: true, error: '' };
- },
- [freeCredits],
- );
-
- const showSavedIndicator = useCallback(() => {
- setShowSaved(true);
- if (hideTimeoutRef.current) {
- clearTimeout(hideTimeoutRef.current);
- }
- hideTimeoutRef.current = setTimeout(() => {
- setShowSaved(false);
- }, 1500);
- }, []);
-
- // Save function - only saves when explicitly called
- const saveValue = useCallback(
- (value: number, isEnabled: boolean) => {
- if (!parentTeam?.id) return;
-
- let validValue = value;
- const validation = validateValue(validValue);
- if (!validation.isValid) {
- // Auto-correct to freeCredits if invalid
- validValue = freeCredits;
- setInputValue(validValue.toString());
- setErrorMessage('');
- }
-
- const settingsData = {
- teamId: parentTeam?.id,
- limitValue: validValue,
- isLimitEnabled: isEnabled,
- };
- setIsSavingBillingLimit(true);
-
- lastSavedValue.current = validValue;
- storeTeamSettings.mutate(settingsData, {
- onSuccess: () => {
- showSavedIndicator();
- },
- onError: (error) => {
- console.error('Save failed:', error);
- },
- onSettled: () => {
- setIsSavingBillingLimit(false);
- },
- });
- },
- [parentTeam?.id, storeTeamSettings, showSavedIndicator, validateValue, freeCredits],
- );
-
- // Handle input changes (typing) with validation buffer
- const handleInputChange = useCallback(
- (newInputValue: string) => {
- setInputValue(newInputValue);
-
- const numericValue = parseInt(newInputValue) || 0;
-
- const preSaveBtnValidation = validateValue(numericValue);
- setHasInputChanged(preSaveBtnValidation.isValid);
- // Clear previous validation timeout
- if (validationTimeoutRef.current) {
- clearTimeout(validationTimeoutRef.current);
- }
-
- // Buffer validation for 800ms
- validationTimeoutRef.current = setTimeout(() => {
- const validation = validateValue(numericValue);
- setErrorMessage(validation.error);
- }, 800);
- },
- [validateValue],
- );
-
- // Handle input blur - correct only negative values to 0
- const handleInputBlur = useCallback(() => {
- const numericValue = parseInt(inputValue) || 0;
- if (numericValue < 0) {
- setInputValue('0');
- const validation = validateValue(0);
- setErrorMessage(validation.error);
- }
- }, [inputValue, validateValue]);
-
- // Handle toggle
- const handleToggle = useCallback(() => {
- const newEnabled = !enableBillingLimit;
- setEnableBillingLimit(newEnabled);
-
- // Use the last saved value, not the current input value
- const currentValue = lastSavedValue.current;
-
- // Save immediately when toggling
- saveValue(currentValue, newEnabled);
- }, [enableBillingLimit, saveValue]);
-
- // Handle save button click
- const handleSave = useCallback(() => {
- const currentValue = parseInt(inputValue) || 0;
- saveValue(currentValue, enableBillingLimit);
- }, [inputValue, enableBillingLimit, saveValue]);
-
- // Cleanup timeouts
- useEffect(() => {
- return () => {
- if (hideTimeoutRef.current) {
- clearTimeout(hideTimeoutRef.current);
- }
- if (validationTimeoutRef.current) {
- clearTimeout(validationTimeoutRef.current);
- }
- };
- }, []);
-
- return (
- <Card className="min-h-[150px]">
- <CardHeader className="pb-2 pt-6">
- <div className="flex items-center justify-between">
- <CardTitle className="text-base">Set Billing Limit</CardTitle>
- <div className="flex items-center gap-4">
- <div
- className={`text-xs transition-opacity duration-300 text-[#45C9A9] ${
- showSaved || isSavingBillingLimit ? 'opacity-100' : 'opacity-0'
- }`}
- >
- {isSavingBillingLimit ? 'Saving...' : 'Saved'}
- </div>
- <button
- type="button"
- className={`relative w-11 h-6 rounded-full cursor-pointer transition-colors duration-200 ease-in-out ${
- enableBillingLimit ? 'bg-v2-blue' : 'bg-gray-200'
- }`}
- onClick={handleToggle}
- aria-pressed={enableBillingLimit}
- role="switch"
- >
- <div
- className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform duration-200 ease-in-out ${
- enableBillingLimit ? 'translate-x-5' : 'translate-x-0'
- }`}
- />
- </button>
- </div>
- </div>
- </CardHeader>
- <CardContent className="p-6">
- <div
- className={`absolute w-[calc(100%-48px)] top-[40%] ${
- !enableBillingLimit ? 'opacity-70 pointer-events-none' : ''
- }`}
- >
- <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">$</span>
- <input
- ref={inputRef}
- type="number"
- step="1"
- min={0}
- value={inputValue}
- disabled={!enableBillingLimit}
- className="w-full pl-7 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#45C9A9] focus:border-transparent [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- onChange={(e) => handleInputChange(e.target.value)}
- onBlur={handleInputBlur}
- />
- {errorMessage && (
- <div className="absolute mt-1 text-sm text-red-500">{errorMessage}</div>
- )}
- {enableBillingLimit && hasInputChanged && (
- <button
- type="button"
- className="absolute right-2 top-1/2 -translate-y-1/2 bg-v2-blue text-white px-3 py-1 rounded text-sm hover:bg-blue-600 transition-colors disabled:opacity-50 w-14 text-center"
- onClick={() => {
- setHasInputChanged(false);
- handleSave();
- }}
- disabled={isSavingBillingLimit}
- >
- Save
- </button>
- )}
- </div>
- </CardContent>
- </Card>
- );
- },
- // Custom comparison function to prevent unnecessary re-renders
- (prevProps, nextProps) => {
- // Only re-render if essential props change (ignore initialBillingLimitSettings changes)
- return (
- prevProps.storeTeamSettings === nextProps.storeTeamSettings &&
- prevProps.parentTeam?.id === nextProps.parentTeam?.id &&
- prevProps.freeCredits === nextProps.freeCredits
- );
- },
-);
-
-BillingLimitCard.displayName = 'BillingLimitCard';
-
-// Create a stable wrapper component that never re-renders
-const StableBillingLimitWrapper = React.memo(
- ({
- billingLimitSettings,
- storeTeamSettings,
- parentTeam,
- freeCredits,
- }: {
- billingLimitSettings: any;
- storeTeamSettings: any;
- parentTeam: any;
- freeCredits: number;
- }) => {
- return (
- <BillingLimitCard
- initialBillingLimitSettings={billingLimitSettings}
- storeTeamSettings={storeTeamSettings}
- parentTeam={parentTeam}
- freeCredits={freeCredits}
- />
- );
- },
- () => true,
-); // Always return true to prevent re-renders
-
-StableBillingLimitWrapper.displayName = 'StableBillingLimitWrapper';
-
-export default function SubscriptionAnalytics({
- isLoading,
- loadingCancelPlan,
- loadingRestartPlan,
- usage,
- tasksUsage,
- subs,
- handleUnsubscribe,
- handleUpgrade,
- getFormattedNumber,
- isReadOnlyAccess,
- hasWriteAccess,
- isCustomPlan,
- userDisplayName,
- loadingUpgrade,
-}) {
- const [, setLlmAndApiUsage] = useState<any>(null); // llmAndApiUsage
- const [selectedMonth] = useState<Date>(new Date());
- const [showModelUsage, setShowModelUsage] = useState(false);
- const [modelLimit, setModelLimit] = useState(0);
- const [showLimitCard, setShowLimitCard] = useState(false);
- const [subscriptionPeriod, setSubscriptionPeriod] = useState<string>('');
- const [totalModelUsage, setTotalModelUsage] = useState<string>('0');
-
- const [isShowLimitFeature, setIsShowLimitFeature] = useState(
- subs?.plan?.properties?.flags?.modelCostMultiplier,
- );
- const { userInfo, userTeams } = useAuthCtx();
- const parentTeam = userTeams?.find((team) => !team.parentId);
- const { data: billingLimitSettings } = useGetTeamSettings(
- teamSettingKeys.BILLING_LIMIT,
- parentTeam?.id,
- );
-
- const freeCredits = subs?.properties?.freeCredits
- ? subs?.properties?.freeCredits
- : subs?.plan?.isDefaultPlan
- ? 5
- : 0;
-
- useEffect(() => {
- const fetchData = async () => {
- const data = await fetchLLMAndApiUsage(parentTeam?.id, selectedMonth);
- setLlmAndApiUsage(data);
- };
-
- fetchData();
- }, []);
-
- useEffect(() => {
- if (subs?.plan?.properties?.flags?.modelCostMultiplier) {
- setShowModelUsage(true);
- setModelLimit(freeCredits);
- }
- }, [subs]);
-
- useEffect(() => {
- const isFreePlan = subs?.plan?.name.toLowerCase().includes('smythos free');
- const isV4Plan = V4_PLAN_NAMES.includes(subs?.plan?.name.toLowerCase());
-
- const subPeriodDate = (start: Date, end: Date) => {
- const startDate = new Date(start);
- const endDate = new Date(end);
- return `${formatDate(startDate.getTime() / 1000)} - ${formatDate(endDate.getTime() / 1000)}`;
- };
-
- if (isV4Plan && !isFreePlan) {
- setSubscriptionPeriod(
- subPeriodDate(
- new Date(subs.object.current_period_start * 1000),
- new Date(subs.object.current_period_end * 1000),
- ),
- );
- } else {
- // Get first and last day of current month
- const now = new Date();
- const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
- const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0); // Using 0 gets the last day of current month
-
- setSubscriptionPeriod(subPeriodDate(firstDay, lastDay));
- }
- }, [subs]);
-
- useEffect(() => {
- const fetchModelUsage = async () => {
- try {
- const currentCycleUsage = await fetchCurrentCycleUsage();
- setTotalModelUsage(Number(currentCycleUsage?.usage || 0).toFixed(2));
- } catch (error) {
- console.error('Error fetching model usage:', error);
- setTotalModelUsage('0');
- }
- };
-
- fetchModelUsage();
- }, []);
-
- // const totalModelUsage = useMemo(() => {
- // if (!llmAndApiUsage) return 0;
-
- // const totalUsage = (apiData: ApiData) => {
- // let totalCost = 0;
-
- // apiData.usage.analytics.forEach((team) => {
- // // Add null check for team.data.days
- // if (team.data?.days) {
- // Object.values(team.data.days as any).forEach((day: any) => {
- // Object.entries(day.agents || ({} as any)).forEach(([, agentData]: any) => {
- // Object.values(agentData.sources || ({} as any)).forEach((source: any) => {
- // Object.values(source).forEach((metric: any) => {
- // totalCost += metric.cost || 0;
- // });
- // });
- // });
- // });
- // }
- // });
-
- // return Number(totalCost.toFixed(2));
- // };
-
- // return totalUsage(llmAndApiUsage);
- // }, [llmAndApiUsage]);
-
- // Load saved settings on component mount
-
- useEffect(() => {
- const isFree = subs?.plan?.name.toLowerCase() === 'smythos free';
- const parentTeamInitiator = userInfo?.user?.roles?.find(
- (role) => role?.sharedTeamRole?.team?.id === parentTeam?.id,
- )?.isTeamInitiator;
-
- // Show limit card for all paid plans (including Enterprise) when user is team initiator
- setShowLimitCard(parentTeamInitiator && subs?.plan?.paid && !isFree);
- }, [userInfo, subs, parentTeam]);
-
- const storeTeamSettings = useStoreTeamSettings(teamSettingKeys.BILLING_LIMIT, parentTeam?.id);
-
- function CancelSubscriptionCard({ isCancelled }: CancelSubscriptionCardProps) {
- return (
- <Card className="w-full">
- <CardContent className="p-6 md:p-8">
- <div className="flex flex-col md:flex-row gap-6">
- {/* Left side - text content */}
- <div className="flex-1 min-w-0">
- <h2 className="text-xl md:text-2xl font-semibold text-foreground mb-4">
- Cancel Subscription
- </h2>
- <p className="text-muted-foreground text-sm md:text-base leading-relaxed">
- {isCancelled
- ? 'Your subscription has been successfully canceled and will remain active until the end of your current billing cycle. You may subscribe again at any time.'
- : 'Canceling your subscription will automatically downgrade your account to our free plan. Upon cancellation, your subscription will remain active until the end of your current billing cycle. This action is irreversible, but you may subscribe again at any time.'}
- </p>
- </div>
-
- {/* Right side - buttons */}
- <div className="flex flex-col lg:flex-row gap-3 shrink-0 items-center">
- {isReadOnlyAccess ? (
- <Tooltip content="You do not have permission to cancel a subscription.">
- <div>
- <CustomButton
- variant="secondary"
- handleClick={() => handleUnsubscribe('cancel')}
- disabled={isCancelled || isReadOnlyAccess}
- addIcon={loadingCancelPlan}
- Icon={<Loader2 className="mr-2 h-4 w-4 animate-spin" />}
- label={loadingCancelPlan ? 'Canceling...' : 'Cancel Subscription'}
- />
- </div>
- </Tooltip>
- ) : (
- <CustomButton
- variant="secondary"
- handleClick={() => handleUnsubscribe('cancel')}
- disabled={isCancelled || isReadOnlyAccess}
- addIcon={loadingCancelPlan}
- Icon={<Loader2 className="mr-2 h-4 w-4 animate-spin" />}
- label={loadingCancelPlan ? 'Canceling...' : 'Cancel Subscription'}
- />
- )}
- {isCancelled && hasWriteAccess && (
- <CustomButton
- handleClick={() => handleUnsubscribe('restart')}
- variant="primary"
- disabled={loadingRestartPlan}
- addIcon={loadingRestartPlan}
- Icon={<Loader2 className="mr-2 h-4 w-4 animate-spin" />}
- label={'Resubscribe'}
- />
- )}
- </div>
- </div>
- </CardContent>
- </Card>
- );
- }
-
- function DataPoolCard() {
- return (
- <Card className="h-full flex flex-col">
- <CardHeader className="pb-2">
- <CardTitle className="text-base">Data Pool Usage</CardTitle>
- </CardHeader>
- <CardContent className="flex-1">
- <div className="h-full flex flex-col justify-center">
- {subs.plan.name !== 'SmythOS Free' ? (
- <div className="flex flex-col gap-0" data-qa="data-pool-usage">
- <span className="text-2xl font-bold">
- {isValid(usage?.dataPools?.usedSize)
- ? getFormattedNumber(usage?.dataPools?.usedSize)
- : '0'}{' '}
- {usage?.dataPools?.unit || 'GB'}
- </span>
- {subs?.plan?.paid && (
- <span className="text-muted-foreground text-sm">
- of{' '}
- {isValid(subs?.plan?.properties?.limits?.dataPoolUsageGB)
- ? `${getFormattedNumber(
- subs?.plan?.properties?.limits?.dataPoolUsageGB,
- )} ${'GB'}`
- : 'Unlimited'}
- </span>
- )}
- </div>
- ) : (
- <div className="flex flex-col gap-10">
- <div className="text-gray-500">
- {isReadOnlyAccess ? (
- <Tooltip content="You do not have permission to upgrade the plan">
- <span
- className="cursor-pointer text-[#3C89F9] underline"
- onClick={() => handleUpgrade()}
- >
- Upgrade
- </span>
- </Tooltip>
- ) : (
- <span
- className="cursor-pointer text-[#3C89F9] underline"
- onClick={() => handleUpgrade()}
- >
- Upgrade
- </span>
- )}{' '}
- to access data pool
- </div>
- </div>
- )}
- </div>
- </CardContent>
- </Card>
- );
- }
- function BannerCard() {
- function GetCustomButton() {
- return (
- <CustomButton
- handleClick={handleUpgrade}
- disabled={isReadOnlyAccess || loadingUpgrade}
- variant="primary"
- >
- {loadingUpgrade ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin " />
- <span>
- {subs?.plan?.name === 'SmythOS Free'
- ? 'Upgrading...'
- : subs?.plan?.isCustomPlan || ENTERPRISE_PLAN_NAMES.includes(subs?.plan?.name)
- ? 'Managing...'
- : 'Changing...'}
- </span>
- </>
- ) : subs?.plan?.name === 'SmythOS Free' ? (
- 'Upgrade Plan'
- ) : subs?.plan?.isCustomPlan || ENTERPRISE_PLAN_NAMES.includes(subs?.plan?.name) ? (
- 'Manage Plan'
- ) : (
- 'Change Plan'
- )}
- </CustomButton>
- );
- }
-
- function RenderButton({ className }: { className: string }) {
- return (
- <div className={className}>
- {isReadOnlyAccess ? (
- <Tooltip content="You do not have permission to change the subscription plan.">
- <div>{GetCustomButton()}</div>
- </Tooltip>
- ) : subs?.object?.cancel_at_period_end && hasWriteAccess ? (
- <Tooltip
- content="You have requested to cancel the subscription. Please re-subscribe to change the plan."
- className="w-[200px]"
- >
- <div className="opacity-50 pointer-events-none">{GetCustomButton()}</div>
- </Tooltip>
- ) : (
- GetCustomButton()
- )}
- </div>
- );
- }
- return (
- <Card className="">
- <CardHeader className="border-b bg-v2-blue/5 p-6">
- <div className="flex items-center justify-between">
- <div>
- <CardTitle className="text-2xl font-bold">Plan Summary</CardTitle>
- <CardDescription className="text-base mt-1" data-qa="current-plan-text">{`${
- subs?.plan?.name
- } ${userDisplayName ? '- ' + userDisplayName : ''}`}</CardDescription>
- </div>
- {RenderButton({ className: 'hidden md:block' })}
- </div>
- </CardHeader>
- <CardContent className="p-6">
- <p className="text-muted-foreground">
- {subs?.plan?.isCustomPlan ? (
- <>
- You are on a custom plan. Contact your account manager or{' '}
- <a
- href="https://smythos.com/contact-us/"
- target="_blank"
- rel="noopener noreferrer"
- className="text-[#3C89F9] hover:underline"
- >
- support
- </a>{' '}
- for any changes or inquiries.
- </>
- ) : ENTERPRISE_PLAN_NAMES.includes(subs?.plan?.name) ? (
- <>
- You are currently subscribed to an Enterprise plan. Contact your account manager or{' '}
- <a
- href="https://smythos.com/contact-us/"
- target="_blank"
- rel="noopener noreferrer"
- className="text-[#3C89F9] hover:underline"
- >
- support
- </a>{' '}
- for any changes or inquiries.
- </>
- ) : subs?.plan?.name === 'Scaleup' ? (
- <>
- You&apos;re on the Scaleup plan, which provides powerful features and high usage
- limits. If you need even more capabilities or customized solutions,{' '}
- <a
- href="https://smythos.com/contact-us/"
- target="_blank"
- rel="noopener noreferrer"
- className="text-[#3C89F9] hover:underline"
- >
- contact us
- </a>{' '}
- to explore enterprise solutions.
- </>
- ) : subs?.plan?.name === 'Builder' || subs?.plan?.name === 'Startup' ? (
- <>
- You&apos;re on the {subs?.plan?.name} plan, which offers robust features and higher
- limits on core tools. If you need additional capabilities, explore our Scaleup plan
- for rapid-growth teams.
- </>
- ) : (
- `You are currently subscribed to a ${subs?.plan?.name} plan. Please upgrade to unlock more features.`
- )}
- </p>
- </CardContent>
- <CardFooter>{RenderButton({ className: 'block md:hidden' })}</CardFooter>
- </Card>
- );
- }
- function ModelUsageCard() {
- return (
- <Card>
- <CardHeader className="pb-2 pt-6">
- <CardTitle className="text-base">Model Use</CardTitle>
- </CardHeader>
- <CardContent className="space-y-2">
- {totalModelUsage >= freeCredits ? (
- <div className="flex flex-col pt-2">
- <div className="flex items-baseline gap-1" data-qa="model-use-total">
- <span className="text-2xl font-bold">${totalModelUsage}</span>
- </div>
- <div className="flex items-baseline gap-1">
- <span className="text-sm text-primary-pink">
- You&apos;ve reached your credit limit. Credits will renew each billing period.
- </span>
- </div>
- </div>
- ) : (
- <>
- <div className="flex flex-col pt-2">
- <div data-qa="model-use-total">
- <span className="text-2xl font-bold">${totalModelUsage} </span>
- <span className="text-sm text-muted-foreground">
- of ${modelLimit} in free credits
- </span>
- </div>
- <div>
- <span className="text-sm text-muted-foreground mt-4">
- Credits will renew each billing period.
- </span>
- </div>
- </div>
- </>
- )}
- <a href="/analytics" className="text-xs text-[#3C89F9] hover:underline group">
- See Details{' '}
- <span className="inline-block transition-transform group-hover:translate-x-1 align-middle">
- <HiOutlineArrowRight />
- </span>
- </a>
- </CardContent>
- </Card>
- );
- }
-
- function TaskConsumedCard() {
- return (
- <SimpleCard
- title="Total Tasks Consumed"
- value={isValid(tasksUsage?.tasks?.used) ? tasksUsage.tasks.used : 0}
- />
- );
- }
- function ActiveAgentsCard() {
- return (
- <SimpleCard
- title="Active Agents"
- value={isValid(usage?.activeAgents) ? usage?.activeAgents : 0}
- dataQa="active-agents-count"
- />
- );
- }
-
- const freeList = ['ModelUsageCard', 'DataPoolCard', 'TaskConsumedCard', 'ActiveAgentsCard'];
- const paidList = [
- 'ModelUsageCard',
- 'TaskConsumedCard',
- 'BillingLimitCard',
- 'ActiveAgentsCard',
- 'DataPoolCard',
- ];
-
- // Use the stable wrapper that never re-renders
- const stableBillingComponent = (
- <StableBillingLimitWrapper
- key="stable-billing-wrapper"
- billingLimitSettings={billingLimitSettings}
- storeTeamSettings={storeTeamSettings}
- parentTeam={parentTeam}
- freeCredits={freeCredits}
- />
- );
-
- const subscriptionCards = useMemo(() => {
- return [
- {
- id: 'BillingLimitCard',
- component: () => stableBillingComponent,
- showCondition: showLimitCard && isShowLimitFeature,
- gridSpan: 'full',
- },
- {
- id: 'ModelUsageCard',
- component: ModelUsageCard,
- showCondition: showModelUsage,
- },
- {
- id: 'DataPoolCard',
- component: DataPoolCard,
- showCondition: true, // Always show
- },
- {
- id: 'TaskConsumedCard',
- component: TaskConsumedCard,
- showCondition: !showModelUsage,
- },
- {
- id: 'ActiveAgentsCard',
- component: ActiveAgentsCard,
- showCondition: true,
- },
- ];
- }, [showModelUsage, showLimitCard, isShowLimitFeature, subs, tasksUsage, usage]);
-
- const cardData = useMemo(() => {
- const shownCards = subscriptionCards.filter((card) => card.showCondition);
- if (shownCards.length <= 3) {
- return {
- count: 1,
- grid: [shownCards.length],
- };
- } else {
- return {
- count: 2,
- grid: shownCards.length === 4 ? [2, 2] : [2, 3],
- };
- }
- }, [subscriptionCards]);
-
- // Add window function to control showLimitCard
- useEffect(() => {
- (window as any).setShowLimitCard = (value: boolean) => {
- setIsShowLimitFeature(value);
- };
-
- // Cleanup function to remove the window property
- return () => {
- delete (window as any).setShowLimitCard;
- };
- }, []);
-
- return (
- <div className="w-full pb-4 md:pb-6 space-y-8 font-sans ml-8 md:mx-auto px-2 md:px-0">
- {/* Header - Always visible */}
- <div className="flex justify-between items-start gap-4 flex-wrap">
- <div className="space-y-1">
- <p className="text-muted-foreground">
- View your usage and manage your subscription settings
- </p>
- </div>
- {subscriptionPeriod && (
- <div className="bg-muted px-4 py-1.5 rounded-full text-sm">
- Current period: {subscriptionPeriod}
- </div>
- )}
- </div>
-
- {/* Content section with loading states */}
- {isLoading || !usage || !subs ? (
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
- {[1, 2, 3].map((index) => (
- <div key={index} className="p-4 border rounded-lg shadow animate-pulse">
- <div className="h-4 bg-gray-200 rounded-full dark:bg-gray-700 w-3/4 mb-4" />
- <div className="space-y-3">
- <div className="h-3 bg-gray-200 rounded-full dark:bg-gray-700 w-full" />
- <div className="h-3 bg-gray-200 rounded-full dark:bg-gray-700 w-5/6" />
- <div className="h-3 bg-gray-200 rounded-full dark:bg-gray-700 w-4/6" />
- </div>
- </div>
- ))}
- </div>
- ) : (
- <>
- <BannerCard />
- {cardData.grid.map((columnCount, rowIndex) => {
- // Get the list of card IDs to show based on plan type
- const cardList = subs.plan.paid ? paidList : freeList;
-
- // First, get all visible components
- const visibleComponents = cardList
- .map((cardName) => {
- const card = subscriptionCards.find((c) => c.id === cardName);
- return card?.showCondition ? card : null;
- })
- .filter(Boolean);
-
- // Calculate start and end indices for current row
- const startIndex =
- rowIndex === 0
- ? 0
- : cardData.grid.slice(0, rowIndex).reduce((sum, count) => sum + count, 0);
- const endIndex = startIndex + columnCount;
-
- // Then slice the visible components for the current row
- const rowComponents = visibleComponents.slice(startIndex, endIndex);
-
- return rowComponents.length > 0 ? (
- <div
- key={`row-${rowIndex}`}
- className={`grid gap-6 md:grid-cols-${columnCount} mb-8`}
- >
- {rowComponents.map((card) => (
- <card.component key={card.id} />
- ))}
- </div>
- ) : null;
- })}
- {subs?.plan?.paid && subs?.plan?.name !== 'Early Adopters' && !isCustomPlan && (
- <CancelSubscriptionCard isCancelled={subs?.object?.cancel_at_period_end || false} />
- )}
- </>
- )}
- </div>
- );
-}
diff --git a/packages/app/src/react/features/analytics/components/usage-analytics.tsx b/packages/app/src/react/features/analytics/components/usage-analytics.tsx
deleted file mode 100644
index 0eb863b9..00000000
--- a/packages/app/src/react/features/analytics/components/usage-analytics.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-import StackedBarChart from '@react/features/analytics/components/stacked-bar-chart';
-import { useAuthCtx } from '@react/shared/contexts/auth.context';
-import { Button } from '@src/react/shared/components/ui/button';
-import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@src/react/shared/components/ui/select';
-import { Spinner } from '@src/react/shared/components/ui/spinner';
-import { SMYTHOS_DOCS_URL } from '@src/shared/constants/general';
-import { ChevronLeft, ChevronRight, Download } from 'lucide-react';
-
-export default function UsageAnalytics({
- isLoading,
- allSpaces,
- selectedSpace,
- setSelectedSpace,
- allAgents,
- selectedAgent,
- setSelectedAgent,
- chartData,
- totalUsage,
- selectedMonth,
- setSelectedMonth,
- handleExport,
- showSpacesDropdown,
-}: {
- isLoading: boolean;
- allSpaces: Array<{ id: string; name: string }>;
- selectedSpace: { id: string; name: string };
- setSelectedSpace: (arg: string) => void;
- allAgents: Array<any>;
- selectedAgent: { id: string; name: string };
- setSelectedAgent: (arg: string) => void;
- chartData: any;
- totalUsage: number | null;
- selectedMonth: any;
- setSelectedMonth: (arg: number) => void;
- handleExport: () => void;
- showSpacesDropdown: boolean;
-}) {
- const {
- userInfo: { subs: userSubs },
- } = useAuthCtx();
-
- return (
- <div className="mx-auto pl-12 md:pl-0">
- <div className="rounded-lg bg-white pr-1 md:pr-0">
- <div className="flex flex-col gap-4 mb-5 lg:flex-row lg:items-center lg:justify-between">
- <h1 className="text-[24px] font-semibold text-black">Model Usage</h1>
-
- <div className="grid grid-cols-2 gap-2 lg:flex lg:flex-row">
- {showSpacesDropdown && (
- <Select
- value={selectedSpace.id}
- onValueChange={(spaceId) => setSelectedSpace(spaceId)}
- >
- <SelectTrigger className="w-full lg:w-[180px] h-[44px]">
- <SelectValue placeholder="All team spaces">{selectedSpace.name}</SelectValue>
- </SelectTrigger>
- <SelectContent>
- {allSpaces.map((space) => (
- <SelectItem key={space.id} value={space.id}>
- {space.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
-
- <Select value={selectedAgent.id} onValueChange={(agentId) => setSelectedAgent(agentId)}>
- <SelectTrigger className="w-full lg:w-[140px] h-[44px]">
- <SelectValue placeholder="All Agents">{selectedAgent.name}</SelectValue>
- </SelectTrigger>
- <SelectContent>
- {allAgents.map((agent) => (
- <SelectItem key={agent.id} value={agent.id}>
- {agent.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
- <Button
- variant="outline"
- className="flex items-center gap-1 px-3 font-normal w-full sm:w-auto h-[44px]"
- >
- <ChevronLeft
- className="h-4 w-4 text-gray-500 cursor-pointer"
- onClick={() => setSelectedMonth(-1)}
- />
- <span>
- {selectedMonth
- ? selectedMonth.toLocaleDateString('en-US', { month: 'short', year: 'numeric' })
- : 'Select Date'}
- </span>
- <ChevronRight
- className="h-4 w-4 text-gray-500 cursor-pointer"
- onClick={() => setSelectedMonth(1)}
- />
- </Button>
-
- <CustomButton
- variant="primary"
- handleClick={handleExport}
- label="Export"
- addIcon
- Icon={<Download className="h-4 w-4 mr-2" />}
- />
- </div>
- </div>
-
- {totalUsage !== null && userSubs?.plan?.properties?.flags?.modelCostMultiplier && (
- <div className="w-full lg:w-max bg-white rounded-[16px] px-5 py-4 border-[1px] border-solid border-gray-200 mb-8">
- <h2 className="text-[13px] font-normal text-[#6B7280]">Total Model Usage</h2>
- <p className="text-[32px] font-semibold text-black mt-1">${totalUsage.toFixed(5)}</p>
- </div>
- )}
-
- <div className="mb-4 bg-white rounded-[16px] px-5 py-4 border-[1px] border-solid border-gray-200">
- <h3 className="mb-4 text-sm font-medium">Daily Model Usage</h3>
- {isLoading ? (
- <div className="h-[400px] w-full flex items-center justify-center">
- <Spinner classes="w-8 h-8" />
- </div>
- ) : (
- <StackedBarChart chartData={chartData} />
- )}
- </div>
-
- <p className="text-[13px] leading-5 text-[#6B7280] mt-8">
- SmythOS provides API keys for many AI models for your convenience. When you use our
- models, you pay SmythOS instead of the AI model provider. See{' '}
- <a
- href={`${SMYTHOS_DOCS_URL}/account-management/model-rates`}
- className="underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- documentation
- </a>
- .
- <br />
- <span className="text-[#9CA3AF]">
- Whenever you bring your own API keys in the vault, cost will not be tracked here, but by
- your AI or API model provider instead.
- </span>
- </p>
- </div>
- </div>
- );
-}
diff --git a/packages/app/src/react/features/analytics/pages/AnalyticsPage.tsx b/packages/app/src/react/features/analytics/pages/AnalyticsPage.tsx
deleted file mode 100644
index ea298fae..00000000
--- a/packages/app/src/react/features/analytics/pages/AnalyticsPage.tsx
+++ /dev/null
@@ -1,723 +0,0 @@
-import { fetchLLMAndApiUsage } from '@react/features/analytics/client/usageAnalytics';
-import UsageAnalytics from '@react/features/analytics/components/usage-analytics';
-import { useEffect, useMemo, useState } from 'react';
-import { toast } from 'react-toastify';
-import { useAuthCtx } from '../../../shared/contexts/auth.context';
-
-export interface ApiData {
- usage: {
- analytics: Array<{
- teamId: string; // Unique identifier for the team
- teamName: string; // Name of the team
- data: {
- days: {
- [date: string]: {
- agents: {
- [agentId: string]: {
- sources: {
- [source: string]: {
- [metric: string]: {
- units: number;
- cost: number;
- };
- };
- };
- };
- };
- };
- };
- costs: {
- [metric: string]: number; // Total costs for the team by metric
- };
- };
- }>;
- agents: Array<{
- agents: Array<{
- id: string; // Unique identifier for the agent
- name: string; // Name of the agent
- description: string; // Description of the agent
- createdAt: string; // Creation timestamp
- updatedAt: string; // Last updated timestamp
- domain: string[]; // Associated domains
- deployed: boolean; // Deployment status
- }>;
- total: number; // Total number of agents
- }>;
- };
-}
-
-const colorsArray = ['#5C19AF', '#E65D89', '#7AA5E5', '#46CEAE', '#97DF85', '#FFEF92'];
-
-function AnalyticsPage() {
- const userContext = useAuthCtx();
- const [isLoading, setIsLoading] = useState(false);
- const [llmAndApiUsage, setLlmAndApiUsage] = useState<any>(null);
- const [selectedAgent, setSelectedAgent] = useState<{ id: string; name: string }>({
- id: 'all-agents',
- name: 'All Agents',
- });
- const [selectedSpace, setSelectedSpace] = useState<{ id: string; name: string }>({
- id: 'all-spaces',
- name: 'All Spaces',
- });
- const [selectedMonth, setSelectedMonth] = useState<Date>(new Date());
- const [dataType, setDataType] = useState<'usage' | 'tasks' | null>(null);
-
- useEffect(() => {
- const fetchData = async () => {
- setIsLoading(true);
- try {
- const data = await fetchLLMAndApiUsage(userContext?.currentUserTeam?.id, selectedMonth);
-
- let detectedType: 'usage' | 'tasks' | null = null;
-
- // Loop through data to determine if it contains sources or tasks
- if (data?.usage?.analytics) {
- for (const team of data.usage.analytics) {
- if (team.data?.days) {
- for (const day of Object.values(team.data.days) as any) {
- for (const agent of Object.values(day.agents || {}) as any) {
- if ('sources' in agent) {
- detectedType = 'usage';
- break;
- }
- if ('tasks' in agent) {
- detectedType = 'tasks';
- break;
- }
- }
- }
- }
- if (detectedType) break;
- }
- }
-
- setLlmAndApiUsage(data);
- setDataType(detectedType);
- } catch (error) {
- if (error instanceof Error) {
- toast.error(error.message);
- } else {
- toast.error('Error fetching usage data. Please try again later.');
- }
- setLlmAndApiUsage(null);
- setDataType(null);
- } finally {
- setIsLoading(false);
- }
- };
-
- fetchData();
- }, [selectedMonth]);
-
- const chartData = useMemo(() => {
- if (!llmAndApiUsage) return null;
-
- function transformData(
- apiData: ApiData,
- selectedSpace: { id: string; name: string },
- selectedAgent: { id: string; name: string },
- ) {
- if (dataType === 'usage') {
- return transformUsageDataToStackedBar(
- apiData.usage.analytics,
- selectedSpace,
- selectedAgent,
- );
- } else if (dataType === 'tasks') {
- return transformTasksDataToStackedBar(apiData, selectedSpace, selectedAgent);
- }
- }
-
- return transformData(llmAndApiUsage, selectedSpace, selectedAgent);
- }, [llmAndApiUsage, selectedSpace, selectedAgent, dataType]);
-
- const getAllAgents = useMemo(() => {
- if (!llmAndApiUsage) return [];
-
- const allAgents = (apiData: ApiData, selectedSpace: { id: string; name: string }) => {
- const agentsSet = new Set<string>();
-
- if (selectedSpace.name === 'All Spaces') {
- apiData.usage.analytics.forEach((team) => {
- // Add null check for team.data.days
- if (team.data?.days) {
- Object.values(team.data.days).forEach((day) => {
- Object.keys(day.agents || {}).forEach((agentId) => {
- agentsSet.add(agentId);
- });
- });
- }
- });
- } else {
- const team = apiData.usage.analytics.find((team) => team.teamId === selectedSpace.id);
- if (team?.data?.days) {
- Object.values(team.data.days).forEach((day) => {
- Object.keys(day.agents || {}).forEach((agentId) => {
- agentsSet.add(agentId);
- });
- });
- }
- }
-
- // Create a map of agent IDs to their names
- const agentNameMap = new Map<string, string>();
- apiData.usage.agents.forEach((agentGroup) => {
- agentGroup.agents.forEach((agent) => {
- agentNameMap.set(agent.id, agent.name);
- });
- });
-
- return [
- { id: 'all-agents', name: 'All Agents' },
- ...Array.from(agentsSet).map((agentId) => ({
- id: agentId,
- name: agentNameMap.get(agentId) || agentId, // Fallback to ID if name not found
- })),
- ];
- };
-
- return allAgents(llmAndApiUsage, selectedSpace);
- }, [llmAndApiUsage, selectedSpace]);
-
- const handleAgentChange = (agentId: string) => {
- const agent = getAllAgents.find((agent) => agent.id === agentId);
- setSelectedAgent(agent);
- };
-
- const getTotalUsage = useMemo(() => {
- if (!llmAndApiUsage) return 0;
-
- if (dataType === 'tasks') return null;
-
- const totalUsage = (
- apiData: ApiData,
- selectedSpace: { id: string | null; name: string },
- selectedAgent: { id: string | null; name: string },
- ) => {
- let totalCost = 0;
-
- if (selectedSpace.name === 'All Spaces') {
- apiData.usage.analytics.forEach((team) => {
- // Add null check for team.data.days
- if (team.data?.days) {
- Object.values(team.data.days).forEach((day) => {
- Object.entries(day.agents || {}).forEach(([agentId, agentData]) => {
- if (selectedAgent.name === 'All Agents' || agentId === selectedAgent.id) {
- Object.values(agentData.sources || {}).forEach((source) => {
- Object.values(source).forEach((metric) => {
- totalCost += metric.cost || 0;
- });
- });
- }
- });
- });
- }
- });
- } else {
- const team = apiData.usage.analytics.find((team) => team.teamId === selectedSpace.id);
- if (team?.data?.days) {
- Object.values(team.data.days).forEach((day) => {
- Object.entries(day.agents || {}).forEach(([agentId, agentData]) => {
- if (selectedAgent.name === 'All Agents' || agentId === selectedAgent.id) {
- Object.values(agentData.sources || {}).forEach((source) => {
- Object.values(source).forEach((metric) => {
- totalCost += metric.cost || 0;
- });
- });
- }
- });
- });
- }
- }
-
- return totalCost;
- };
-
- return totalUsage(llmAndApiUsage, selectedSpace, selectedAgent);
- }, [llmAndApiUsage, selectedSpace, selectedAgent]);
-
- const getAllSpaces = useMemo(() => {
- if (!llmAndApiUsage) return [];
-
- const allSpaces = (apiData: ApiData) => {
- return [
- { id: 'all-spaces', name: 'All Spaces' },
- ...apiData.usage.analytics.map((team) => ({
- id: team.teamId,
- name: team.teamName,
- })),
- ];
- };
-
- return allSpaces(llmAndApiUsage);
- }, [llmAndApiUsage]);
-
- const handleSpaceChange = (spaceId: string) => {
- const space = getAllSpaces.find((space) => space.id === spaceId);
- setSelectedSpace(space);
- setSelectedAgent({ id: 'all-agents', name: 'All Agents' });
- };
-
- const handleMonthChange = (increment: number) => {
- if (isLoading) return;
-
- setSelectedMonth((currentDate) => {
- if (!currentDate) return new Date();
- const newDate = new Date(currentDate);
- newDate.setMonth(newDate.getMonth() + increment);
- return newDate;
- });
- setSelectedAgent({ id: 'all-agents', name: 'All Agents' });
- setSelectedSpace({ id: 'all-spaces', name: 'All Spaces' });
- };
-
- function exportToCSV(chartData, dataType) {
- if (!chartData) {
- console.warn('No chartData provided');
- return;
- }
-
- // 1) If dataType === 'usage', do the 5-column export
- if (dataType === 'usage') {
- // Check that we have a breakdown
- if (!chartData.labels?.length || !chartData.breakdown) {
- console.warn('No valid usage data to export');
- return;
- }
-
- const rows = [];
- const labelsSorted = [...chartData.labels];
-
- // Sort the day labels chronologically by parsing them
- labelsSorted.sort((a, b) => {
- const dA: any = new Date(`${a}, ${new Date().getFullYear()}`);
- const dB: any = new Date(`${b}, ${new Date().getFullYear()}`);
- return dA - dB;
- });
-
- // Build rows from breakdown
- for (const dayLabel of labelsSorted) {
- const categoryObj = chartData.breakdown[dayLabel] || {};
- for (const category of Object.keys(categoryObj)) {
- const childArr = categoryObj[category] || [];
- if (!childArr.length) {
- // skip if no sub-items
- continue;
- }
- for (const child of childArr) {
- rows.push({
- date: dayLabel,
- source: category, // e.g. "LLM", "Tasks", ...
- subCategory: child.name, // e.g. "llm:bard" or "smyth"
- units: child.units ?? 0,
- costs: child.cost ? child.cost.toFixed(5) : 0,
- });
- }
- }
- }
-
- if (!rows.length) {
- console.warn('No nonzero usage data to export');
- return;
- }
-
- // Build CSV
- const headers = ['Date', 'Source', 'Sub-Category', 'Units', 'Costs'];
- const csvLines = [headers.join(',')];
- for (const row of rows) {
- csvLines.push(`${row.date},${row.source},${row.subCategory},${row.units},${row.costs}`);
- }
- const csvContent = csvLines.join('\n');
- downloadCSV(csvContent, 'usage_analytics');
-
- // 2) If dataType === 'tasks', do the simpler 2-column export
- } else if (dataType === 'tasks') {
- // Check we have labels/datasets
- if (!chartData.labels?.length || !chartData.datasets?.length) {
- console.warn('No valid tasks data to export');
- return;
- }
-
- const csvRows = [];
- // Sort the day labels
- const sortedDateIndices = chartData.labels
- .map((date, index) => ({ date, index }))
- .sort((a, b) => {
- const dA: any = new Date(`${a.date}, ${new Date().getFullYear()}`);
- const dB: any = new Date(`${b.date}, ${new Date().getFullYear()}`);
- return dA - dB;
- });
-
- // For tasks, we typically have just 1 dataset: "Tasks"
- // But if you have multiple datasets, we can gather them all
- sortedDateIndices.forEach(({ date, index }) => {
- chartData.datasets.forEach((dataset) => {
- const taskValue = dataset.data[index] || 0;
- if (taskValue !== 0) {
- csvRows.push({
- date,
- tasks: taskValue,
- });
- }
- });
- });
-
- if (!csvRows.length) {
- console.warn('No valid tasks data to export');
- return;
- }
-
- const headers = ['Date', 'Tasks'];
- const csvLines = [headers.join(',')];
- for (const row of csvRows) {
- csvLines.push(`${row.date},${row.tasks}`);
- }
- const csvContent = csvLines.join('\n');
- downloadCSV(csvContent, 'tasks_analytics');
- } else {
- // If dataType is something else
- console.warn('Unknown dataType:', dataType);
- }
- }
-
- /**
- * Helper: downloadCSV(csvContent, filePrefix)
- * Creates a Blob from the CSV text and triggers a browser download
- */
- function downloadCSV(csvContent, filePrefix) {
- const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
- const url = URL.createObjectURL(blob);
- const link = document.createElement('a');
- link.setAttribute('href', url);
- const dateStr = new Date().toISOString().split('T')[0];
- link.setAttribute('download', `${filePrefix}_${dateStr}.csv`);
- link.style.visibility = 'hidden';
-
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- }
-
- const handleExport = () => {
- const hasNoData =
- !chartData?.datasets?.length || chartData.datasets.every((dataset) => !dataset.data?.length);
-
- if (!hasNoData) {
- exportToCSV(chartData, dataType);
- } else {
- toast.info('No data to export');
- }
- };
-
- function transformUsageDataToStackedBar(apiData, selectedSpace, selectedAgent) {
- // apiData => e.g. llmAndApiUsage.usage.analytics
- // If there's nothing to parse, return empty
- if (!apiData || !apiData.length) {
- return {
- labels: [],
- datasets: [],
- breakdown: {},
- };
- }
-
- //
- // 1) Identify all days that appear in the raw data,
- // but only for teams that match selectedSpace
- //
- const daySet = new Set();
- for (const team of apiData) {
- // Check space
- if (selectedSpace.name !== 'All Spaces' && team.teamId !== selectedSpace.id) {
- continue; // skip
- }
-
- const daysObj = team?.data?.days || {};
- for (const dayStr of Object.keys(daysObj)) {
- daySet.add(dayStr);
- }
- }
-
- if (daySet.size === 0) {
- return {
- labels: [],
- datasets: [],
- breakdown: {},
- };
- }
-
- //
- // 2) Sort all days, fill in from earliest to latest
- //
- function parseDayStr(dayStr) {
- return new Date(`${dayStr}, ${new Date().getFullYear()}`);
- }
-
- const sortedDayStrings = [...daySet].sort(
- (a, b) => parseDayStr(a).getTime() - parseDayStr(b).getTime(),
- );
- const startDate = parseDayStr(sortedDayStrings[0]);
- const endDate = parseDayStr(sortedDayStrings[sortedDayStrings.length - 1]);
-
- function formatDay(dateObj) {
- return dateObj.toLocaleString('en-US', { month: 'short', day: 'numeric' });
- }
-
- const allDayLabels = [];
- for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
- allDayLabels.push(formatDay(d));
- }
-
- //
- // 3) Decide on the categories (bottom -> top) + color map
- //
- const categoryOrder = ['Image Generation', 'Code', 'Tools', 'LLM', 'Weaver', 'Tasks'];
-
- const colorMap = {
- Tasks: '#FFEF92',
- Weaver: '#97DF85',
- LLM: '#46CEAE',
- Tools: '#7AA5E5',
- Code: '#E65D89',
- 'Image Generation': '#8840E1',
- };
-
- //
- // 4) Prepare dayCategoryData for accumulation
- // dayCategoryData[dayLabel][category] = { totalUnits, aggregator: {}, children: [] }
- //
- const dayCategoryData = {};
- for (const dayLabel of allDayLabels) {
- dayCategoryData[dayLabel] = {};
- for (const cat of categoryOrder) {
- dayCategoryData[dayLabel][cat] = {
- totalUnits: 0,
- aggregator: {},
- children: [],
- };
- }
- }
-
- // Helper function that maps (sourceKey, subKey) -> one of our 6 categories
- function getCategory(sourceKey, subKey) {
- if (sourceKey.startsWith('api:imagegen')) {
- return 'Image Generation';
- } else if (['api:serverless_code.smyth'].includes(sourceKey)) {
- return 'Code';
- } else if (sourceKey.startsWith('api:')) {
- return 'Tools';
- } else if (sourceKey.startsWith('llm:')) {
- return 'LLM';
- } else if (sourceKey === 'smyth') {
- if (subKey === 'task') return 'Tasks';
- if (subKey.startsWith('weaver')) return 'Weaver';
- return 'Tools';
- }
- return 'Tools';
- }
-
- //
- // 5) Accumulate usage from teams that match the selectedSpace,
- // and agents that match the selectedAgent
- //
- for (const team of apiData) {
- // Skip if not the chosen space
- if (selectedSpace.name !== 'All Spaces' && team.teamId !== selectedSpace.id) {
- continue;
- }
-
- const daysObj = team?.data?.days || {};
- for (const rawDayStr of Object.keys(daysObj)) {
- const agentsObj = daysObj[rawDayStr]?.agents || {};
- const dayLabel = formatDay(parseDayStr(rawDayStr));
-
- // If dayLabel not in range, create a new entry
- if (!dayCategoryData[dayLabel]) {
- dayCategoryData[dayLabel] = {};
- for (const cat of categoryOrder) {
- dayCategoryData[dayLabel][cat] = {
- totalUnits: 0,
- aggregator: {},
- children: [],
- };
- }
- }
-
- // For each agent
- for (const agentId of Object.keys(agentsObj)) {
- // Skip if not the chosen agent
- if (selectedAgent.name !== 'All Agents' && agentId !== selectedAgent.id) {
- continue;
- }
-
- const sourcesObj = agentsObj[agentId]?.sources || {};
- // e.g. {"llm:gpt-4o": {"tok-in": {...}, "tok-out": {...}}}
- for (const sourceKey of Object.keys(sourcesObj)) {
- const subObj = sourcesObj[sourceKey];
- for (const subKey of Object.keys(subObj)) {
- const usage = subObj[subKey] || {};
- const units = usage.units || 0;
- const cost = usage.cost || 0;
-
- const cat = getCategory(sourceKey, subKey);
-
- // Increase total units for this category
- dayCategoryData[dayLabel][cat].totalUnits += units;
-
- // aggregator => group by the sourceKey
- if (!dayCategoryData[dayLabel][cat].aggregator[sourceKey]) {
- dayCategoryData[dayLabel][cat].aggregator[sourceKey] = {
- units: 0,
- cost: 0,
- };
- }
- dayCategoryData[dayLabel][cat].aggregator[sourceKey].units += units;
- dayCategoryData[dayLabel][cat].aggregator[sourceKey].cost += cost;
- }
- }
- }
- }
- }
-
- //
- // 6) Convert aggregator -> children arrays
- //
- for (const dayLabel of allDayLabels) {
- for (const cat of categoryOrder) {
- const agg = dayCategoryData[dayLabel][cat].aggregator;
- let childrenArr = Object.keys(agg).map((sourceKey) => ({
- name: sourceKey,
- units: agg[sourceKey].units,
- cost: agg[sourceKey].cost,
- }));
-
- // Special handling for Image Generation category to combine api:imagegen entries
- if (cat === 'Image Generation') {
- const imageGenEntries = childrenArr.filter((entry) =>
- entry.name.startsWith('api:imagegen'),
- );
- const otherEntries = childrenArr.filter(
- (entry) => !entry.name.startsWith('api:imagegen'),
- );
-
- if (imageGenEntries.length > 0) {
- const combinedImageGen = {
- name: 'api:imagegen',
- units: imageGenEntries.reduce((sum, entry) => sum + entry.units, 0),
- cost: imageGenEntries.reduce((sum, entry) => sum + entry.cost, 0),
- };
- childrenArr = [...otherEntries, combinedImageGen];
- }
- }
-
- dayCategoryData[dayLabel][cat].children = childrenArr;
- }
- }
-
- //
- // 7) Build final datasets in the correct order with the correct colors
- //
- const datasets = categoryOrder.map((cat) => ({
- label: cat,
- data: allDayLabels.map((lbl) => dayCategoryData[lbl][cat].totalUnits),
- backgroundColor: colorMap[cat] || '#CCCCCC',
- }));
-
- //
- // 8) Build a "breakdown" object for advanced tooltip usage
- //
- const breakdown = {};
- for (const dayLabel of allDayLabels) {
- breakdown[dayLabel] = {};
- for (const cat of categoryOrder) {
- breakdown[dayLabel][cat] = dayCategoryData[dayLabel][cat].children;
- }
- }
-
- // 9) Return the final chart data
- return {
- labels: allDayLabels,
- datasets,
- breakdown,
- };
- }
-
- function transformTasksDataToStackedBar(apiData, selectedSpace, selectedAgent) {
- const transformed: any = {
- labels: [],
- datasets: [],
- };
-
- // 1) Build a map from "Tasks" -> [ array of daily sums ]
- // We only have one dataset, "Tasks".
- const taskMap = new Map<string, number[]>();
-
- // 2) Collect all unique labels (days)
- const allDays = new Set<string>();
- for (const team of apiData.usage.analytics) {
- if (!team.data?.days) continue;
- Object.keys(team.data.days).forEach((day) => allDays.add(day));
- }
-
- // Sort the day labels so they're in ascending order
- transformed.labels = Array.from(allDays).sort();
-
- // 3) Populate the sums
- for (const team of apiData.usage.analytics) {
- // Skip spaces that aren't selected (unless "All Spaces")
- if (selectedSpace.name !== 'All Spaces' && team.teamId !== selectedSpace.id) continue;
- if (!team.data?.days) continue;
-
- for (const [day, dayData] of Object.entries(team.data.days || {}) as any) {
- const agents = dayData.agents || {};
- for (const [agentId, agent] of Object.entries(agents) as any) {
- // Skip agents that aren't selected (unless "All Agents")
- if (selectedAgent.name !== 'All Agents' && agentId !== selectedAgent.id) continue;
-
- if ('tasks' in agent) {
- // If we haven't created the array for "Tasks" yet, do so
- if (!taskMap.has('Tasks')) {
- taskMap.set('Tasks', Array(transformed.labels.length).fill(0));
- }
- const taskArray = taskMap.get('Tasks');
- const dayIndex = transformed.labels.indexOf(day);
- if (dayIndex >= 0) {
- taskArray[dayIndex] += agent.tasks || 0;
- }
- }
- }
- }
- }
-
- // 4) Convert taskMap to final datasets
- for (const [taskLabel, taskData] of taskMap.entries()) {
- transformed.datasets.push({
- label: taskLabel,
- data: taskData.map((value) => value || 0),
- backgroundColor: '#FFEF92', // your color for tasks
- });
- }
-
- return transformed;
- }
-
- return (
- <UsageAnalytics
- isLoading={isLoading}
- allSpaces={getAllSpaces}
- selectedSpace={selectedSpace}
- setSelectedSpace={handleSpaceChange}
- allAgents={getAllAgents}
- selectedAgent={selectedAgent}
- setSelectedAgent={handleAgentChange}
- totalUsage={getTotalUsage}
- chartData={chartData} // Call the function to get the transformed data
- selectedMonth={selectedMonth}
- setSelectedMonth={handleMonthChange}
- handleExport={handleExport}
- showSpacesDropdown={userContext?.currentUserTeam?.parentId === null}
- />
- );
-}
-
-export default AnalyticsPage;
diff --git a/packages/app/src/react/features/subscriptions/pages/MyPlanPage.tsx b/packages/app/src/react/features/subscriptions/pages/MyPlanPage.tsx
deleted file mode 100644
index 52a4f4c8..00000000
--- a/packages/app/src/react/features/subscriptions/pages/MyPlanPage.tsx
+++ /dev/null
@@ -1,176 +0,0 @@
-import SubscriptionAnalytics from '@src/react/features/analytics/components/subscription-analytics'; // Import the Child component
-import {
- fetchTeamFeaturesQuota,
- fetchUsage,
- generateBillingPortalSession,
-} from '@src/react/features/subscriptions/client/myPlanPage';
-import { useAuthCtx } from '@src/react/shared/contexts/auth.context';
-import { extractError } from '@src/react/shared/utils/errors';
-import { convertToGB, formatNumber } from '@src/react/shared/utils/format';
-import { Analytics } from '@src/shared/posthog/services/analytics';
-import { useEffect, useMemo, useState } from 'react';
-import { toast } from 'react-toastify';
-
-/**
- * Checks if a subscription plan is a custom plan
- * @param plan - The subscription plan object
- * @returns boolean indicating if it's a custom plan
- */
-const isCustomPlan = (plan: { isCustomPlan?: boolean; stripeId?: string }): boolean => {
- return !!plan?.isCustomPlan && (!plan?.stripeId || plan?.stripeId === 'no_id');
-};
-
-interface Usage {
- tasks?: {
- used: number;
- };
- dataPools?: {
- usedSize: number;
- unit: string;
- };
- activeAgents?: number;
-}
-
-const MyPlanPage = () => {
- const [isLoading, setIsLoading] = useState<boolean>(true);
- const [loadingCancelPlan, setLoadingCancelPlan] = useState<boolean>(false);
- const [loadingRestartPlan, setLoadingRestartPlan] = useState<boolean>(false);
- const [dataPoolUsage, setDataPoolUsage] = useState<Usage | null>(null);
- const [tasksUsage, setTasksUsage] = useState<any>(null);
- const { userInfo } = useAuthCtx();
-
- const {
- userInfo: { user, subs: userSubs },
- hasReadOnlyPageAccess,
- getPageAccess,
- } = useAuthCtx();
-
- const userDisplayName = user?.name || userInfo?.userOnBoarding?.name || user?.email || '';
- const isOwner = useMemo(() => {
- return user?.userTeamRole?.isTeamInitiator || false;
- }, [user?.userTeamRole]);
- const isReadOnlyAccess = !isOwner || hasReadOnlyPageAccess('/my-plan', true);
- const hasWriteAccess = isOwner && getPageAccess('/my-plan', true)?.write;
-
- const [loadingUpgrade, setLoadingUpgrade] = useState<boolean>(false);
- const [dataPoolProgress, setDataPoolProgress] = useState<number>(0);
-
- useEffect(() => {
- if (userSubs) {
- Analytics.track('my_plan_page_visited', { planName: userSubs?.plan?.name });
- }
- }, [userSubs]);
-
- useEffect(() => {
- const fetchData = async () => {
- try {
- setIsLoading(true);
- const [teamFeaturesQuota, { usage: tasksUsage }] = await Promise.all([
- fetchTeamFeaturesQuota(),
- fetchUsage(),
- ]);
-
- if (tasksUsage) {
- setTasksUsage(tasksUsage);
- }
-
- if (teamFeaturesQuota) {
- const { usage: teamFeaturesUsage } = teamFeaturesQuota;
- setDataPoolUsage(teamFeaturesUsage);
- const dataPoolUsage = teamFeaturesUsage.dataPools?.usedSize ?? 0;
- const dataPoolLimit = userSubs?.plan?.properties?.limits?.dataPoolUsageGB ?? 0;
- const activeAgents = teamFeaturesUsage.activeAgents;
-
- let progress = 0;
- if (dataPoolLimit > 0 && dataPoolUsage > 0) {
- const dataPoolUsageInGB = convertToGB(dataPoolUsage, teamFeaturesUsage.dataPools?.unit);
- // Ensure progress doesn't exceed 100%
- progress = Math.min(Math.ceil((dataPoolUsageInGB / dataPoolLimit) * 100), 100);
- }
- setDataPoolProgress(progress);
- }
- } catch (error) {
- console.error('Error fetching team features:', error);
- toast.error(extractError(error) || 'Failed to load subscription data');
- } finally {
- setIsLoading(false);
- }
- };
-
- if (user?.id && userSubs) {
- fetchData();
- }
- }, [user?.id, userSubs]);
-
- const handleUnsubscribe = async (type: 'cancel' | 'restart') => {
- if (isReadOnlyAccess) return;
-
- try {
- // Set loading state before the API call
- if (type === 'cancel') {
- setLoadingCancelPlan(true);
- } else {
- setLoadingRestartPlan(true);
- }
-
- const { sessionUrl } = await generateBillingPortalSession();
-
- // Only redirect if we get a valid session URL
- if (sessionUrl) {
- window.location.href = sessionUrl;
- } else {
- throw new Error('No session URL returned');
- }
- } catch (error) {
- toast.error(extractError(error) || 'Something went wrong. Please try again.');
- // Reset loading state on error
- if (type === 'cancel') {
- setLoadingCancelPlan(false);
- } else {
- setLoadingRestartPlan(false);
- }
- }
- };
-
- const handleUpgrade = async () => {
- if (isReadOnlyAccess) return;
-
- try {
- setLoadingUpgrade(true);
- const redirectUrl = '/plans';
-
- // Add a small delay to show loading state
- await new Promise((resolve) => setTimeout(resolve, 3000));
- window.location.href = redirectUrl;
-
- // Note: The following line won't execute due to the redirect
- setLoadingUpgrade(false);
- } catch {
- setLoadingUpgrade(false);
- toast.error('Failed to redirect to plans page');
- }
- };
-
- const customPlanStatus = useMemo(() => isCustomPlan(userSubs?.plan || {}), [userSubs]);
-
- return (
- <SubscriptionAnalytics
- isLoading={isLoading}
- loadingCancelPlan={loadingCancelPlan}
- loadingRestartPlan={loadingRestartPlan}
- loadingUpgrade={loadingUpgrade}
- usage={dataPoolUsage}
- tasksUsage={tasksUsage}
- subs={userSubs}
- handleUnsubscribe={handleUnsubscribe}
- handleUpgrade={handleUpgrade}
- isReadOnlyAccess={isReadOnlyAccess}
- hasWriteAccess={hasWriteAccess}
- isCustomPlan={customPlanStatus}
- getFormattedNumber={formatNumber}
- userDisplayName={userDisplayName}
- />
- );
-};
-
-export default MyPlanPage;
diff --git a/packages/app/src/react/shared/constants/navigation.ts b/packages/app/src/react/shared/constants/navigation.ts
index ec773102..3810546e 100644
--- a/packages/app/src/react/shared/constants/navigation.ts
+++ b/packages/app/src/react/shared/constants/navigation.ts
@@ -1,13 +1,6 @@
import { plugins, PluginTarget, PluginType } from '@src/react/shared/plugins/Plugins';
import { SMYTHOS_DOCS_URL } from '@src/shared/constants/general';
-import {
- BookIcon,
- DiscordIcon,
- GridIcon,
- HomeIcon,
- KeyIcon,
- LineChartIcon,
-} from '../components/svgs';
+import { BookIcon, DiscordIcon, GridIcon, HomeIcon, KeyIcon } from '../components/svgs';
export const PRICING_PLAN_REDIRECT = 'https://smythos.com/pricing/';
@@ -30,7 +23,6 @@ export const getSidebarMenuItems = (): SidebarMenuItem[] => {
return [
{ url: '/agents', name: 'Home', icon: HomeIcon, visible: true, order: 1 },
- { url: '/analytics', name: 'Analytics', icon: LineChartIcon, visible: true, order: 4 },
{ url: '/vault', name: 'Vault', icon: KeyIcon, visible: true, order: 5 },
{ url: '/templates', name: 'Templates', icon: GridIcon, visible: true, order: 6 },
...pluginItems,
@@ -59,6 +51,5 @@ export const profileDropdownItems = () => {
// { url: '/teams/members', name: 'User Management' },
...pluginItems,
{ url: '/teams/settings', name: 'User Management' },
- { url: '/my-plan', name: 'My Plan' },
];
};