All files / components/subscription DowngradeDialog.tsx

100% Statements 149/149
93.1% Branches 27/29
100% Functions 6/6
100% Lines 149/149

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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 2101x                                                           1x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x   52x 52x 52x   52x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x   8x 1x 1x   7x 8x 8x 5x 2x 8x   8x 8x 8x 1x 1x 1x 1x 1x 8x 8x 8x 8x   52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x   52x   52x 4x 4x 4x 4x 4x   4x 4x 4x   4x 4x 4x 2x   4x 2x   4x 2x   4x 4x   4x 4x 4x 4x       52x 48x 48x 48x 48x 96x 96x 96x 96x 48x 48x 48x       52x 52x   52x 51x 51x 51x 51x 6x 45x 51x   51x 51x 51x 51x 51x 51x   51x 51x 51x 51x     52x 52x 52x 52x 52x   52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x   52x 52x   52x 52x 52x 52x 52x 52x   52x 52x 52x 52x 52x   52x  
'use client';
 
import { useState } from 'react';
import { AlertTriangle, ArrowDown, Calendar, Clock, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { useToast } from '@/hooks/use-toast';
import { TIER_NAMES, type SubscriptionTier } from '@/lib/subscription/tiers';
import {
  calculateDowngradeImpact,
  hasDowngradeImpact,
  getLostFeatures,
} from '@/lib/subscription/downgrade';
 
interface DowngradeDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  currentTier: SubscriptionTier;
  targetTier: SubscriptionTier;
  currentPeriodEnd: string | null;
  currentCounts: { samples: number; testimonials: number; packages: number };
  onDowngradeComplete: () => void;
}
 
export function DowngradeDialog({
  open,
  onOpenChange,
  currentTier,
  targetTier,
  currentPeriodEnd,
  currentCounts,
  onDowngradeComplete,
}: DowngradeDialogProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [downgradeType, setDowngradeType] = useState<'scheduled' | 'immediate' | null>(null);
  const { toast } = useToast();
 
  const impact = calculateDowngradeImpact(targetTier, currentCounts);
  const hasImpact = hasDowngradeImpact(impact);
  const lostFeatures = getLostFeatures(currentTier, targetTier);
 
  async function handleDowngrade(immediate: boolean) {
    setIsLoading(true);
    try {
      const response = await fetch('/api/subscription/downgrade', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          target_tier: targetTier,
          immediate,
        }),
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        throw new Error(data.error || 'Failed to process downgrade');
      }
 
      toast({
        title: immediate ? 'Plan downgraded' : 'Downgrade scheduled',
        description: immediate
          ? `You are now on the ${TIER_NAMES[targetTier]} plan.`
          : `Your plan will change to ${TIER_NAMES[targetTier]} on ${new Date(data.effective_date).toLocaleDateString()}.`,
      });
 
      onDowngradeComplete();
      onOpenChange(false);
    } catch (error) {
      toast({
        title: 'Error',
        description: error instanceof Error ? error.message : 'Failed to process downgrade',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  }
 
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <ArrowDown className="h-5 w-5 text-orange-500" />
            Downgrade to {TIER_NAMES[targetTier]}
          </DialogTitle>
          <DialogDescription>
            Review the impact of downgrading from {TIER_NAMES[currentTier]} to{' '}
            {TIER_NAMES[targetTier]}.
          </DialogDescription>
        </DialogHeader>
 
        <div className="space-y-4">
          {/* Content Impact Warning */}
          {hasImpact && (
            <div className="rounded-lg border border-orange-200 bg-orange-50 p-4 dark:border-orange-900 dark:bg-orange-950/30">
              <div className="flex items-start gap-3">
                <AlertTriangle className="mt-0.5 h-5 w-5 flex-shrink-0 text-orange-500" />
                <div>
                  <p className="font-medium text-orange-800 dark:text-orange-200">
                    Content will be hidden
                  </p>
                  <p className="mt-1 text-sm text-orange-700 dark:text-orange-300">
                    Some of your content exceeds the {TIER_NAMES[targetTier]} plan limits and will
                    be hidden from your public profile:
                  </p>
                  <ul className="mt-2 space-y-1 text-sm text-orange-700 dark:text-orange-300">
                    {impact.samples.over_limit > 0 && (
                      <li>• {impact.samples.over_limit} work sample(s) will be hidden</li>
                    )}
                    {impact.testimonials.over_limit > 0 && (
                      <li>• {impact.testimonials.over_limit} testimonial(s) will be hidden</li>
                    )}
                    {impact.packages.over_limit > 0 && (
                      <li>• {impact.packages.over_limit} package(s) will be hidden</li>
                    )}
                  </ul>
                  <p className="mt-2 text-xs text-orange-600 dark:text-orange-400">
                    Your content is not deleted - upgrade anytime to restore visibility.
                  </p>
                </div>
              </div>
            </div>
          )}
 
          {/* Lost Features */}
          {lostFeatures.length > 0 && (
            <div className="rounded-lg border p-4">
              <p className="mb-2 font-medium">Features you will lose:</p>
              <ul className="space-y-1 text-sm text-muted-foreground">
                {lostFeatures.map((feature) => (
                  <li key={feature} className="flex items-center gap-2">
                    <X className="h-4 w-4 text-destructive" />
                    {feature}
                  </li>
                ))}
              </ul>
            </div>
          )}
 
          {/* Downgrade Options */}
          <div className="space-y-3">
            <p className="text-sm font-medium">When should the downgrade take effect?</p>
 
            {currentPeriodEnd && (
              <button
                onClick={() => setDowngradeType('scheduled')}
                className={`w-full rounded-lg border p-4 text-left transition-colors ${
                  downgradeType === 'scheduled'
                    ? 'border-primary bg-primary/5'
                    : 'hover:bg-muted/50'
                }`}
              >
                <div className="flex items-start gap-3">
                  <Calendar className="mt-0.5 h-5 w-5 text-primary" />
                  <div>
                    <p className="font-medium">End of current period</p>
                    <p className="text-sm text-muted-foreground">
                      Keep your current plan until {new Date(currentPeriodEnd).toLocaleDateString()}
                      , then switch.
                    </p>
                  </div>
                </div>
              </button>
            )}
 
            <button
              onClick={() => setDowngradeType('immediate')}
              className={`w-full rounded-lg border p-4 text-left transition-colors ${
                downgradeType === 'immediate' ? 'border-primary bg-primary/5' : 'hover:bg-muted/50'
              }`}
            >
              <div className="flex items-start gap-3">
                <Clock className="mt-0.5 h-5 w-5 text-primary" />
                <div>
                  <p className="font-medium">Immediately</p>
                  <p className="text-sm text-muted-foreground">
                    Switch to {TIER_NAMES[targetTier]} plan right now.
                  </p>
                </div>
              </div>
            </button>
          </div>
        </div>
 
        <div className="mt-4 flex gap-3">
          <Button variant="outline" onClick={() => onOpenChange(false)} className="flex-1">
            Cancel
          </Button>
          <Button
            onClick={() => handleDowngrade(downgradeType === 'immediate')}
            disabled={!downgradeType || isLoading}
            variant="destructive"
            className="flex-1"
          >
            {isLoading ? 'Processing...' : 'Confirm Downgrade'}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}