all repos — caroster @ e3dd820256e0c4ea2c317a33c8fc29f9a83f3711

[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 },
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: moduleProduct.notificationType,
56            event,
57            user: event.creator,
58          },
59        });
60    } catch (error) {
61      strapi.log.error(
62        `Can't enable module ${moduleProduct.name} for event ${eventUuid}: ${error}`
63      );
64    }
65  },
66});
67
68const getModuleProduct = async (paymentLink: string) => {
69  const modulesConfig = await strapi.entityService.findOne(
70    "api::module.module",
71    1
72  );
73  const modules = [];
74  if (modulesConfig.caroster_plus_enabled) {
75    modules.push([
76      modulesConfig.caroster_plus_payment_link_id,
77      { name: "caroster-plus", notificationType: "EnabledCarosterPlus" },
78    ]);
79  }
80  return Object.fromEntries(modules)[paymentLink];
81};