All files / app/(dashboard)/subscription SubscriptionActions.tsx

100% Statements 112/112
92.59% Branches 25/27
100% Functions 7/7
100% Lines 112/112

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 1581x                                       1x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x   40x 40x 40x     40x 30x 4x 1x 1x 4x   30x 6x 6x 6x 40x   40x 5x 5x 5x 5x 5x   5x   5x 1x 1x   4x 4x 4x 4x   4x 5x 1x 1x 1x 1x 1x 5x 5x 5x 5x   40x 3x 3x 3x   40x 40x 40x 40x 37x 37x   37x 37x 37x     40x 22x 22x 22x 22x 22x   22x   22x 22x 6x 6x 13x 13x 13x 3x 3x 3x 13x   13x 13x 6x 6x   22x     40x 16x 16x 16x 16x     40x 38x 38x 38x   40x   40x 4x 4x 4x 4x 4x 4x 4x 4x 4x   40x   40x  
'use client';
 
import { useState, useRef, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ArrowRight, ArrowDown, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { DowngradeDialog } from '@/components/subscription/DowngradeDialog';
import { useToast } from '@/hooks/use-toast';
import { TIER_NAMES, type SubscriptionTier } from '@/lib/subscription/tiers';
import { getDowngradeOptions } from '@/lib/subscription/downgrade';
 
interface SubscriptionActionsProps {
  currentTier: string;
  currentPeriodEnd: string | null;
  hasPendingDowngrade: boolean;
  pendingDowngradeTier: string | null;
  contentCounts: { samples: number; testimonials: number; packages: number };
}
 
export function SubscriptionActions({
  currentTier,
  currentPeriodEnd,
  hasPendingDowngrade,
  pendingDowngradeTier: _pendingDowngradeTier,
  contentCounts,
}: SubscriptionActionsProps) {
  const router = useRouter();
  const { toast } = useToast();
  const [showDowngradeDialog, setShowDowngradeDialog] = useState(false);
  const [selectedDowngradeTier, setSelectedDowngradeTier] = useState<SubscriptionTier | null>(null);
  const [isCancelling, setIsCancelling] = useState(false);
  const [showDowngradeMenu, setShowDowngradeMenu] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
 
  const tier = currentTier as SubscriptionTier;
  const downgradeOptions = getDowngradeOptions(tier);
  const isSubscribed = tier !== 'free';
 
  // Close menu when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setShowDowngradeMenu(false);
      }
    }
 
    if (showDowngradeMenu) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => document.removeEventListener('mousedown', handleClickOutside);
    }
  }, [showDowngradeMenu]);
 
  async function cancelPendingDowngrade() {
    setIsCancelling(true);
    try {
      const response = await fetch('/api/subscription/downgrade', {
        method: 'DELETE',
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        throw new Error(data.error || 'Failed to cancel downgrade');
      }
 
      toast({
        title: 'Downgrade cancelled',
        description: `You will keep your ${TIER_NAMES[tier]} plan.`,
      });
 
      router.refresh();
    } catch (error) {
      toast({
        title: 'Error',
        description: error instanceof Error ? error.message : 'Failed to cancel downgrade',
        variant: 'destructive',
      });
    } finally {
      setIsCancelling(false);
    }
  }
 
  function openDowngradeDialog(targetTier: SubscriptionTier) {
    setSelectedDowngradeTier(targetTier);
    setShowDowngradeDialog(true);
  }
 
  return (
    <>
      <div className="flex flex-col gap-2">
        {tier !== 'premium' && (
          <Button asChild>
            <Link href="/pricing">
              Upgrade Plan
              <ArrowRight className="ml-2 h-4 w-4" />
            </Link>
          </Button>
        )}
 
        {isSubscribed && !hasPendingDowngrade && downgradeOptions.length > 0 && (
          <div className="relative" ref={menuRef}>
            <Button
              variant="outline"
              className="w-full"
              onClick={() => setShowDowngradeMenu(!showDowngradeMenu)}
            >
              <ArrowDown className="mr-2 h-4 w-4" />
              Downgrade Plan
            </Button>
            {showDowngradeMenu && (
              <div className="absolute right-0 top-full z-10 mt-1 min-w-[160px] rounded-md border bg-popover p-1 shadow-md">
                {downgradeOptions.map((option) => (
                  <button
                    key={option}
                    onClick={() => {
                      openDowngradeDialog(option);
                      setShowDowngradeMenu(false);
                    }}
                    className="w-full rounded px-3 py-2 text-left text-sm hover:bg-muted"
                  >
                    {TIER_NAMES[option]}
                  </button>
                ))}
              </div>
            )}
          </div>
        )}
 
        {hasPendingDowngrade && (
          <Button variant="outline" onClick={cancelPendingDowngrade} disabled={isCancelling}>
            <X className="mr-2 h-4 w-4" />
            {isCancelling ? 'Cancelling...' : 'Cancel Downgrade'}
          </Button>
        )}
 
        {isSubscribed && (
          <Button variant="ghost" asChild>
            <Link href="/pricing">View All Plans</Link>
          </Button>
        )}
      </div>
 
      {selectedDowngradeTier && (
        <DowngradeDialog
          open={showDowngradeDialog}
          onOpenChange={setShowDowngradeDialog}
          currentTier={tier}
          targetTier={selectedDowngradeTier}
          currentPeriodEnd={currentPeriodEnd}
          currentCounts={contentCounts}
          onDowngradeComplete={() => router.refresh()}
        />
      )}
    </>
  );
}