Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zomars/cal 884 paid events not sending the link #7318

Merged
merged 6 commits into from
Feb 25, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/app-store/stripepayment/lib/PaymentService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export class PaymentService implements IAbstractPaymentService {
amount: payment.amount,
currency: this.credentials.default_currency,
payment_method_types: ["card"],
application_fee_amount: paymentFee,
// application_fee_amount: paymentFee,
};

const paymentIntent = await this.stripe.paymentIntents.create(params, {
Expand Down Expand Up @@ -89,7 +89,7 @@ export class PaymentService implements IAbstractPaymentService {
stripe_publishable_key: this.credentials.stripe_publishable_key,
stripeAccount: this.credentials.stripe_user_id,
}) as unknown as Prisma.InputJsonValue,
fee: paymentFee,
fee: 0,
zomars marked this conversation as resolved.
Show resolved Hide resolved
refunded: false,
success: false,
},
Expand Down
8 changes: 4 additions & 4 deletions packages/core/EventManager.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DestinationCalendar } from "@prisma/client";
import type { DestinationCalendar } from "@prisma/client";
import merge from "lodash/merge";
import { v5 as uuidv5 } from "uuid";
import { z } from "zod";
import type { z } from "zod";

import { FAKE_DAILY_CREDENTIAL } from "@calcom/app-store/dailyvideo/lib/VideoApiAdapter";
import { getEventLocationTypeFromApp } from "@calcom/app-store/locations";
Expand All @@ -10,7 +10,7 @@ import getApps from "@calcom/app-store/utils";
import prisma from "@calcom/prisma";
import { createdEventSchema } from "@calcom/prisma/zod-utils";
import type { AdditionalInformation, CalendarEvent, NewCalendarEventType } from "@calcom/types/Calendar";
import { CredentialPayload, CredentialWithAppName } from "@calcom/types/Credential";
import type { CredentialPayload, CredentialWithAppName } from "@calcom/types/Credential";
import type { Event } from "@calcom/types/Event";
import type {
CreateUpdateResult,
Expand Down Expand Up @@ -59,7 +59,7 @@ export const processLocation = (event: CalendarEvent): CalendarEvent => {
return event;
};

type EventManagerUser = {
export type EventManagerUser = {
credentials: CredentialPayload[];
destinationCalendar: DestinationCalendar | null;
};
Expand Down
241 changes: 241 additions & 0 deletions packages/features/bookings/lib/handleConfirmation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
import type { PrismaClient, Workflow, WorkflowsOnEventTypes, WorkflowStep } from "@prisma/client";
import { BookingStatus, WebhookTriggerEvents } from "@prisma/client";

import { scheduleTrigger } from "@calcom/app-store/zapier/lib/nodeScheduler";
import type { EventManagerUser } from "@calcom/core/EventManager";
import EventManager from "@calcom/core/EventManager";
import { sendScheduledEmails } from "@calcom/emails";
import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/reminders/reminderScheduler";
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import sendPayload from "@calcom/features/webhooks/lib/sendPayload";
import logger from "@calcom/lib/logger";
import type { AdditionalInformation, CalendarEvent } from "@calcom/types/Calendar";

const log = logger.getChildLogger({ prefix: ["[handleConfirmation] book:user"] });

export async function handleConfirmation(args: {
user: EventManagerUser & { username: string | null };
evt: CalendarEvent;
recurringEventId?: string;
prisma: PrismaClient;
bookingId: number;
booking: {
eventType: {
currency: string;
description: string | null;
id: number;
length: number;
price: number;
requiresConfirmation: boolean;
title: string;
} | null;
eventTypeId: number | null;
smsReminderNumber: string | null;
userId: number | null;
};
paid?: boolean;
}) {
const { user, evt, recurringEventId, prisma, bookingId, booking, paid } = args;
const eventManager = new EventManager(user);
const scheduleResult = await eventManager.create(evt);
const results = scheduleResult.results;

if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
errorCode: "BookingCreatingMeetingFailed",
message: "Booking failed",
};

log.error(`Booking ${user.username} failed`, error, results);
} else {
const metadata: AdditionalInformation = {};

if (results.length) {
// TODO: Handle created event metadata more elegantly
metadata.hangoutLink = results[0].createdEvent?.hangoutLink;
metadata.conferenceData = results[0].createdEvent?.conferenceData;
metadata.entryPoints = results[0].createdEvent?.entryPoints;
}
try {
await sendScheduledEmails({ ...evt, additionalInformation: metadata });
} catch (error) {
log.error(error);
}
}
let updatedBookings: {
scheduledJobs: string[];
id: number;
startTime: Date;
endTime: Date;
uid: string;
smsReminderNumber: string | null;
eventType: {
workflows: (WorkflowsOnEventTypes & {
workflow: Workflow & {
steps: WorkflowStep[];
};
})[];
} | null;
}[] = [];

if (recurringEventId) {
// The booking to confirm is a recurring event and comes from /booking/recurring, proceeding to mark all related
// bookings as confirmed. Prisma updateMany does not support relations, so doing this in two steps for now.
const unconfirmedRecurringBookings = await prisma.booking.findMany({
where: {
recurringEventId,
status: BookingStatus.PENDING,
},
});

const updateBookingsPromise = unconfirmedRecurringBookings.map((recurringBooking) =>
prisma.booking.update({
where: {
id: recurringBooking.id,
},
data: {
status: BookingStatus.ACCEPTED,
references: {
create: scheduleResult.referencesToCreate,
},
paid,
},
select: {
eventType: {
select: {
workflows: {
include: {
workflow: {
include: {
steps: true,
},
},
},
},
},
},
uid: true,
startTime: true,
endTime: true,
smsReminderNumber: true,
id: true,
scheduledJobs: true,
},
})
);
const updatedBookingsResult = await Promise.all(updateBookingsPromise);
updatedBookings = updatedBookings.concat(updatedBookingsResult);
} else {
// @NOTE: be careful with this as if any error occurs before this booking doesn't get confirmed
// Should perform update on booking (confirm) -> then trigger the rest handlers
const updatedBooking = await prisma.booking.update({
where: {
id: bookingId,
},
data: {
status: BookingStatus.ACCEPTED,
references: {
create: scheduleResult.referencesToCreate,
},
},
select: {
eventType: {
select: {
workflows: {
include: {
workflow: {
include: {
steps: true,
},
},
},
},
},
},
uid: true,
startTime: true,
endTime: true,
smsReminderNumber: true,
id: true,
scheduledJobs: true,
},
});
updatedBookings.push(updatedBooking);
}

//Workflows - set reminders for confirmed events
try {
for (let index = 0; index < updatedBookings.length; index++) {
if (updatedBookings[index].eventType?.workflows) {
const evtOfBooking = evt;
evtOfBooking.startTime = updatedBookings[index].startTime.toISOString();
evtOfBooking.endTime = updatedBookings[index].endTime.toISOString();
evtOfBooking.uid = updatedBookings[index].uid;

const isFirstBooking = index === 0;

await scheduleWorkflowReminders(
updatedBookings[index]?.eventType?.workflows || [],
updatedBookings[index].smsReminderNumber,
evtOfBooking,
false,
false,
isFirstBooking
);
}
}
} catch (error) {
// Silently fail
console.error(error);
}

try {
// schedule job for zapier trigger 'when meeting ends'
const subscribersBookingCreated = await getWebhooks({
userId: booking.userId || 0,
eventTypeId: booking.eventTypeId || 0,
triggerEvent: WebhookTriggerEvents.BOOKING_CREATED,
});
const subscribersMeetingEnded = await getWebhooks({
userId: booking.userId || 0,
eventTypeId: booking.eventTypeId || 0,
triggerEvent: WebhookTriggerEvents.MEETING_ENDED,
});

subscribersMeetingEnded.forEach((subscriber) => {
updatedBookings.forEach((booking) => {
scheduleTrigger(booking, subscriber.subscriberUrl, subscriber);
});
});

const eventTypeInfo: EventTypeInfo = {
eventTitle: booking.eventType?.title,
eventDescription: booking.eventType?.description,
requiresConfirmation: booking.eventType?.requiresConfirmation || null,
price: booking.eventType?.price,
currency: booking.eventType?.currency,
length: booking.eventType?.length,
};

const promises = subscribersBookingCreated.map((sub) =>
sendPayload(sub.secret, WebhookTriggerEvents.BOOKING_CREATED, new Date().toISOString(), sub, {
...evt,
...eventTypeInfo,
bookingId,
eventTypeId: booking.eventType?.id,
status: "ACCEPTED",
smsReminderNumber: booking.smsReminderNumber || undefined,
}).catch((e) => {
console.error(
`Error executing webhook for event: ${WebhookTriggerEvents.BOOKING_CREATED}, URL: ${sub.subscriberUrl}`,
e
);
})
);
await Promise.all(promises);
} catch (error) {
// Silently fail
console.error(error);
}
}
44 changes: 29 additions & 15 deletions packages/features/ee/payments/api/webhook.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { BookingStatus, Prisma } from "@prisma/client";
import { BookingStatus } from "@prisma/client";
import type { Prisma } from "@prisma/client";
import { buffer } from "micro";
import type { NextApiRequest, NextApiResponse } from "next";
import Stripe from "stripe";
import type Stripe from "stripe";

