()
| 26 | }; |
| 27 | |
| 28 | export async function getSubscriptionDetails(): Promise<SubscriptionDetailsResult> { |
| 29 | try { |
| 30 | const session = await auth.api.getSession({ |
| 31 | headers: await headers(), |
| 32 | }); |
| 33 | |
| 34 | if (!session?.user?.id) { |
| 35 | return { hasSubscription: false }; |
| 36 | } |
| 37 | |
| 38 | const userSubscriptions = await db |
| 39 | .select() |
| 40 | .from(subscription) |
| 41 | .where(eq(subscription.userId, session.user.id)); |
| 42 | |
| 43 | if (!userSubscriptions.length) { |
| 44 | return { hasSubscription: false }; |
| 45 | } |
| 46 | |
| 47 | // Get the most recent active subscription |
| 48 | const activeSubscription = userSubscriptions |
| 49 | .filter((sub) => sub.status === "active") |
| 50 | .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())[0]; |
| 51 | |
| 52 | if (!activeSubscription) { |
| 53 | // Check for canceled or expired subscriptions |
| 54 | const latestSubscription = userSubscriptions |
| 55 | .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())[0]; |
| 56 | |
| 57 | if (latestSubscription) { |
| 58 | const now = new Date(); |
| 59 | const isExpired = new Date(latestSubscription.currentPeriodEnd) < now; |
| 60 | const isCanceled = latestSubscription.status === "canceled"; |
| 61 | |
| 62 | return { |
| 63 | hasSubscription: true, |
| 64 | subscription: { |
| 65 | id: latestSubscription.id, |
| 66 | productId: latestSubscription.productId, |
| 67 | status: latestSubscription.status, |
| 68 | amount: latestSubscription.amount, |
| 69 | currency: latestSubscription.currency, |
| 70 | recurringInterval: latestSubscription.recurringInterval, |
| 71 | currentPeriodStart: latestSubscription.currentPeriodStart, |
| 72 | currentPeriodEnd: latestSubscription.currentPeriodEnd, |
| 73 | cancelAtPeriodEnd: latestSubscription.cancelAtPeriodEnd, |
| 74 | canceledAt: latestSubscription.canceledAt, |
| 75 | organizationId: null, |
| 76 | }, |
| 77 | error: isCanceled ? "Subscription has been canceled" : isExpired ? "Subscription has expired" : "Subscription is not active", |
| 78 | errorType: isCanceled ? "CANCELED" : isExpired ? "EXPIRED" : "GENERAL", |
| 79 | }; |
| 80 | } |
| 81 | |
| 82 | return { hasSubscription: false }; |
| 83 | } |
| 84 | |
| 85 | return { |
no outgoing calls
no test coverage detected