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.4 KB
Raw Blame
import {
  AiCreditsAutoTopUpState,
  isNil,
  ConsumableBillableFeature,
} from '@activepieces/shared';
import { useQueryClient } from '@tanstack/react-query';
import { t } from 'i18next';
import { Pencil } from 'lucide-react';
import { type ReactNode, useState } from 'react';

import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { AdminControl, adminControl } from '@/lib/admin-control';
import { cn } from '@/lib/utils';

import { billingMutations } from '../../hooks/billing-hooks';
import { DetailRow } from '../detail-row';

import { AutoRechargeConfigDialog } from './auto-recharge-config-dialog';

export const AutoRechargeCard = ({
  feature,
  hasCard,
  note,
  className,
}: AutoRechargeCardProps) => {
  const autoTopUp = feature.autoTopUp;
  const queryClient = useQueryClient();
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const { mutate: updateAutoTopUp, isPending } =
    billingMutations.useUpdateAutoTopUp(queryClient);
  const { mutate: setupPayment, isPending: isSettingUpPayment } =
    billingMutations.useSetupPayment();

  const enabled = (autoTopUp?.enabled ?? false) && !isNil(autoTopUp);

  const toggle = (checked: boolean) => {
    if (checked) {
      setIsDialogOpen(true);
      return;
    }
    updateAutoTopUp({
      state: AiCreditsAutoTopUpState.DISABLED,
      featureId: feature.featureId,
    });
  };

  // Auto-recharge can only charge with a card on file, so collect one first: a cardless customer sees an
  // "add payment method" CTA instead of the toggle. Once the card is saved, the toggle appears.
  if (!hasCard) {
    return (
      <div
        className={cn(
          'flex flex-col gap-4 rounded-xl border bg-panel p-5',
          className,
        )}
      >
        <span className="text-sm font-medium text-gray-12">
          {t('Enable auto recharge')}
        </span>
        {note && <span className="text-sm text-gray-11">{note}</span>}
        <span className="text-sm text-gray-11">
          {t(
            'Add a payment method to set up auto recharge. You can configure it once your card is on file.',
          )}
        </span>
        <Button
          {...adminControl(AdminControl.BILLING_PAYMENT_METHOD_OPEN)}
          variant="outline"
          size="sm"
          className="self-start"
          loading={isSettingUpPayment}
          onClick={() => setupPayment()}
        >
          {t('Add a payment method')}
        </Button>
      </div>
    );
  }

  return (
    <div
      className={cn(
        'flex flex-col gap-4 rounded-xl border bg-panel p-5',
        className,
      )}
    >
      <div className="flex items-center gap-2">
        <Switch
          {...adminControl(AdminControl.BILLING_AUTO_RECHARGE_TOGGLE)}
          checked={enabled}
          disabled={isPending}
          onCheckedChange={toggle}
        />
        <span className="text-sm font-medium text-gray-12">
          {t('Enable auto recharge')}
        </span>
      </div>
      {note && <span className="text-sm text-gray-11">{note}</span>}
      {enabled && (
        <>
          <div className="flex flex-col gap-2 text-sm">
            <DetailRow
              label={t('When credits below')}
              value={autoTopUp.threshold.toLocaleString()}
            />
            <DetailRow
              label={t('Add')}
              value={autoTopUp.quantity.toLocaleString()}
            />
            <DetailRow
              label={t('Monthly limit')}
              value={
                isNil(autoTopUp.maxMonthlyTopUps)
                  ? t('No limit')
                  : t(
                      '{count, plural, =1 {1 auto recharge} other {# auto recharges}}',
                      { count: autoTopUp.maxMonthlyTopUps },
                    )
              }
            />
          </div>
          <Button
            {...adminControl(AdminControl.BILLING_AUTO_RECHARGE_OPEN)}
            variant="outline"
            size="sm"
            className="self-start"
            onClick={() => setIsDialogOpen(true)}
          >
            <Pencil className="size-4" />
            {t('Edit')}
          </Button>
        </>
      )}
      <AutoRechargeConfigDialog
        key={isDialogOpen ? 'auto-open' : 'auto-closed'}
        isOpen={isDialogOpen}
        onOpenChange={setIsDialogOpen}
        feature={feature}
      />
    </div>
  );
};

type AutoRechargeCardProps = {
  feature: ConsumableBillableFeature;
  hasCard: boolean;
  note?: ReactNode;
  className?: string;
};