import stripe from "@calcom/app-store/stripepayment/lib/server";
import EventManager from "@calcom/core/EventManager";
import { sendScheduledEmails } from "@calcom/emails";
import { handleConfirmation } from "@calcom/features/bookings/lib/handleConfirmation";
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
import { IS_PRODUCTION } from "@calcom/lib/constants";
import { getErrorFromUnknown } from "@calcom/lib/errors";
Expand All @@ -20,6 +22,18 @@ export const config = {
},
};

async function getEventType(id: number) {
return prisma.eventType.findUnique({
where: {
id,
},
select: {
recurringEvent: true,
requiresConfirmation: true,
},
});
}

async function handlePaymentSuccess(event: Stripe.Event) {
const paymentIntent = event.data.object as Stripe.PaymentIntent;
const payment = await prisma.payment.findFirst({
Expand All @@ -42,6 +56,8 @@ async function handlePaymentSuccess(event: Stripe.Event) {
},
select: {
...bookingMinimalSelect,
eventType: true,
smsReminderNumber: true,
location: true,
eventTypeId: true,
userId: true,
Expand All @@ -52,6 +68,7 @@ async function handlePaymentSuccess(event: Stripe.Event) {
user: {
select: {
id: true,
username: true,
credentials: true,
timeZone: true,
email: true,
Expand All @@ -63,22 +80,14 @@ async function handlePaymentSuccess(event: Stripe.Event) {
},
});

console.log("booking", JSON.stringify(booking));
zomars marked this conversation as resolved.
Show resolved Hide resolved

if (!booking) throw new HttpCode({ statusCode: 204, message: "No booking found" });

const eventTypeSelect = Prisma.validator<Prisma.EventTypeSelect>()({
recurringEvent: true,
requiresConfirmation: true,
});
const eventTypeData = Prisma.validator<Prisma.EventTypeArgs>()({ select: eventTypeSelect });
type EventTypeRaw = Prisma.EventTypeGetPayload<typeof eventTypeData>;
type EventTypeRaw = Awaited<ReturnType<typeof getEventType>>;
let eventTypeRaw: EventTypeRaw | null = null;
if (booking.eventTypeId) {
eventTypeRaw = await prisma.eventType.findUnique({
where: {
id: booking.eventTypeId,
},
select: eventTypeSelect,
});
eventTypeRaw = await getEventType(booking.eventTypeId);
}

const { user } = booking;
Expand Down Expand Up @@ -131,6 +140,7 @@ async function handlePaymentSuccess(event: Stripe.Event) {
const eventManager = new EventManager(user);
const scheduleResult = await eventManager.create(evt);
bookingData.references = { create: scheduleResult.referencesToCreate };
scheduleResult.results;
}

if (eventTypeRaw?.requiresConfirmation) {
Expand All @@ -155,7 +165,11 @@ async function handlePaymentSuccess(event: Stripe.Event) {

await prisma.$transaction([paymentUpdate, bookingUpdate]);

await sendScheduledEmails({ ...evt });
if (!isConfirmed && !eventTypeRaw?.requiresConfirmation) {
hariombalhara marked this conversation as resolved.
Show resolved Hide resolved
await handleConfirmation({ user, evt, prisma, bookingId: booking.id, booking, paid: true });
} else {
await sendScheduledEmails({ ...evt });
Copy link
Member

@hariombalhara hariombalhara Feb 24, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How is the case where isConfirmed is false and event requires confirmation? sendScheduledEmails seem to send confirmed booking emails only.

I will test the flow too, I don't have clear picture of how everything is handled.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the booking is not already confirmed and doesn't require confirmation. I didn't want to modify too much the current logic

}

throw new HttpCode({
statusCode: 200,
Expand Down
Loading