Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

4.6 KB
Raw Blame
import { SeekPage } from '@activepieces/core-utils';
import { ProjectCreditUsage } from '@activepieces/shared';
import { ColumnDef } from '@tanstack/react-table';
import dayjs from 'dayjs';
import { t } from 'i18next';
import { Coins } from 'lucide-react';
import { useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';

import {
  CURSOR_QUERY_PARAM,
  DataTable,
  LIMIT_QUERY_PARAM,
  RowDataWithActions,
} from '@/components/custom/data-table';
import { DateTimePickerWithRange } from '@/components/custom/date-time-picker-range';
import { TextWithTooltip } from '@/components/custom/text-with-tooltip';
import { billingQueries } from '@/features/billing';
import { projectCollectionUtils } from '@/features/projects';
import { authenticationSession } from '@/lib/authentication-session';

export function ProjectsUsageTable({
  platformId,
  enabled = true,
  frameClassName,
}: {
  platformId: string;
  enabled?: boolean;
  frameClassName?: string;
}) {
  const [range, setRange] = useState<{ from: Date; to: Date }>(() => ({
    from: dayjs().subtract(30, 'day').startOf('day').toDate(),
    to: dayjs().endOf('day').toDate(),
  }));
  const [searchParams] = useSearchParams();
  const cursor = searchParams.get(CURSOR_QUERY_PARAM) ?? undefined;
  const limit = searchParams.get(LIMIT_QUERY_PARAM);

  const { data, isLoading, isError, refetch } = billingQueries.useProjectsUsage(
    platformId,
    {
      startDate: range.from.toISOString(),
      endDate: range.to.toISOString(),
      cursor,
      limit: limit ? parseInt(limit) : undefined,
    },
    enabled,
  );

  const page: SeekPage<ProjectUsageRow> | undefined = data
    ? { ...data, data: data.data.map((row) => ({ ...row, id: row.projectId })) }
    : undefined;

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-wrap items-end justify-between gap-x-4 gap-y-2">
        <h2 className="text-base font-semibold text-gray-12">
          {t('Credits Usage by Project')}
        </h2>
        <DateTimePickerWithRange
          presetType="past"
          from={range.from.toISOString()}
          to={range.to.toISOString()}
          onChange={(selected) => {
            if (selected?.from && selected?.to) {
              setRange({ from: selected.from, to: selected.to });
            }
          }}
        />
      </div>
      <DataTable
        bordered={frameClassName !== undefined}
        frameClassName={frameClassName}
        columns={COLUMNS}
        page={page}
        isLoading={isLoading}
        isError={isError}
        errorStateEntity={t('project usage')}
        onRetry={refetch}
        emptyStateIcon={<Coins className="size-14 text-gray-11" />}
        emptyStateTextTitle={t('No project usage yet')}
        emptyStateTextDescription={t(
          'Once your projects consume credits, their usage will appear here.',
        )}
      />
    </div>
  );
}

function ProjectNameLink({
  projectId,
  projectName,
}: {
  projectId: string;
  projectName: string;
}) {
  const navigate = useNavigate();
  const goToProjectHome = () => {
    projectCollectionUtils.setCurrentProject(projectId);
    navigate(authenticationSession.appendProjectRoutePrefix('/automations'));
  };
  return (
    <TextWithTooltip tooltipMessage={projectName}>
      <button
        type="button"
        onClick={goToProjectHome}
        className="truncate text-sm font-medium text-accent-11 hover:underline"
      >
        {projectName}
      </button>
    </TextWithTooltip>
  );
}

const COLUMNS: ColumnDef<RowDataWithActions<ProjectUsageRow>, unknown>[] = [
  {
    accessorKey: 'projectName',
    header: () => <span className="text-sm">{t('Project')}</span>,
    cell: ({ row }) => (
      <ProjectNameLink
        projectId={row.original.projectId}
        projectName={row.original.projectName}
      />
    ),
  },
  {
    accessorKey: 'aiCreditsUsed',
    header: () => <span className="text-sm">{t('AI Usage')}</span>,
    cell: ({ row }) => (
      <span className="text-sm">
        {Math.round(row.original.aiCreditsUsed).toLocaleString()}
      </span>
    ),
  },
  {
    id: 'runsCreditsUsed',
    header: () => <span className="text-sm">{t('Runs Usage')}</span>,
    cell: ({ row }) => (
      <span className="text-sm">
        {Math.round(
          Math.max(0, row.original.creditsUsed - row.original.aiCreditsUsed),
        ).toLocaleString()}
      </span>
    ),
  },
  {
    accessorKey: 'creditsUsed',
    header: () => <span className="text-sm">{t('Total')}</span>,
    cell: ({ row }) => (
      <span className="text-sm">
        {Math.round(row.original.creditsUsed).toLocaleString()}
      </span>
    ),
  },
];

type ProjectUsageRow = ProjectCreditUsage & { id: string };