()
| 28 | } = AUTO_TOPUP_CONSTANTS |
| 29 | |
| 30 | export function useAutoTopup(): AutoTopupState { |
| 31 | const queryClient = useQueryClient() |
| 32 | const [isEnabled, setIsEnabled] = useState(false) |
| 33 | const [threshold, setThreshold] = useState<number>(DEFAULT_THRESHOLD_CREDITS) |
| 34 | const [topUpAmountDollars, setTopUpAmountDollars] = |
| 35 | useState<number>(DEFAULT_TOPUP_DOLLARS) |
| 36 | const isInitialLoad = useRef(true) |
| 37 | const pendingSettings = useRef<{ |
| 38 | threshold: number |
| 39 | topUpAmountDollars: number |
| 40 | } | null>(null) |
| 41 | const [isCheckingBalance, setIsCheckingBalance] = useState(false) |
| 42 | const [showConfirmDialog, setShowConfirmDialog] = useState(false) |
| 43 | const [confirmDialogBalance, setConfirmDialogBalance] = useState< |
| 44 | number | null |
| 45 | >(null) |
| 46 | |
| 47 | const { data: userProfile, isLoading: isLoadingProfile } = useQuery< |
| 48 | UserProfile & { initialTopUpDollars?: number } |
| 49 | >({ |
| 50 | queryKey: ['userProfile'], |
| 51 | queryFn: async () => { |
| 52 | const response = await fetch('/api/user/profile') |
| 53 | if (!response.ok) throw new Error('Failed to fetch profile') |
| 54 | const data = await response.json() |
| 55 | const thresholdCredits = |
| 56 | data.auto_topup_threshold ?? DEFAULT_THRESHOLD_CREDITS |
| 57 | const topUpAmount = data.auto_topup_amount ?? DEFAULT_TOPUP_DOLLARS * 100 |
| 58 | const topUpDollars = topUpAmount / 100 |
| 59 | |
| 60 | return { |
| 61 | ...data, |
| 62 | auto_topup_enabled: data.auto_topup_enabled ?? false, |
| 63 | auto_topup_threshold: clamp( |
| 64 | thresholdCredits, |
| 65 | MIN_THRESHOLD_CREDITS, |
| 66 | MAX_THRESHOLD_CREDITS, |
| 67 | ), |
| 68 | initialTopUpDollars: clamp( |
| 69 | topUpDollars > 0 ? topUpDollars : DEFAULT_TOPUP_DOLLARS, |
| 70 | MIN_TOPUP_DOLLARS, |
| 71 | MAX_TOPUP_DOLLARS, |
| 72 | ), |
| 73 | } |
| 74 | }, |
| 75 | }) |
| 76 | |
| 77 | useEffect(() => { |
| 78 | if (userProfile?.auto_topup_blocked_reason && isEnabled) { |
| 79 | setIsEnabled(false) |
| 80 | toast({ |
| 81 | title: 'Auto Top-up Disabled', |
| 82 | description: userProfile.auto_topup_blocked_reason, |
| 83 | variant: 'destructive', |
| 84 | }) |
| 85 | } |
| 86 | }, [userProfile?.auto_topup_blocked_reason, isEnabled]) |
| 87 |
no test coverage detected