fix: Handle calendar-cache with Delegation Credentials
Fixes CAL-5372 # Delegation Credentials with CalendarCache. Following content is a snapshot of the [internal document](https://calendso.slack.com/docs/T08B8KA2BNF/F08L5JYU3V3) **Problem-1 :** CalendarCache needs SelectedCalendar records to work but SelectedCalendar record is only created when a user connects their calendar and then enables some calendar for conflict checking. Because with Delegation, no manual connection is done by any of the members, we need a way to create SelectedCalendar records automatically. **Problem-2** CalendarCache connects to credential(regular credential) which doesn’t exist for Delegation Credential scenario. Also, DelegationCredential is common for all the members(different from Credential which is different for different members) of the organization and we need to identify to which user the CalendarCache belongs. **Solution for both problems** - Create credential records for Delegation Credentials as well - Through Cron(new - we could schedule it every 5mins) - Now create SelectedCalendar records for those Credential records - Through another Cron(new - we could schedule it every 5mins) - Now CalendarCache records will automatically be created for those SelectedCalendar records -existing cron ## Fixed some Delegation Credentials bugs unrelated to calendar-cache - If DestinationCalendar wasn't set(which is possible only with Delegation Credentials), then Google Meet wasn't used as a conferencing app - [Added a test] - If no SelectedCalendar is there but Google Calendar connection exists(possible only with Delegation Credential) then we were not doing conflict checking. It is expected to not do it for Regular Credentials, but for Delegation Credential we must check for conflict in that case too [Added a test] - Earlier if a user has Regular Credential as well as Delegation Credential for the same external id which is the member email(say [email protected]) then availability were retrieved twice because we weren't deduplicating credentials as it wasn't a trivial thing to do. Now that is being done. **Env Variables:** Note this PR doesn't introduce any new env variable. The existing env variable has been added to .env.example. But if this env variable isn't already set, it must be set. `CALCOM_SERVICE_ACCOUNT_ENCRYPTION_KEY={SAME_AS_SET_FOR_V2_API}` **Deployment Plan:** 1. Add Observability for SelectedCalendar when _error_ field is set 2. Follow https://github.com/calcom/cal.com/blob/calendar-cache-dwd-support/apps/web/app/(use-page-wrapper)/settings/(settings-layout)/organizations/delegation-credential/delegation-credential.md#setting-up-delegation-credential-for-google-calendar-api to enable Delegation Credential for i.cal.com 3. Note that to be able to see the option to enable Delegation Credential for an organization, you need to enable `teamFeature` and `feature` for `delegation-credential` ## Automation Tests - Introduced tests for calendar-cache.repository.ts - Tests all methods of the repository - Added more tests for handleNewBooking/delegation-credential flow. - Added test to verify the bug fix when no DestinationCalendar exists and Google Meet should be used still - Added more tests for Google Calendar/CalendarService targeting DelegationCredential - Added more tests for getCalendarsEvents. - To test the new logic of calling getAvailability still if there are no selectedCalendars in case of Delegation Credential - Also introduced tests for `getAvailabitlityWithTimezones` which was an existing function but now has some new changes. - Added tests for deduplication logic in CalendarManager.ts ## How to Test Enable Calendar Cache and Delegation Credential feature for acme org through `features` and `teamFeatures` tables. - Enable Delegation Credential for acme org - Enable atleast 1 calendar for conflict checking for one of the users(say owner1) - Ensure GOOGLE_WEBHOOK_TOKEN is set in .env file - Ensure GOOGLE_WEBHOOK_URL is set to ngrok url of webapp in .env file - Hit cron endpoint `curl http://localhost:3000/api/calendar-cache/cron\?apiKey\={API_KEY}` that would cache the freebusy result for the selected calendars Followup - https://github.com/calcom/cal.com/pull/20698 - https://github.com/calcom/cal.com/pull/18619/files#r2046795643
This commit is contained in:
1 parent
17f1932467
commit
e3bd90c4f2
55 files changed
+3409
-629
No files matched your search
+124
@@ -0,0 +1,124 @@
|
||||
# Delegation Credentials
|
||||
|
||||
## Setting up Delegation Credential for Google Calendar API
|
||||
|
||||
Step 1: Create a Google Cloud Project
|
||||
|
||||
Before you can create a service account, you'll need to set up a Google Cloud project.
|
||||
|
||||
1. Create a Google Cloud Project:
|
||||
- Go to the Google Cloud Console
|
||||
- Select Create Project
|
||||
- Give your project a name and select your billing account (if applicable)
|
||||
- Click Create
|
||||
2. Enable the Google Calendar API:
|
||||
1. Go to the Google Cloud Console
|
||||
2. Select API & Services → Library
|
||||
3. Search for "Google Calendar API"
|
||||
4. Click Enable
|
||||
|
||||
Step 2: Create a Service Account
|
||||
|
||||
A service account is needed to act on behalf of users
|
||||
|
||||
1. Navigate to the Service Accounts page:
|
||||
- In the Google Cloud Console, go to IAM & Admin → Service Accounts
|
||||
2. Create a New Service Account:
|
||||
- Click on Create Service Account
|
||||
- Give your service account a name and description
|
||||
- Click Create and Continue
|
||||
|
||||
Step 3: To Be taken by Cal.com instance admin:
|
||||
|
||||
- Create a Workspace Platform with slug="google". Slug has to be exactly this. This is how we know we need to use Google Calendar and Google Meet.
|
||||
|
||||
Last Step (To Be Taken By Cal.com organization Owner/Admin): Assign Specific API Permissions via OAuth Scopes:
|
||||
- Create Delegation Credential with workspace platform "google"
|
||||
- User must be a member of the Google Workspace to be able to enable Delegation Credential as there is a validation if the user's calendar can be accessed through the service account
|
||||
- Get the Client ID from there
|
||||
- Go to your Google Admin Console (admin-google-com)
|
||||
- Navigate to Security → Access and Data Controls -> API controls -> Manage Domain-Wide Delegation
|
||||
- Here, you'll authorize the Client ID(Unique ID) to access the Google Calendar API
|
||||
- Add the necessary API scopes for Google Calendar(Full access to Google Calendar)
|
||||
<https://www.googleapis.com/auth/calendar>
|
||||
|
||||
## Onboarding Improvements
|
||||
|
||||
- Just adding a member to the organization would do the following:
|
||||
- Member to receive events in their calendar, even if they don't login to their account and complete the onboarding process.
|
||||
- The booking location would be Google Meet, even if the user hasn't set it as default(Though Cal Video would show up as default, but we still use Google Meet in this case. We will fix it later.)
|
||||
- It would still not use their calendar for conflict checking, but user can complete the onboarding(just select one calendar there for conflict checking)
|
||||
- Onboarding process: Google Calendar is pre-installed for any new member of the organization(assuming the user has an email of the Delegation Credential domain) and Destination Calendar and Selected Calendar are configurable. On next step, Google Meet is pre-installed and shown at the top and could be set as default.
|
||||
|
||||
## Restrictions after enabling Delegation Credential
|
||||
|
||||
- Enabling Delegation Credential for a particular workspace in Cal.com(only google/outlook supported at the moment) disables the user from disconnecting that credential.
|
||||
|
||||
## Who can create Delegation Credential and enable it?
|
||||
|
||||
- Only the owner/admin of the organization can create Delegation Credential
|
||||
- Only the owner/admin of the organization can enable the created Delegation Credential. Following additional requirements are there:
|
||||
- The client ID must be added to the Google Admin Console
|
||||
- The user's email must be a member of the Google Workspace
|
||||
- The user's email must be verified.
|
||||
|
||||
## Disabling Delegation Credential
|
||||
|
||||
- Disabling Delegation **Credential** maintains the user's preferences in terms of SelectedCalendars and DestinationCalendar.
|
||||
|
||||
## Developer Notes
|
||||
|
||||
### Terminology
|
||||
|
||||
- Delegation Credential: A Delegation Credential service account key along with user's email becomes the Delegation Credential which is an alternative to regular Credential in DB.
|
||||
- DWD: Domain Wide Delegation
|
||||
- non-dwd credential: Regular credentials that are stored in Credentials table
|
||||
|
||||
### How Delegation Credential works
|
||||
|
||||
- We use the Cal.com user's email to impersonate that user using Delegation Credential(which is just a service account key at the moment)
|
||||
- That gives us read/write permission to get availability of the user and create new events in their calendar.
|
||||
|
||||
### What is a Delegation Credential?
|
||||
|
||||
- A Delegation Credential service account key along with user's email becomes the Delegation Credential which is an alternative to regular Credential in DB.
|
||||
- Delegation Credential doesn't completely replace the regular credentials. Delegation Credential gives access to the cal.com user's email in Google Calendar. So, if the user needs to connect to some other email's calendar, we need to use the regular credentials.
|
||||
|
||||
### Important Points
|
||||
|
||||
- No Credential table entry is created when enabling Delegation Credential. The workspace platform's related apps will be considered as "installed" for the users with email matching dwd domain. An in-memory credential like object is created for this purpose. It allows avoiding creation of thousands of records for all the members of the organization when Delegation Credential is enabled.
|
||||
- Delegation Credential is applicable to Users only.
|
||||
- For team, we don't use Delegation Credential as you can impersonate a user and not team through Delegation Credential. Currently supported apps(Google Calendar and Google Meet) don't support team installation, so we could simply allow enabling Delegation Credential without any issues.
|
||||
- Disabling a workspace platform stops it from being used for any new organizations and also disables any Delegation Credential using the workspace platform from being edited.
|
||||
- It still all existing Delegation Credentials to keep on working
|
||||
- Workspace default service account is unused and is to be removed.
|
||||
|
||||
### How apps/installed loads the credentials
|
||||
|
||||
1. Identify the logged in user's email
|
||||
2. Identify the domainWideDelegations for that email's domain
|
||||
3. Build in-memory credentials for the domainWideDelegations and use them along with the actual credentials(that user might have connected) of the user
|
||||
4. We don't show the non-dwd connected calendar(if there is a corresponding dwd connected calendar). Though we use the non-dwd credentials to identify the selected calendars, for the dwd connected calendar.
|
||||
|
||||
### Impact of disabling Delegation Credential
|
||||
|
||||
Disabling effectively stops generating in-memory delegation user credentials. So, any members who haven't manually connected their Calendar and thus their calendar connections were working only because of Delegation Credential, would have their connections broken.
|
||||
|
||||
#### What would not work correctly ?
|
||||
|
||||
- Calendar won't be checked for conflicts. So, they could get booked at a time when they are marked busy in their calendar.
|
||||
- Cal.com bookings would still be checked for conflicts.
|
||||
- Bookings might not appear in the attendee and host's Google Calendar. Because we would be unable to use the API to create the events in calendar and Google doesn't always add events to calendar automatically based on .ics file alone.
|
||||
- Cal Video would be used as the booking location instead of Google Meet.
|
||||
|
||||
#### What would work correctly ?
|
||||
|
||||
- Bookings would still go through. People relying on Salesforce for booking details, would face no issues.
|
||||
- Cal.com bookings would still be checked for conflicts.
|
||||
|
||||
### Notes when testing locally
|
||||
|
||||
- You need to enable the feature through feature flag.
|
||||
- You could use Acme org and login as <owner1-acme@example.com>
|
||||
- Make sure to change the email of the user above to your workspace owner's email(other member's email might also work). This is necessary otherwise you won't be able to enable Delegation Credential for the organization.
|
||||
- Note: After changing the email, you would have to logout and login again
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
|
||||
|
||||
import { defaultResponderForAppDir } from "../../defaultResponderForAppDir";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["CreateCredentials"] });
|
||||
const batchSizeToCreateCredentials = 100;
|
||||
const validateRequest = (req: NextRequest) => {
|
||||
const url = new URL(req.url);
|
||||
const apiKey = req.headers.get("authorization") || url.searchParams.get("apiKey");
|
||||
if (![process.env.CRON_API_KEY, `Bearer ${process.env.CRON_SECRET}`].includes(`${apiKey}`)) {
|
||||
throw new HttpError({ statusCode: 401, message: "Unauthorized" });
|
||||
}
|
||||
};
|
||||
|
||||
async function handleCreateCredentials() {
|
||||
const delegationCredentials = await DelegationCredentialRepository.findAllEnabledIncludeDelegatedMembers();
|
||||
|
||||
if (!delegationCredentials.length) {
|
||||
return {
|
||||
message: "No enabled delegation credentials found",
|
||||
success: 0,
|
||||
failures: 0,
|
||||
};
|
||||
}
|
||||
let totalSuccess = 0;
|
||||
let totalFailures = 0;
|
||||
for (const delegationCredential of delegationCredentials) {
|
||||
const { workspacePlatform, organization } = delegationCredential;
|
||||
|
||||
if (workspacePlatform.slug !== "google") {
|
||||
log.info(
|
||||
`Skipping credential creation for workspace platform ${workspacePlatform.slug} - only google is supported`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// We can't know by looking at a Credential record in DB, if it has access to the `user.email` calendar in Google Calendar.
|
||||
// It could be a credential of a personal calendar of the same user. So, we can't just reuse any existing credential for the user, we have to check if this specific delegationCredential's UserCredential exists or not
|
||||
const existingCredentials =
|
||||
await CredentialRepository.findAllDelegationByUserIdsListAndDelegationCredentialIdAndType({
|
||||
userIds: organization.delegatedMembers.map((member) => member.userId),
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
type: "google_calendar",
|
||||
});
|
||||
|
||||
const existingCredentialUserIds = new Set(existingCredentials.map((cred) => cred.userId));
|
||||
|
||||
const membersNeedingCredentials = organization.delegatedMembers.filter(
|
||||
(member) => !existingCredentialUserIds.has(member.userId)
|
||||
);
|
||||
|
||||
const toProcessMembers = membersNeedingCredentials.slice(0, batchSizeToCreateCredentials);
|
||||
|
||||
log.info(
|
||||
`Creating credentials for ${toProcessMembers.length} members in organization ${organization.id}`
|
||||
);
|
||||
|
||||
const credentialCreationPromises = toProcessMembers.map(async (member) => {
|
||||
try {
|
||||
await CredentialRepository.create({
|
||||
type: "google_calendar",
|
||||
key: {
|
||||
// The in-memory credential that we create for Delegation Credential has access_token as "NOOP_UNUSED_DELEGATION_TOKEN. This is to mark it is in DB, in case we need to identify that.
|
||||
access_token: "NOOP_UNUSED_DELEGATION_TOKEN_DB",
|
||||
},
|
||||
userId: member.userId,
|
||||
appId: "google-calendar",
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
});
|
||||
log.info(`Created credential for member ${member.userId}`);
|
||||
} catch (error) {
|
||||
log.error(`Error creating credential for member ${member.userId}:`, error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
const results = await Promise.allSettled(credentialCreationPromises);
|
||||
const successCount = results.filter((r) => r.status === "fulfilled").length;
|
||||
const failureCount = results.filter((r) => r.status === "rejected").length;
|
||||
|
||||
totalSuccess += successCount;
|
||||
totalFailures += failureCount;
|
||||
}
|
||||
|
||||
return {
|
||||
executedAt: new Date().toISOString(),
|
||||
success: totalSuccess,
|
||||
failures: totalFailures,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleDeleteCredentials() {
|
||||
const delegationCredentials =
|
||||
await DelegationCredentialRepository.findAllDisabledAndIncludeNextBatchOfMembersToProcess();
|
||||
|
||||
if (!delegationCredentials.length) {
|
||||
return {
|
||||
message: "No disabled delegation credentials found",
|
||||
success: 0,
|
||||
failures: 0,
|
||||
};
|
||||
}
|
||||
let totalSuccess = 0;
|
||||
for (const delegationCredential of delegationCredentials) {
|
||||
const { workspacePlatform } = delegationCredential;
|
||||
|
||||
if (workspacePlatform.slug !== "google") {
|
||||
log.info(
|
||||
`Skipping credential deletion for workspace platform ${workspacePlatform.slug} - only google is supported`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// DB?: can deleting all credentials at once be problematic?
|
||||
const { count } = await CredentialRepository.deleteAllByDelegationCredentialId({
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
});
|
||||
totalSuccess += count;
|
||||
}
|
||||
log.info(`Deleted ${totalSuccess} credentials for disabled delegation credentials`);
|
||||
|
||||
return {
|
||||
executedAt: new Date().toISOString(),
|
||||
success: totalSuccess,
|
||||
failures: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const handler = async (request: NextRequest) => {
|
||||
validateRequest(request);
|
||||
const result = await Promise.allSettled([handleCreateCredentials(), handleDeleteCredentials()]);
|
||||
const response = result.map((r, index) => {
|
||||
if (r.status === "fulfilled") {
|
||||
return {
|
||||
...r.value,
|
||||
message: `Successfully executed ${index === 0 ? "create" : "delete"} credentials`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...r.reason,
|
||||
message: `Failed to execute ${index === 0 ? "create" : "delete"} credentials`,
|
||||
};
|
||||
});
|
||||
return NextResponse.json(response);
|
||||
};
|
||||
|
||||
export const GET = defaultResponderForAppDir(handler);
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import GoogleCalendarService from "@calcom/app-store/googlecalendar/lib/CalendarService";
|
||||
import { findUniqueDelegationCalendarCredential } from "@calcom/lib/delegationCredential/server";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
|
||||
import type { CredentialForCalendarServiceWithEmail } from "@calcom/types/Credential";
|
||||
import type { Ensure } from "@calcom/types/utils";
|
||||
|
||||
import { defaultResponderForAppDir } from "../../defaultResponderForAppDir";
|
||||
|
||||
const limitOnQueryingGoogleCalendar = 50;
|
||||
const log = logger.getSubLogger({ prefix: ["[api] selected-calendars/cron"] });
|
||||
const validateRequest = (req: NextRequest) => {
|
||||
const url = new URL(req.url);
|
||||
const apiKey = req.headers.get("authorization") || url.searchParams.get("apiKey");
|
||||
if (![process.env.CRON_API_KEY, `Bearer ${process.env.CRON_SECRET}`].includes(`${apiKey}`)) {
|
||||
throw new HttpError({ statusCode: 401, message: "Unauthorized" });
|
||||
}
|
||||
};
|
||||
|
||||
async function handleCreateSelectedCalendars() {
|
||||
// These are in DB delegation user credentials in contrast to in-memory delegation user credentials that are used elsewhere
|
||||
const allDelegationUserCredentials = await CredentialRepository.findAllDelegationByTypeIncludeUserAndTake({
|
||||
type: "google_calendar",
|
||||
take: limitOnQueryingGoogleCalendar,
|
||||
});
|
||||
|
||||
if (!allDelegationUserCredentials.length) {
|
||||
return {
|
||||
message: "No delegation credentials found",
|
||||
success: 0,
|
||||
failures: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Groups delegationUserCredentials by delegationCredentialId
|
||||
const groupedDelegationUserCredentials = allDelegationUserCredentials.reduce((acc, curr) => {
|
||||
acc[curr.delegationCredentialId] = [...(acc[curr.delegationCredentialId] || []), curr];
|
||||
return acc;
|
||||
}, {} as Record<string, typeof allDelegationUserCredentials>);
|
||||
|
||||
let totalSuccess = 0;
|
||||
let totalFailures = 0;
|
||||
|
||||
for (const [delegationCredentialId, delegationUserCredentials] of Object.entries(
|
||||
groupedDelegationUserCredentials
|
||||
)) {
|
||||
// First, create an array of promises that check if each credential should be processed
|
||||
const checkedDelegationUserCredentials = await Promise.all(
|
||||
delegationUserCredentials.map(async (delegationUserCredential) => {
|
||||
if (!delegationUserCredential.user) {
|
||||
log.error(`Credential ${delegationUserCredential.id} has no user`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get all selectedCalendars for this user, regardless of credentialId as we want to reuse the existing SelectedCalendar(which has their googleChannel related column set) after Delegation Credential has been enabled
|
||||
const hasSelectedCalendarForUserEmail = !!(await SelectedCalendarRepository.findFirst({
|
||||
where: {
|
||||
userId: delegationUserCredential.user.id,
|
||||
externalId: delegationUserCredential.user.email,
|
||||
},
|
||||
}));
|
||||
|
||||
if (hasSelectedCalendarForUserEmail) {
|
||||
log.info(`Found a reusable SelectedCalendar for ${delegationUserCredential.user.id}`);
|
||||
return null;
|
||||
}
|
||||
return delegationUserCredential;
|
||||
})
|
||||
);
|
||||
|
||||
const delegationUserCredentialsToProcess = checkedDelegationUserCredentials.filter(
|
||||
(credential): credential is Ensure<(typeof delegationUserCredentials)[number], "user"> =>
|
||||
credential !== null
|
||||
);
|
||||
|
||||
log.info(
|
||||
`Found ${delegationUserCredentialsToProcess.length} delegationUserCredentials to process for delegationCredentialId: ${delegationCredentialId}`
|
||||
);
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
delegationUserCredentialsToProcess.map(async (delegationUserCredential) => {
|
||||
try {
|
||||
const credentialForCalendarService = await findUniqueDelegationCalendarCredential({
|
||||
userId: delegationUserCredential.user.id,
|
||||
delegationCredentialId: delegationUserCredential.delegationCredentialId,
|
||||
});
|
||||
|
||||
if (!credentialForCalendarService) {
|
||||
log.error(
|
||||
`Credential not found for delegationCredentialId: ${delegationUserCredential.delegationCredentialId} and userId: ${delegationUserCredential.user.id}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!credentialForCalendarService.delegatedTo ||
|
||||
!credentialForCalendarService.delegatedTo.serviceAccountKey ||
|
||||
!credentialForCalendarService.delegatedTo.serviceAccountKey.client_email
|
||||
) {
|
||||
log.error(
|
||||
`Invalid delegatedTo for delegationCredentialId: ${delegationUserCredential.delegationCredentialId}`,
|
||||
safeStringify({
|
||||
delegatedToSet: !!credentialForCalendarService.delegatedTo,
|
||||
serviceAccountKeySet: !!credentialForCalendarService.delegatedTo?.serviceAccountKey,
|
||||
clientEmailSet: !!credentialForCalendarService.delegatedTo?.serviceAccountKey?.client_email,
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const googleCalendarService = new GoogleCalendarService(
|
||||
credentialForCalendarService as CredentialForCalendarServiceWithEmail
|
||||
);
|
||||
|
||||
let primaryCalendar;
|
||||
try {
|
||||
primaryCalendar = await googleCalendarService.fetchPrimaryCalendar();
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`Error fetching primary calendar for delegationCredentialId: ${delegationUserCredential.delegationCredentialId} and userId: ${delegationUserCredential.userId}`,
|
||||
safeStringify(error)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!primaryCalendar || !primaryCalendar.id) {
|
||||
log.error(
|
||||
`Primary calendar not found for delegationCredentialId: ${delegationUserCredential.delegationCredentialId} and userId: ${delegationUserCredential.userId}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await SelectedCalendarRepository.create({
|
||||
integration: "google_calendar",
|
||||
externalId: primaryCalendar.id,
|
||||
userId: delegationUserCredential.user.id,
|
||||
delegationCredentialId: delegationUserCredential.delegationCredentialId,
|
||||
credentialId: delegationUserCredential.id,
|
||||
});
|
||||
|
||||
log.debug(`Created SelectedCalendar for user ${delegationUserCredential.userId}`);
|
||||
} catch (error) {
|
||||
log.error(`Error processing credential ${delegationUserCredential.id}:`, safeStringify(error));
|
||||
throw error;
|
||||
}
|
||||
})
|
||||
);
|
||||
const successCount = results.filter((r) => r.status === "fulfilled").length;
|
||||
const failureCount = results.filter((r) => r.status === "rejected").length;
|
||||
|
||||
totalSuccess += successCount;
|
||||
totalFailures += failureCount;
|
||||
}
|
||||
|
||||
log.info(
|
||||
`Completed processing all selected calendars. Total Success: ${totalSuccess}, Total Failures: ${totalFailures}`
|
||||
);
|
||||
|
||||
return {
|
||||
message: "All selected calendars processed",
|
||||
executedAt: new Date().toISOString(),
|
||||
success: totalSuccess,
|
||||
failures: totalFailures,
|
||||
};
|
||||
}
|
||||
|
||||
const handler = async (request: NextRequest) => {
|
||||
validateRequest(request);
|
||||
return NextResponse.json(await handleCreateSelectedCalendars());
|
||||
};
|
||||
|
||||
export const GET = defaultResponderForAppDir(handler);
|
||||
Reference in new issue
Block a user