Repository navigation
Expand file tree
/
Copy pathuse-subscription.ts
More file actions
225 lines (205 loc) · 7.94 KB
/
Copy pathuse-subscription.ts
File metadata and controls
225 lines (205 loc) · 7.94 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import { useQuery } from '@tanstack/react-query';
import { supabase } from '@/lib/supabase/client';
import { useAuth } from '@/lib/supabase/AuthProvider';
import {
planDailyLimit,
resolveBillingState,
type BillingDateKind,
type BillingStateName,
type BillingSubscriptionRow,
} from '../../supabase/functions/_shared/billing-state';
export type SubscriptionTier = 'trial' | 'pro' | 'legacy_free' | 'expired';
export type { BillingDateKind, BillingStateName };
// The server's tier defaults (supabase/functions/_shared/usage-limits.ts).
const DEFAULT_LIMITS = { pro: 50, trial: 5 };
interface SubscriptionState {
tier: SubscriptionTier;
/** The state the server resolves too (billing-state.ts); Settings shows it. */
billingState: BillingStateName;
/** The date that goes with the state: trial end, renewal, cancellation, payment grace end, or when Pro ended. */
billingDate: string | null;
billingDateKind: BillingDateKind | null;
/** A Stripe subscription can still bill, so the next step is Manage subscription, not Checkout. */
hasOpenSubscription: boolean;
isPro: boolean;
isTrialActive: boolean;
isExpired: boolean;
hasStripeBilling: boolean;
dailyLimit: number;
dailyUsed: number;
/** AI requests left today, or null while it is unknown (loading, failed read, signed out). Never block on null. */
remainingToday: number | null;
trialEndsAt: string | null;
gracePeriodEndsAt: string | null;
loading: boolean;
refresh: () => Promise<void>;
/** Re-reads usage and returns what is left today, or null when it cannot be read. */
checkRemainingToday: () => Promise<number | null>;
}
interface BillingRow extends BillingSubscriptionRow {
stripe_customer_id?: string | null;
}
type SubscriptionSnapshot = Omit<SubscriptionState, 'loading' | 'refresh' | 'checkRemainingToday' | 'isPro' | 'isTrialActive' | 'isExpired' | 'remainingToday'> & {
usageKnown: boolean;
};
const SUBSCRIPTION_STALE_TIME_MS = 60_000;
const SIGNED_OUT_SNAPSHOT: SubscriptionSnapshot = {
tier: 'trial',
billingState: 'trial',
billingDate: null,
billingDateKind: null,
hasOpenSubscription: false,
hasStripeBilling: false,
dailyLimit: 5,
dailyUsed: 0,
usageKnown: false,
trialEndsAt: null,
gracePeriodEndsAt: null,
};
const SIGNED_IN_FALLBACK: SubscriptionSnapshot = {
tier: 'expired',
billingState: 'trial_ended',
billingDate: null,
billingDateKind: null,
hasOpenSubscription: false,
hasStripeBilling: false,
dailyLimit: 0,
dailyUsed: 0,
usageKnown: false,
trialEndsAt: null,
gracePeriodEndsAt: null,
};
async function fetchSubscription(userId: string): Promise<SubscriptionSnapshot> {
let snapshot = { ...SIGNED_IN_FALLBACK };
let hasAccess = false;
try {
const { data, error: settingsError } = await supabase
.from('user_settings')
.select('subscription_tier, daily_limit_override, trial_ends_at, grace_period_ends_at')
.eq('user_id', userId)
.maybeSingle();
if (settingsError) {
console.warn('[useSubscription] Failed to load user settings:', settingsError.message);
throw new Error(settingsError.message);
}
if (data) {
let billingRows: BillingRow[] = [];
const { data: billingData, error: billingError } = await supabase
.from('subscriptions')
// `*`: the frontend ships on merge, before migrations, so naming a new
// column (payment_failed_at) would fail this read until it lands.
.select('*')
.eq('user_id', userId)
.order('current_period_end', { ascending: false, nullsFirst: false })
.limit(10);
if (billingError) {
console.warn('[useSubscription] Failed to load Stripe billing state:', billingError.message);
} else {
billingRows = billingData || [];
}
// The same resolver the AI functions use, so Settings never says
// "Expired" to an account the server serves (QB-02).
const billing = resolveBillingState(data, billingRows);
hasAccess = billing.hasAccess;
snapshot = {
...snapshot,
tier: billing.tier,
billingState: billing.state,
billingDate: billing.date,
billingDateKind: billing.dateKind,
hasOpenSubscription: billing.hasOpenSubscription,
dailyLimit: planDailyLimit(billing, data.daily_limit_override, DEFAULT_LIMITS),
hasStripeBilling: billingRows.some((row) => Boolean(row.stripe_customer_id)),
trialEndsAt: data.trial_ends_at,
gracePeriodEndsAt: data.grace_period_ends_at,
};
}
// The server lets a per-account rate_limits row replace the plan's limit
// (getConfiguredDailyLimit). Global rows are server-only, so the remaining
// count is an estimate: warn with it, and let the server's 402 decide.
let limitKnown = true;
// An account with no access is refused before the server reads rate_limits.
if (data && hasAccess) {
const { data: ownLimit, error: limitError } = await supabase
.from('rate_limits')
.select('limit_value')
.eq('user_id', userId)
.eq('limit_type', 'daily_requests')
.order('created_at', { ascending: false })
.limit(1)
.maybeSingle();
if (limitError) {
console.warn('[useSubscription] rate_limits lookup failed:', limitError.message);
limitKnown = false;
}
else if (typeof ownLimit?.limit_value === 'number') snapshot.dailyLimit = ownLimit.limit_value;
}
// The server's own counter (daily_usage_counters through ai_usage_today):
// model-weighted units, one charge per Crossfire or Sparring round, refunds
// given back. Counting logged rows would disagree with what the server
// enforces, so an unreadable counter leaves the count unknown (QB-03).
const counted = await readAIUsageToday();
if (counted === null) return { ...snapshot, usageKnown: false };
return { ...snapshot, dailyUsed: counted, usageKnown: limitKnown && Boolean(data) };
} catch (error) {
console.warn('[useSubscription] Failed to load:', error);
throw error;
}
}
/** Today's charged AI units from the server's counter, or null when it cannot be read. */
async function readAIUsageToday(): Promise<number | null> {
try {
const { data, error } = await supabase.rpc('ai_usage_today');
return !error && typeof data === 'number' ? data : null;
} catch {
return null;
}
}
function remainingRequests(snapshot: SubscriptionSnapshot, usageKnown: boolean): number | null {
if (!usageKnown) return null;
return Math.max(0, snapshot.dailyLimit - snapshot.dailyUsed);
}
export function useSubscription(): SubscriptionState {
const { user } = useAuth();
const userId = user?.id;
const query = useQuery({
queryKey: ['subscription', userId],
queryFn: () => fetchSubscription(userId!),
enabled: Boolean(userId),
staleTime: SUBSCRIPTION_STALE_TIME_MS,
});
const snapshot = userId
? query.isError ? SIGNED_IN_FALLBACK : query.data ?? SIGNED_IN_FALLBACK
: SIGNED_OUT_SNAPSHOT;
const { tier, billingState, billingDate, billingDateKind, hasOpenSubscription, dailyLimit, dailyUsed, trialEndsAt, gracePeriodEndsAt, hasStripeBilling } = snapshot;
const usageKnown = Boolean(userId) && !query.isError && snapshot.usageKnown;
const isPro = tier === 'pro' || tier === 'legacy_free';
const isTrialActive = tier === 'trial';
const isExpired = tier === 'expired';
return {
tier,
billingState,
billingDate,
billingDateKind,
hasOpenSubscription,
isPro,
isTrialActive,
isExpired,
hasStripeBilling,
dailyLimit,
dailyUsed,
remainingToday: remainingRequests(snapshot, usageKnown),
trialEndsAt,
gracePeriodEndsAt,
loading: Boolean(userId) && query.isPending,
refresh: async () => {
if (!userId) return;
await query.refetch();
},
checkRemainingToday: async () => {
if (!userId) return null;
const result = await query.refetch();
return result.isError || !result.data ? null : remainingRequests(result.data, result.data.usageKnown);
},
};
}