all repos — caroster @ 27332dc9778a133a03349f1ebc56af222fff16f0

[Octree] Group carpool to your event https://caroster.io

backend/src/api/stripe/services/stripe.ts (view raw)

 1import type { Stripe } from "stripe";
 2
 3export default () => ({
 4  async enableModule(stripeEvent: Stripe.CheckoutSessionCompletedEvent) {
 5    const eventUuid = stripeEvent.data.object.client_reference_id;
 6    if (!eventUuid) {
 7      strapi.log.error(
 8        `Can't retrieve event UUID in Stripe webhook. Webhook ID: ${stripeEvent.id}`
 9      );
10      return;
11    }
12
13    if (stripeEvent.data.object.payment_status !== "paid") {
14      strapi.log.error(
15        `Can't enable module for event UUID ${eventUuid} as payment status is not 'paid'. Webhook ID: ${stripeEvent.id}`
16      );
17      return;
18    }
19
20    const paymentLink = stripeEvent.data.object.payment_link as string;
21    const moduleProduct = await getModuleProduct(paymentLink);
22    if (!moduleProduct) {
23      strapi.log.error(
24        `Can't retrieve product/module in Stripe webhook. Is module enabled ? Webhook ID: ${stripeEvent.id}`
25      );
26      return;
27    }
28
29    const event = await strapi.db.query("api::event.event").findOne({
30      where: { uuid: eventUuid },
31      populate: ["creator"],
32    });
33    if (!event) {
34      strapi.log.error(
35        `Can't retrieve event with UUID ${eventUuid}. Webhook ID: ${stripeEvent.id}`
36      );
37      return;
38    }
39
40    try {
41      const enabledModules = event.enabled_modules
42        ? [...event.enabled_modules, moduleProduct.name]
43        : [moduleProduct.name];
44      await strapi.db.query("api::event.event").update({
45        where: { uuid: eventUuid },
46        data: { enabled_modules: enabledModules, unpaid: false },
47      });
48      strapi.log.info(
49        `Module '${moduleProduct.name}' enabled for event ${eventUuid}`
50      );
51
52      if (event.creator)
53        strapi.entityService.create("api::notification.notification", {
54          data: {
55            type: event.unpaid // unpaid before update
56              ? "EventCreated"
57              : moduleProduct.notificationType,
58            event,
59            user: event.creator,
60          },
61        });
62    } catch (error) {
63      strapi.log.error(
64        `Can't enable module ${moduleProduct.name} for event ${eventUuid}: ${error}`
65      );
66    }
67  },
68});
69
70const getModuleProduct = async (paymentLink: string) => {
71  const modulesConfig = await strapi.entityService.findOne(
72    "api::module.module",
73    1
74  );
75  const modules = [];
76  if (modulesConfig.caroster_plus_enabled) {
77    modules.push([
78      modulesConfig.caroster_plus_payment_link_id,
79      { name: "caroster-plus", notificationType: "EnabledCarosterPlus" },
80    ]);
81  }
82  return Object.fromEntries(modules)[paymentLink];
83};