MCPcopy Create free account
hub / github.com/CodebuffAI/codebuff / useOrgAutoTopup

Function useOrgAutoTopup

web/src/hooks/use-org-auto-topup.ts:51–416  ·  view source on GitHub ↗
(organizationId: string)

Source from the content-addressed store, hash-verified

49}
50
51export function useOrgAutoTopup(organizationId: string): OrgAutoTopupState {
52 const queryClient = useQueryClient()
53 const [isEnabled, setIsEnabled] = useState(false)
54 const [threshold, setThreshold] = useState<number>(
55 ORG_AUTO_TOPUP_CONSTANTS.MIN_THRESHOLD_CREDITS,
56 )
57 const [topUpAmountDollars, setTopUpAmountDollars] =
58 useState<number>(MIN_TOPUP_DOLLARS)
59 const isInitialLoad = useRef(true)
60 const pendingSettings = useRef<{
61 threshold: number
62 topUpAmountDollars: number
63 } | null>(null)
64
65 const { data: organizationSettings, isLoading: isLoadingSettings } =
66 useQuery<OrganizationSettings>({
67 queryKey: ['organizationSettings', organizationId],
68 queryFn: async () => {
69 const response = await fetch(`/api/orgs/${organizationId}/settings`)
70 if (!response.ok)
71 throw new Error('Failed to fetch organization settings')
72 const data = await response.json()
73
74 const thresholdCredits =
75 data.autoTopupThreshold ??
76 ORG_AUTO_TOPUP_CONSTANTS.MIN_THRESHOLD_CREDITS
77 const topUpAmount =
78 data.autoTopupAmount ?? ORG_AUTO_TOPUP_CONSTANTS.MIN_TOPUP_CREDITS
79 const topUpDollars =
80 (topUpAmount * ORG_AUTO_TOPUP_CONSTANTS.CENTS_PER_CREDIT) / 100
81
82 return {
83 ...data,
84 autoTopupEnabled: data.autoTopupEnabled ?? false,
85 autoTopupThreshold: clamp(
86 thresholdCredits,
87 ORG_AUTO_TOPUP_CONSTANTS.MIN_THRESHOLD_CREDITS,
88 ORG_AUTO_TOPUP_CONSTANTS.MAX_THRESHOLD_CREDITS,
89 ),
90 autoTopupAmount: clamp(
91 topUpAmount,
92 ORG_AUTO_TOPUP_CONSTANTS.MIN_TOPUP_CREDITS,
93 (ORG_AUTO_TOPUP_CONSTANTS.MAX_TOPUP_DOLLARS * 100) /
94 ORG_AUTO_TOPUP_CONSTANTS.CENTS_PER_CREDIT,
95 ),
96 initialTopUpDollars: clamp(
97 topUpDollars > 0 ? topUpDollars : MIN_TOPUP_DOLLARS,
98 MIN_TOPUP_DOLLARS,
99 ORG_AUTO_TOPUP_CONSTANTS.MAX_TOPUP_DOLLARS,
100 ),
101 }
102 },
103 enabled: !!organizationId,
104 })
105
106 const canManageAutoTopup = organizationSettings?.userRole === 'owner'
107
108 useEffect(() => {

Callers 2

OrgAutoTopupSettingsFunction · 0.90
CreditMonitorFunction · 0.90

Calls 4

clampFunction · 0.90
toastFunction · 0.90
setTimeoutFunction · 0.85
fetchFunction · 0.50

Tested by

no test coverage detected