* fix timezone display on booking page to reflect event availability timezone * migrate fetching event owner's schedule to server side * migrate fetching event owner's schedule to server side * fix e2e test errors * Add WEBAPP_URL_FOR_OAUTH to salesforce auth * In event manager constructor include "_crm" credentials as calendar creds * Change crm apps to type to end with `_crm` * Move sendgrid out of CRM * Add zoho bigin to CRM apps * When getting apps, use slug * Add `crm` variants * Hubspot Oauth use `WEBAPP_URL_FOR_OAUTH` * Refactor creating credentials * Fix empty CRM page * Use credentials with `_crm` * Abstract getAppCategoryTitle * Add integration.handler changes * Init crmManager * Change salesforce to CrmService * Create crmManager * Create contact on new event * Create event * Create new CRM reference * - Fix create new contact for salesforce - Add reschedule to crmManager * Create deleteAllCRMEvents * When searching for credential, look for current credentials in class * On cancel, delete 3rd party events * Add delete method * Type fix * Type fix * Convert Close.com to CrmService * Convert Close.com to CrmService * Move hubspot to CrmService * Convert Pipedrive to CrmService * Rename classes to CrmService * Move ZohoCrm to CrmService * Move Bigin to CrmService * Type return for CrmServices * Fix type errors * Close.com create leads and contacts * Fix tests * Type fix * Zoho bug fixes * Clean up * Type fixes * Remove apiDeletes * Type fixes * Specific typing * Type fix * Type fix * Type fix * Type fix * Type fix * feat: Enable CRM apps on a per event type basis (#14450) * Add Salesforce to be an event type app * Handle new booking, only get enabled CRM credentials * Abstract generating search params * Add close.com to event type * Clean up * Move hubspot to event type * Add pipedrive to event type * Add zoho bigin to event type * Add zoho crm to event type * Remove console.log * Add deleting CRM apps from event type * Delete event type apps * Fix deleting credentials * Add CRM app data to event type metadata * Backwards compatibility: add CRM credential if doesn't exist on event type * Don't include user CRM credentials for backwards comp * Backwards compatibility show CRM app is enabled and dirty field * Clean up * Type fixes * Type fixes * Type fix * Type fix * Remove console.log * Test fix * Upgrade embed-react vite version - dev * Change build can't find error message * Add back omni install prop * Clean up * Refactor `writeAppDataToEventType` * Use eventType repository in writeAppDataToEventType * Clean up old comments * Add error logging * createCRMEvents pass event uid as created event uid * Use `getUid` * Clean up props in create crm event * Small changes to `crmManager` * Fix zoho CRM * refactor crmManager * Undo vite config change * Fix teamId query * Fix bigin error * Remove need for `writeAppDataToEventType` * Add `getAllCredentials` test * Add crmManager tests * Type fixes * Fix type errors * Fix getAllCredentials test * Fix tests * Skip CRM manager tests for now * feat: Skip RR Assignment if Contact Exists In Salesforce (#14556) Co-authored-by: CarinaWolli <[email protected]> * Update yarn.lock * @zomars feedback - use new URL for state params * fix: update hook to not produce enabled === undefined * fix: update app card interfaces to use the new enabled from useIsAppEnabled * fix: feedback for crm RR skip (#15160) * code clean up * fix type any * test setup for RR lead skip * code clean up * simplify code * type error * finshed first test for RR lead skip * add seconds test * add test for handleNewBooking * test if teamMember is set * fix missing enabled key * fix tests * fix type error * use setSystemTime instead of getDate * remove nested if --------- Co-authored-by: CarinaWolli <[email protected]> * fix type error * fix: remove app metadata from all eventTypes on deleting the app * fix: update hook to not produce enabled === undefined (default to false) --------- Co-authored-by: Shaik-Sirajuddin <sirajuddinshaik30gmail.com> Co-authored-by: Shaik-Sirajuddin <[email protected]> Co-authored-by: Shaik-Sirajuddin <[email protected]> Co-authored-by: sean-brydon <[email protected]> Co-authored-by: Omar López <[email protected]> Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: sean-brydon <[email protected]> Co-authored-by: Carina Wollendorfer <[email protected]> Co-authored-by: Somay Chauhan <[email protected]>
331 lines
11 KiB
TypeScript
331 lines
11 KiB
TypeScript
import type { TokenResponse } from "jsforce";
|
|
import jsforce from "jsforce";
|
|
import { RRule } from "rrule";
|
|
import { z } from "zod";
|
|
|
|
import { getLocation } from "@calcom/lib/CalEventParser";
|
|
import { WEBAPP_URL } from "@calcom/lib/constants";
|
|
import { HttpError } from "@calcom/lib/http-error";
|
|
import logger from "@calcom/lib/logger";
|
|
import { prisma } from "@calcom/prisma";
|
|
import type { CalendarEvent } from "@calcom/types/Calendar";
|
|
import type { CredentialPayload } from "@calcom/types/Credential";
|
|
import type { CRM, Contact, CrmEvent } from "@calcom/types/CrmService";
|
|
|
|
import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug";
|
|
import type { ParseRefreshTokenResponse } from "../../_utils/oauth/parseRefreshTokenResponse";
|
|
import parseRefreshTokenResponse from "../../_utils/oauth/parseRefreshTokenResponse";
|
|
|
|
type ExtendedTokenResponse = TokenResponse & {
|
|
instance_url: string;
|
|
};
|
|
|
|
type ContactSearchResult = {
|
|
attributes: {
|
|
type: string;
|
|
url: string;
|
|
};
|
|
Id: string;
|
|
Email: string;
|
|
};
|
|
|
|
const sfApiErrors = {
|
|
INVALID_EVENTWHOIDS: "INVALID_FIELD: No such column 'EventWhoIds' on sobject of type Event",
|
|
};
|
|
|
|
type ContactRecord = {
|
|
Id: string;
|
|
Email: string;
|
|
OwnerId: string;
|
|
[key: string]: any;
|
|
};
|
|
|
|
const salesforceTokenSchema = z.object({
|
|
id: z.string(),
|
|
issued_at: z.string(),
|
|
instance_url: z.string(),
|
|
signature: z.string(),
|
|
access_token: z.string(),
|
|
scope: z.string(),
|
|
token_type: z.string(),
|
|
});
|
|
|
|
export default class SalesforceCRMService implements CRM {
|
|
private integrationName = "";
|
|
private conn: Promise<jsforce.Connection>;
|
|
private log: typeof logger;
|
|
private calWarnings: string[] = [];
|
|
|
|
constructor(credential: CredentialPayload) {
|
|
this.integrationName = "salesforce_other_calendar";
|
|
this.conn = this.getClient(credential).then((c) => c);
|
|
this.log = logger.getSubLogger({ prefix: [`[[lib] ${this.integrationName}`] });
|
|
}
|
|
|
|
private getClient = async (credential: CredentialPayload) => {
|
|
let consumer_key = "";
|
|
let consumer_secret = "";
|
|
|
|
const appKeys = await getAppKeysFromSlug("salesforce");
|
|
if (typeof appKeys.consumer_key === "string") consumer_key = appKeys.consumer_key;
|
|
if (typeof appKeys.consumer_secret === "string") consumer_secret = appKeys.consumer_secret;
|
|
if (!consumer_key)
|
|
throw new HttpError({ statusCode: 400, message: "Salesforce consumer key is missing." });
|
|
if (!consumer_secret)
|
|
throw new HttpError({ statusCode: 400, message: "Salesforce consumer secret missing." });
|
|
|
|
const credentialKey = credential.key as unknown as ExtendedTokenResponse;
|
|
|
|
try {
|
|
/* XXX: This code results in 'Bad Request', which indicates something is wrong with our salesforce integration.
|
|
Needs further investigation ASAP */
|
|
const response = await fetch("https://login.salesforce.com/services/oauth2/token", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
},
|
|
body: new URLSearchParams({
|
|
grant_type: "refresh_token",
|
|
client_id: consumer_key,
|
|
client_secret: consumer_secret,
|
|
refresh_token: credentialKey.refresh_token,
|
|
}),
|
|
});
|
|
if (!response.ok) {
|
|
const message = `${response.statusText}: ${JSON.stringify(await response.json())}`;
|
|
throw new Error(message);
|
|
}
|
|
|
|
const accessTokenJson = await response.json();
|
|
|
|
const accessTokenParsed: ParseRefreshTokenResponse<typeof salesforceTokenSchema> =
|
|
parseRefreshTokenResponse(accessTokenJson, salesforceTokenSchema);
|
|
|
|
await prisma.credential.update({
|
|
where: { id: credential.id },
|
|
data: { key: { ...accessTokenParsed, refresh_token: credentialKey.refresh_token } },
|
|
});
|
|
} catch (err: unknown) {
|
|
console.error(err); // log but proceed
|
|
}
|
|
|
|
return new jsforce.Connection({
|
|
clientId: consumer_key,
|
|
clientSecret: consumer_secret,
|
|
redirectUri: `${WEBAPP_URL}/api/integrations/salesforce/callback`,
|
|
instanceUrl: credentialKey.instance_url,
|
|
accessToken: credentialKey.access_token,
|
|
refreshToken: credentialKey.refresh_token,
|
|
});
|
|
};
|
|
|
|
private getSalesforceUserFromEmail = async (email: string) => {
|
|
const conn = await this.conn;
|
|
return await conn.query(`SELECT Id, Email FROM User WHERE Email = '${email}'`);
|
|
};
|
|
|
|
private getSalesforceUserFromOwnerId = async (ownerId: string) => {
|
|
const conn = await this.conn;
|
|
return await conn.query(`SELECT Id, Email FROM User WHERE Id = '${ownerId}'`);
|
|
};
|
|
|
|
private getSalesforceEventBody = (event: CalendarEvent): string => {
|
|
return `${event.organizer.language.translate("invitee_timezone")}: ${
|
|
event.attendees[0].timeZone
|
|
} \r\n\r\n ${event.organizer.language.translate("share_additional_notes")}\r\n${
|
|
event.additionalNotes || "-"
|
|
}`;
|
|
};
|
|
|
|
private salesforceCreateEventApiCall = async (
|
|
event: CalendarEvent,
|
|
options: { [key: string]: unknown }
|
|
) => {
|
|
const conn = await this.conn;
|
|
return await conn.sobject("Event").create({
|
|
StartDateTime: new Date(event.startTime).toISOString(),
|
|
EndDateTime: new Date(event.endTime).toISOString(),
|
|
Subject: event.title,
|
|
Description: this.getSalesforceEventBody(event),
|
|
Location: getLocation(event),
|
|
...options,
|
|
...(event.recurringEvent && {
|
|
IsRecurrence2: true,
|
|
Recurrence2PatternText: new RRule(event.recurringEvent).toString(),
|
|
}),
|
|
});
|
|
};
|
|
|
|
private salesforceCreateEvent = async (event: CalendarEvent, contacts: Contact[]) => {
|
|
const createdEvent = await this.salesforceCreateEventApiCall(event, {
|
|
EventWhoIds: contacts.map((contact) => contact.id),
|
|
}).catch(async (reason) => {
|
|
if (reason === sfApiErrors.INVALID_EVENTWHOIDS) {
|
|
this.calWarnings.push(
|
|
`Please enable option "Allow Users to Relate Multiple Contacts to Tasks and Events" under
|
|
"Setup > Feature Settings > Sales > Activity Settings" to be able to create events with
|
|
multiple contact attendees.`
|
|
);
|
|
// User has not configured "Allow Users to Relate Multiple Contacts to Tasks and Events"
|
|
// proceeding to create the event using just the first attendee as the primary WhoId
|
|
return await this.salesforceCreateEventApiCall(event, {
|
|
WhoId: contacts[0],
|
|
});
|
|
} else {
|
|
return Promise.reject();
|
|
}
|
|
});
|
|
return createdEvent;
|
|
};
|
|
|
|
private salesforceUpdateEvent = async (uid: string, event: CalendarEvent) => {
|
|
const conn = await this.conn;
|
|
return await conn.sobject("Event").update({
|
|
Id: uid,
|
|
StartDateTime: new Date(event.startTime).toISOString(),
|
|
EndDateTime: new Date(event.endTime).toISOString(),
|
|
Subject: event.title,
|
|
Description: this.getSalesforceEventBody(event),
|
|
Location: getLocation(event),
|
|
...(event.recurringEvent && {
|
|
IsRecurrence2: true,
|
|
Recurrence2PatternText: new RRule(event.recurringEvent).toString(),
|
|
}),
|
|
});
|
|
};
|
|
|
|
private salesforceDeleteEvent = async (uid: string) => {
|
|
const conn = await this.conn;
|
|
return await conn.sobject("Event").delete(uid);
|
|
};
|
|
|
|
async handleEventCreation(event: CalendarEvent, contacts: Contact[]) {
|
|
const sfEvent = await this.salesforceCreateEvent(event, contacts);
|
|
if (sfEvent.success) {
|
|
this.log.debug("event:creation:ok", { sfEvent });
|
|
return Promise.resolve({
|
|
uid: sfEvent.id,
|
|
id: sfEvent.id,
|
|
type: "salesforce_other_calendar",
|
|
password: "",
|
|
url: "",
|
|
additionalInfo: { contacts, sfEvent, calWarnings: this.calWarnings },
|
|
});
|
|
}
|
|
this.log.debug("event:creation:notOk", { event, sfEvent, contacts });
|
|
return Promise.reject({
|
|
calError: "Something went wrong when creating an event in Salesforce",
|
|
});
|
|
}
|
|
|
|
async createEvent(event: CalendarEvent, contacts: Contact[]): Promise<CrmEvent> {
|
|
const sfEvent = await this.salesforceCreateEvent(event, contacts);
|
|
if (sfEvent.success) {
|
|
return Promise.resolve({
|
|
uid: sfEvent.id,
|
|
id: sfEvent.id,
|
|
type: "salesforce_other_calendar",
|
|
password: "",
|
|
url: "",
|
|
additionalInfo: { contacts, sfEvent, calWarnings: this.calWarnings },
|
|
});
|
|
}
|
|
this.log.debug("event:creation:notOk", { event, sfEvent, contacts });
|
|
return Promise.reject("Something went wrong when creating an event in Salesforce");
|
|
}
|
|
|
|
async updateEvent(uid: string, event: CalendarEvent): Promise<CrmEvent> {
|
|
const updatedEvent = await this.salesforceUpdateEvent(uid, event);
|
|
if (updatedEvent.success) {
|
|
return Promise.resolve({
|
|
uid: updatedEvent.id,
|
|
id: updatedEvent.id,
|
|
type: "salesforce_other_calendar",
|
|
password: "",
|
|
url: "",
|
|
additionalInfo: { calWarnings: this.calWarnings },
|
|
});
|
|
} else {
|
|
return Promise.reject({ calError: "Something went wrong when updating the event in Salesforce" });
|
|
}
|
|
}
|
|
|
|
public async deleteEvent(uid: string) {
|
|
const deletedEvent = await this.salesforceDeleteEvent(uid);
|
|
if (deletedEvent.success) {
|
|
Promise.resolve();
|
|
} else {
|
|
Promise.reject({ calError: "Something went wrong when deleting the event in Salesforce" });
|
|
}
|
|
}
|
|
|
|
async getContacts(email: string | string[], includeOwner?: boolean) {
|
|
const conn = await this.conn;
|
|
const emails = Array.isArray(email) ? email : [email];
|
|
const soql = `SELECT Id, Email, OwnerId FROM Contact WHERE Email IN ('${emails.join("','")}')`;
|
|
const results = await conn.query(soql);
|
|
|
|
if (!results || !results.records.length) return [];
|
|
|
|
const records = results.records as ContactRecord[];
|
|
|
|
if (includeOwner) {
|
|
const ownerIds: Set<string> = new Set();
|
|
records.forEach((record) => {
|
|
ownerIds.add(record.OwnerId);
|
|
});
|
|
|
|
const ownersQuery = (await Promise.all(
|
|
Array.from(ownerIds).map(async (ownerId) => {
|
|
return this.getSalesforceUserFromOwnerId(ownerId);
|
|
})
|
|
)) as { records: ContactRecord[] }[];
|
|
const contactsWithOwners = records.map((record) => {
|
|
const ownerEmail = ownersQuery.find((user) => user.records[0].Id === record.OwnerId)?.records[0]
|
|
.Email;
|
|
return { id: record.Id, email: record.Email, ownerId: record.OwnerId, ownerEmail };
|
|
});
|
|
return contactsWithOwners;
|
|
}
|
|
|
|
return records
|
|
? records.map((record) => ({
|
|
id: record.Id,
|
|
email: record.Email,
|
|
}))
|
|
: [];
|
|
}
|
|
|
|
async createContacts(contactsToCreate: { email: string; name: string }[], organizerEmail?: string) {
|
|
const conn = await this.conn;
|
|
|
|
// See if the organizer exists in the CRM
|
|
let organizerId: string;
|
|
if (organizerEmail) {
|
|
const userQuery = await this.getSalesforceUserFromEmail(organizerEmail);
|
|
if (userQuery) {
|
|
organizerId = (userQuery.records[0] as { Email: string; Id: string }).Id;
|
|
}
|
|
}
|
|
const createdContacts = await Promise.all(
|
|
contactsToCreate.map(async (attendee) => {
|
|
const [FirstName, LastName] = attendee.name ? attendee.name.split(" ") : [attendee.email, ""];
|
|
return await conn
|
|
.sobject("Contact")
|
|
.create({
|
|
FirstName,
|
|
LastName: LastName || "-",
|
|
Email: attendee.email,
|
|
...(organizerId && { OwnerId: organizerId }),
|
|
})
|
|
.then((result) => {
|
|
if (result.success) {
|
|
return { id: result.id, email: attendee.email };
|
|
}
|
|
});
|
|
})
|
|
);
|
|
return createdContacts.filter((contact): contact is Contact => contact !== undefined);
|
|
}
|
|
}
|