···145145 return;
146146 }
147147148148- // Update each subscription in the database
149149- for (const subscription of subscriptions.result.items) {
148148+ // Filter to only active/trialing/past_due subscriptions (not canceled/expired)
149149+ const currentSubscriptions = subscriptions.result.items.filter(
150150+ (sub) => sub.status === 'active' || sub.status === 'trialing' || sub.status === 'past_due'
151151+ );
152152+153153+ if (currentSubscriptions.length === 0) {
154154+ console.log(`[Sync] No current subscriptions found for customer ${customer.id}`);
155155+ return;
156156+ }
157157+158158+ // Update each current subscription in the database
159159+ for (const subscription of currentSubscriptions) {
150160 db.run(
151161 `INSERT INTO subscriptions (id, user_id, customer_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, updated_at)
152162 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
···183193 }
184194185195 console.log(
186186- `[Sync] Linked ${subscriptions.result.items.length} subscription(s) to user ${userId} (${email})`,
196196+ `[Sync] Linked ${currentSubscriptions.length} current subscription(s) to user ${userId} (${email})`,
187197 );
188198 } catch (error) {
189199 console.error(
+13-4
src/lib/auth.ts
···190190191191 // Get user's subscription if they have one
192192 const subscription = db
193193- .query<{ id: string }, [number]>(
194194- "SELECT id FROM subscriptions WHERE user_id = ? ORDER BY created_at DESC LIMIT 1",
193193+ .query<{ id: string; status: string; cancel_at_period_end: number }, [number]>(
194194+ "SELECT id, status, cancel_at_period_end FROM subscriptions WHERE user_id = ? ORDER BY created_at DESC LIMIT 1",
195195 )
196196 .get(userId);
197197198198- // Cancel subscription if it exists (soft cancel - keeps access until period end)
199199- if (subscription) {
198198+ // Cancel subscription if it exists and is not already canceled or scheduled to cancel
199199+ if (
200200+ subscription &&
201201+ subscription.status !== 'canceled' &&
202202+ subscription.status !== 'expired' &&
203203+ !subscription.cancel_at_period_end
204204+ ) {
200205 try {
201206 const { polar } = await import("./polar");
202207 await polar.subscriptions.update({
···213218 );
214219 // Continue with user deletion even if subscription cancellation fails
215220 }
221221+ } else if (subscription) {
222222+ console.log(
223223+ `[User Delete] Skipping cancellation for subscription ${subscription.id} (status: ${subscription.status}, cancel_at_period_end: ${subscription.cancel_at_period_end})`,
224224+ );
216225 }
217226218227 // Reassign class transcriptions to ghost user (id=0)