-
Notifications
You must be signed in to change notification settings - Fork 74
/
actions.ts
619 lines (520 loc) · 17.2 KB
/
actions.ts
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/* eslint-disable @typescript-eslint/no-non-null-assertion -- checked in configureLemonSqueezy() */
"use server";
import crypto from "node:crypto";
import {
cancelSubscription,
createCheckout,
createWebhook,
getPrice,
getProduct,
getSubscription,
listPrices,
listProducts,
listWebhooks,
updateSubscription,
type Variant,
} from "@lemonsqueezy/lemonsqueezy.js";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { notFound } from "next/navigation";
import {
db,
plans,
subscriptions,
webhookEvents,
type NewPlan,
type NewSubscription,
type NewWebhookEvent,
} from "@/db/schema";
import { configureLemonSqueezy } from "@/config/lemonsqueezy";
import { webhookHasData, webhookHasMeta } from "@/lib/typeguards";
import { takeUniqueOrThrow } from "@/lib/utils";
import { auth, signOut } from "../auth";
/**
* This action will log out the current user.
*/
export async function logout() {
await signOut();
}
/**
* This action will create a checkout on Lemon Squeezy.
*/
export async function getCheckoutURL(variantId: number, embed = false) {
configureLemonSqueezy();
const session = await auth();
if (!session?.user) {
throw new Error("User is not authenticated.");
}
const checkout = await createCheckout(
process.env.LEMONSQUEEZY_STORE_ID!,
variantId,
{
checkoutOptions: {
embed,
media: false,
logo: !embed,
},
checkoutData: {
email: session.user.email ?? undefined,
custom: {
user_id: session.user.id,
},
},
productOptions: {
enabledVariants: [variantId],
redirectUrl: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard/billing/`,
receiptButtonText: "Go to Dashboard",
receiptThankYouNote: "Thank you for signing up to Lemon Stand!",
},
},
);
return checkout.data?.data.attributes.url;
}
/**
* This action will check if a webhook exists on Lemon Squeezy. It will return
* the webhook if it exists, otherwise it will return undefined.
*/
export async function hasWebhook() {
configureLemonSqueezy();
if (!process.env.WEBHOOK_URL) {
throw new Error(
"Missing required WEBHOOK_URL env variable. Please, set it in your .env file.",
);
}
// Check if a webhook exists on Lemon Squeezy.
const allWebhooks = await listWebhooks({
filter: { storeId: process.env.LEMONSQUEEZY_STORE_ID },
});
// Check if WEBHOOK_URL ends with a slash. If not, add it.
let webhookUrl = process.env.WEBHOOK_URL;
if (!webhookUrl.endsWith("/")) {
webhookUrl += "/";
}
webhookUrl += "api/webhook";
const webhook = allWebhooks.data?.data.find(
(wh) => wh.attributes.url === webhookUrl && wh.attributes.test_mode,
);
return webhook;
}
/**
* This action will set up a webhook on Lemon Squeezy to listen to
* Subscription events. It will only set up the webhook if it does not exist.
*/
export async function setupWebhook() {
configureLemonSqueezy();
if (!process.env.WEBHOOK_URL) {
throw new Error(
"Missing required WEBHOOK_URL env variable. Please, set it in your .env file.",
);
}
// Check if WEBHOOK_URL ends with a slash. If not, add it.
let webhookUrl = process.env.WEBHOOK_URL;
if (!webhookUrl.endsWith("/")) {
webhookUrl += "/";
}
webhookUrl += "api/webhook";
// eslint-disable-next-line no-console -- allow
console.log("Setting up a webhook on Lemon Squeezy (Test Mode)...");
// Do not set a webhook on Lemon Squeezy if it already exists.
let webhook = await hasWebhook();
// If the webhook does not exist, create it.
if (!webhook) {
const newWebhook = await createWebhook(process.env.LEMONSQUEEZY_STORE_ID!, {
secret: process.env.LEMONSQUEEZY_WEBHOOK_SECRET!,
url: webhookUrl,
testMode: true, // will create a webhook in Test mode only!
events: [
"subscription_created",
"subscription_expired",
"subscription_updated",
],
});
webhook = newWebhook.data?.data;
}
// eslint-disable-next-line no-console -- allow
console.log(`Webhook ${webhook?.id} created on Lemon Squeezy.`);
}
/**
* This action will sync the product variants from Lemon Squeezy with the
* Plans database model. It will only sync the 'subscription' variants.
*/
export async function syncPlans() {
configureLemonSqueezy();
// Fetch all the variants from the database.
const productVariants: NewPlan[] = await db.select().from(plans);
// Helper function to add a variant to the productVariants array and sync it with the database.
async function _addVariant(variant: NewPlan) {
// eslint-disable-next-line no-console -- allow
console.log(`Syncing variant ${variant.name} with the database...`);
// Sync the variant with the plan in the database.
await db
.insert(plans)
.values(variant)
.onConflictDoUpdate({ target: plans.variantId, set: variant });
/* eslint-disable no-console -- allow */
console.log(`${variant.name} synced with the database...`);
productVariants.push(variant);
}
// Fetch products from the Lemon Squeezy store.
const products = await listProducts({
filter: { storeId: process.env.LEMONSQUEEZY_STORE_ID },
include: ["variants"],
});
// Loop through all the variants.
const allVariants = products.data?.included as Variant["data"][] | undefined;
// for...of supports asynchronous operations, unlike forEach.
if (allVariants) {
for (const v of allVariants) {
const variant = v.attributes;
// Skip draft variants or if there's more than one variant, skip the default
// variant. See https://docs.lemonsqueezy.com/api/variants
if (
variant.status === "draft" ||
(allVariants.length !== 1 && variant.status === "pending")
) {
// `return` exits the function entirely, not just the current iteration.
continue;
}
// Fetch the Product name.
const productName =
(await getProduct(variant.product_id)).data?.data.attributes.name ?? "";
// Fetch the Price object.
const variantPriceObject = await listPrices({
filter: {
variantId: v.id,
},
});
const currentPriceObj = variantPriceObject.data?.data.at(0);
const isUsageBased =
currentPriceObj?.attributes.usage_aggregation !== null;
const interval = currentPriceObj?.attributes.renewal_interval_unit;
const intervalCount =
currentPriceObj?.attributes.renewal_interval_quantity;
const trialInterval = currentPriceObj?.attributes.trial_interval_unit;
const trialIntervalCount =
currentPriceObj?.attributes.trial_interval_quantity;
const price = isUsageBased
? currentPriceObj?.attributes.unit_price_decimal
: currentPriceObj.attributes.unit_price;
const priceString = price !== null ? price?.toString() ?? "" : "";
const isSubscription =
currentPriceObj?.attributes.category === "subscription";
// If not a subscription, skip it.
if (!isSubscription) {
continue;
}
await _addVariant({
name: variant.name,
description: variant.description,
price: priceString,
interval,
intervalCount,
isUsageBased,
productId: variant.product_id,
productName,
variantId: parseInt(v.id) as unknown as number,
trialInterval,
trialIntervalCount,
sort: variant.sort,
});
}
}
return productVariants;
}
/**
* This action will store a webhook event in the database.
* @param eventName - The name of the event.
* @param body - The body of the event.
*/
export async function storeWebhookEvent(
eventName: string,
body: NewWebhookEvent["body"],
) {
if (!process.env.POSTGRES_URL) {
throw new Error("POSTGRES_URL is not set");
}
const id = crypto.randomInt(100000000, 1000000000);
const returnedValue = await db
.insert(webhookEvents)
.values({
id,
eventName,
processed: false,
body,
})
.onConflictDoNothing({ target: plans.id })
.returning();
return returnedValue[0];
}
/**
* This action will process a webhook event in the database.
*/
export async function processWebhookEvent(webhookEvent: NewWebhookEvent) {
configureLemonSqueezy();
const dbwebhookEvent = await db
.select()
.from(webhookEvents)
.where(eq(webhookEvents.id, webhookEvent.id));
if (dbwebhookEvent.length < 1) {
throw new Error(
`Webhook event #${webhookEvent.id} not found in the database.`,
);
}
if (!process.env.WEBHOOK_URL) {
throw new Error(
"Missing required WEBHOOK_URL env variable. Please, set it in your .env file.",
);
}
let processingError = "";
const eventBody = webhookEvent.body;
if (!webhookHasMeta(eventBody)) {
processingError = "Event body is missing the 'meta' property.";
} else if (webhookHasData(eventBody)) {
if (webhookEvent.eventName.startsWith("subscription_payment_")) {
// Save subscription invoices; eventBody is a SubscriptionInvoice
// Not implemented.
} else if (webhookEvent.eventName.startsWith("subscription_")) {
// Save subscription events; obj is a Subscription
const attributes = eventBody.data.attributes;
const variantId = attributes.variant_id as string;
// We assume that the Plan table is up to date.
const plan = await db
.select()
.from(plans)
.where(eq(plans.variantId, parseInt(variantId, 10)));
if (plan.length < 1) {
processingError = `Plan with variantId ${variantId} not found.`;
} else {
// Update the subscription in the database.
const priceId = attributes.first_subscription_item.price_id;
// Get the price data from Lemon Squeezy.
const priceData = await getPrice(priceId);
if (priceData.error) {
processingError = `Failed to get the price data for the subscription ${eventBody.data.id}.`;
}
const isUsageBased = attributes.first_subscription_item.is_usage_based;
const price = isUsageBased
? priceData.data?.data.attributes.unit_price_decimal
: priceData.data?.data.attributes.unit_price;
const updateData: NewSubscription = {
lemonSqueezyId: eventBody.data.id,
orderId: attributes.order_id as number,
name: attributes.user_name as string,
email: attributes.user_email as string,
status: attributes.status as string,
statusFormatted: attributes.status_formatted as string,
renewsAt: attributes.renews_at as string,
endsAt: attributes.ends_at as string,
trialEndsAt: attributes.trial_ends_at as string,
price: price?.toString() ?? "",
isPaused: false,
subscriptionItemId: attributes.first_subscription_item.id,
isUsageBased: attributes.first_subscription_item.is_usage_based,
userId: eventBody.meta.custom_data.user_id,
planId: plan[0].id,
};
// Create/update subscription in the database.
try {
await db.insert(subscriptions).values(updateData).onConflictDoUpdate({
target: subscriptions.lemonSqueezyId,
set: updateData,
});
} catch (error) {
processingError = `Failed to upsert Subscription #${updateData.lemonSqueezyId} to the database.`;
console.error(error);
}
}
} else if (webhookEvent.eventName.startsWith("order_")) {
// Save orders; eventBody is a "Order"
/* Not implemented */
} else if (webhookEvent.eventName.startsWith("license_")) {
// Save license keys; eventBody is a "License key"
/* Not implemented */
}
// Update the webhook event in the database.
await db
.update(webhookEvents)
.set({
processed: true,
processingError,
})
.where(eq(webhookEvents.id, webhookEvent.id));
}
}
/**
* This action will get the subscriptions for the current user.
*/
export async function getUserSubscriptions() {
const session = await auth();
const userId = session?.user?.id;
if (!userId) {
notFound();
}
const userSubscriptions: NewSubscription[] = await db
.select()
.from(subscriptions)
.where(eq(subscriptions.userId, userId));
return userSubscriptions;
}
/**
* This action will get the subscription URLs (update_payment_method and
* customer_portal) for the given subscription ID.
*
*/
export async function getSubscriptionURLs(id: string) {
configureLemonSqueezy();
const subscription = await getSubscription(id);
if (subscription.error) {
throw new Error(subscription.error.message);
}
return subscription.data?.data.attributes.urls;
}
/**
* This action will cancel a subscription on Lemon Squeezy.
*/
export async function cancelSub(id: string) {
configureLemonSqueezy();
// Get user subscriptions
const userSubscriptions = await getUserSubscriptions();
// Check if the subscription exists
const subscription = userSubscriptions.find(
(sub) => sub.lemonSqueezyId === id,
);
if (!subscription) {
throw new Error(`Subscription #${id} not found.`);
}
const cancelledSub = await cancelSubscription(id);
if (cancelledSub.error) {
throw new Error(cancelledSub.error.message);
}
// Update the db
try {
await db
.update(subscriptions)
.set({
status: cancelledSub.data?.data.attributes.status,
statusFormatted: cancelledSub.data?.data.attributes.status_formatted,
endsAt: cancelledSub.data?.data.attributes.ends_at,
})
.where(eq(subscriptions.lemonSqueezyId, id));
} catch (error) {
throw new Error(`Failed to cancel Subscription #${id} in the database.`);
}
revalidatePath("/");
return cancelledSub;
}
/**
* This action will pause a subscription on Lemon Squeezy.
*/
export async function pauseUserSubscription(id: string) {
configureLemonSqueezy();
// Get user subscriptions
const userSubscriptions = await getUserSubscriptions();
// Check if the subscription exists
const subscription = userSubscriptions.find(
(sub) => sub.lemonSqueezyId === id,
);
if (!subscription) {
throw new Error(`Subscription #${id} not found.`);
}
const returnedSub = await updateSubscription(id, {
pause: {
mode: "void",
},
});
// Update the db
try {
await db
.update(subscriptions)
.set({
status: returnedSub.data?.data.attributes.status,
statusFormatted: returnedSub.data?.data.attributes.status_formatted,
endsAt: returnedSub.data?.data.attributes.ends_at,
isPaused: returnedSub.data?.data.attributes.pause !== null,
})
.where(eq(subscriptions.lemonSqueezyId, id));
} catch (error) {
throw new Error(`Failed to pause Subscription #${id} in the database.`);
}
revalidatePath("/");
return returnedSub;
}
/**
* This action will unpause a subscription on Lemon Squeezy.
*/
export async function unpauseUserSubscription(id: string) {
configureLemonSqueezy();
// Get user subscriptions
const userSubscriptions = await getUserSubscriptions();
// Check if the subscription exists
const subscription = userSubscriptions.find(
(sub) => sub.lemonSqueezyId === id,
);
if (!subscription) {
throw new Error(`Subscription #${id} not found.`);
}
const returnedSub = await updateSubscription(id, {
// @ts-expect-error -- null is a valid value for pause
pause: null,
});
// Update the db
try {
await db
.update(subscriptions)
.set({
status: returnedSub.data?.data.attributes.status,
statusFormatted: returnedSub.data?.data.attributes.status_formatted,
endsAt: returnedSub.data?.data.attributes.ends_at,
isPaused: returnedSub.data?.data.attributes.pause !== null,
})
.where(eq(subscriptions.lemonSqueezyId, id));
} catch (error) {
throw new Error(`Failed to pause Subscription #${id} in the database.`);
}
revalidatePath("/");
return returnedSub;
}
/**
* This action will change the plan of a subscription on Lemon Squeezy.
*/
export async function changePlan(currentPlanId: number, newPlanId: number) {
configureLemonSqueezy();
// Get user subscriptions
const userSubscriptions = await getUserSubscriptions();
// Check if the subscription exists
const subscription = userSubscriptions.find(
(sub) => sub.planId === currentPlanId,
);
if (!subscription) {
throw new Error(
`No subscription with plan id #${currentPlanId} was found.`,
);
}
// Get the new plan details from the database.
const newPlan = await db
.select()
.from(plans)
.where(eq(plans.id, newPlanId))
.then(takeUniqueOrThrow);
// Send request to Lemon Squeezy to change the subscription.
const updatedSub = await updateSubscription(subscription.lemonSqueezyId, {
variantId: newPlan.variantId,
});
// Save in db
try {
await db
.update(subscriptions)
.set({
planId: newPlanId,
price: newPlan.price,
endsAt: updatedSub.data?.data.attributes.ends_at,
})
.where(eq(subscriptions.lemonSqueezyId, subscription.lemonSqueezyId));
} catch (error) {
throw new Error(
`Failed to update Subscription #${subscription.lemonSqueezyId} in the database.`,
);
}
revalidatePath("/");
return updatedSub;
}