Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions src/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"ical-generator": "^10.2.0",
"jsonwebtoken": "^8.5.1",
"multer": "^1.4.5-lts.1",
"node-ical": "^0.26.1",
"nodemailer": "^6.9.1",
"prisma": "^6.2.1",
"shared": "1.0.0"
Expand Down
23 changes: 21 additions & 2 deletions src/backend/src/controllers/users.controllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,13 +173,14 @@ export default class UsersController {

static async setUserScheduleSettings(req: Request, res: Response, next: NextFunction) {
try {
const { personalGmail, personalZoomLink, availability } = req.body;
const { personalGmail, personalZoomLink, availability, importedIcsCalendarUrl } = req.body;

const updatedScheduleSettings = await UsersService.setUserScheduleSettings(
req.currentUser,
personalGmail,
personalZoomLink,
availability
availability,
importedIcsCalendarUrl
);

res.status(200).json(updatedScheduleSettings);
Expand All @@ -199,6 +200,24 @@ export default class UsersController {
}
}

static async getUserIcsBusyTimes(req: Request, res: Response, next: NextFunction) {
try {
const { userId } = req.params as Record<string, string>;
const { startDate, endDate } = req.query as Record<string, string>;

const busyTimes = await UsersService.getUserIcsBusyTimes(
userId,
req.currentUser,
new Date(startDate),
new Date(endDate),
req.organization
);
res.status(200).json(busyTimes);
} catch (error: unknown) {
next(error);
}
}

static async getUserTasks(req: Request, res: Response, next: NextFunction) {
try {
const { userId } = req.params as Record<string, string>;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Schedule_Settings" ADD COLUMN "importedIcsCalendarUrl" TEXT NOT NULL DEFAULT '';
13 changes: 7 additions & 6 deletions src/backend/src/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -1265,12 +1265,13 @@ model Availability {
}

model Schedule_Settings {
drScheduleSettingsId String @id @default(uuid())
personalGmail String
personalZoomLink String
User User @relation(fields: [userId], references: [userId])
userId String @unique
availabilities Availability[]
drScheduleSettingsId String @id @default(uuid())
personalGmail String
personalZoomLink String
User User @relation(fields: [userId], references: [userId])
userId String @unique
availabilities Availability[]
importedIcsCalendarUrl String @default("")
}

model Wbs_Proposed_Changes {
Expand Down
10 changes: 9 additions & 1 deletion src/backend/src/routes/users.routes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Theme } from '@prisma/client';
import express from 'express';
import { body } from 'express-validator';
import { body, query } from 'express-validator';
import UsersController from '../controllers/users.controllers.js';
import { isRole, nonEmptyString, intMinZero, validateInputs, isDateOnly } from '../utils/validation.utils.js';

Expand Down Expand Up @@ -47,6 +47,7 @@ userRouter.post(
'/schedule-settings/set',
body('personalGmail').isString(),
body('personalZoomLink').isString(),
body('importedIcsCalendarUrl').optional().isString(),
body('availability').isArray(),
body('availability.*.availability').isArray(),
intMinZero(body('availability.*.availability.*')),
Expand All @@ -57,6 +58,13 @@ userRouter.post(

userRouter.get('/:userId/secure-settings', UsersController.getUserSecureSettings);
userRouter.get('/:userId/schedule-settings', UsersController.getUserScheduleSettings);
userRouter.get(
'/:userId/schedule-settings/ics-busy',
isDateOnly(query('startDate')),
isDateOnly(query('endDate')),
validateInputs,
UsersController.getUserIcsBusyTimes
);
userRouter.get('/:userId/tasks', UsersController.getUserTasks);
userRouter.post(
'/tasks/get-many',
Expand Down
66 changes: 62 additions & 4 deletions src/backend/src/services/users.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ import {
AvailabilityCreateArgs,
UserWithScheduleSettings,
ProjectOverview,
isAtLeastRank
isAtLeastRank,
IcsBusySlots
} from 'shared';
import prisma from '../prisma/prisma.js';
import { AccessDeniedException, HttpException, NotFoundException } from '../utils/errors.utils.js';
import { busyIntervalsToSlots, fetchIcsBusyTimes, validateIcsUrl } from '../utils/ics.utils.js';
import { generateAccessToken } from '../utils/auth.utils.js';
import { projectOverviewTransformer } from '../transformers/projects.transformer.js';
import { getProjectOverviewQueryArgs } from '../prisma-query-args/projects.query-args.js';
Expand All @@ -29,6 +31,7 @@ import authenticatedUserTransformer from '../transformers/auth-user.transformer.
import { getTaskQueryArgs } from '../prisma-query-args/tasks.query-args.js';
import taskTransformer from '../transformers/tasks.transformer.js';
import { validateUserIsPartOfFinanceTeamOrHead } from '../utils/reimbursement-requests.utils.js';
import { encrypt, decrypt } from '../utils/encryption.utils.js';

export default class UsersService {
/**
Expand Down Expand Up @@ -525,7 +528,8 @@ export default class UsersService {
user: User,
personalGmail: string,
personalZoomLink: string,
availabilities: AvailabilityCreateArgs[]
availabilities: AvailabilityCreateArgs[],
importedIcsCalendarUrl?: string
): Promise<UserScheduleSettings> {
if (personalGmail !== '') {
const existingUser = await prisma.schedule_Settings.findFirst({
Expand All @@ -537,16 +541,22 @@ export default class UsersService {
}
}

if (importedIcsCalendarUrl) validateIcsUrl(importedIcsCalendarUrl);

const encryptedIcsUrl = importedIcsCalendarUrl ? encrypt(importedIcsCalendarUrl) : importedIcsCalendarUrl;

const newUserScheduleSettings = await prisma.schedule_Settings.upsert({
where: { userId: user.userId },
update: {
personalGmail,
personalZoomLink
personalZoomLink,
importedIcsCalendarUrl: encryptedIcsUrl
},
create: {
userId: user.userId,
personalGmail,
personalZoomLink
personalZoomLink,
importedIcsCalendarUrl: encryptedIcsUrl
},
...getUserScheduleSettingsQueryArgs()
});
Expand Down Expand Up @@ -622,4 +632,52 @@ export default class UsersService {

return users.map(userWithScheduleSettingsTransformer);
}

/**
* Read-only busy-times for a user's imported ICS calendar over [startDate, endDate), mapped onto the
* 0-11 availability slots per day.
*
* @param userId the user whose imported calendar is being read
* @param submitter the requesting user
* @param startDate the first day of the range (inclusive)
* @param endDate the day after the last day of the range (exclusive)
* @param organization the organization the requesting user is in
* @returns the busy slots per day, only including days that have at least one busy slot
*/
static async getUserIcsBusyTimes(
Comment thread
staysgt marked this conversation as resolved.
userId: string,
submitter: User,
startDate: Date,
endDate: Date,
organization: Organization
): Promise<IcsBusySlots[]> {
if (submitter.userId !== userId) throw new AccessDeniedException('You can only access your own schedule settings');
const user = await prisma.user.findUnique({ where: { userId }, include: { organizations: true } });
if (!user) throw new NotFoundException('User', userId);
if (!user.organizations.map((org) => org.organizationId).includes(organization.organizationId))
throw new HttpException(400, `User ${userId} is not apart of the current organization`);

const scheduleSettings = await prisma.schedule_Settings.findUnique({ where: { userId } });
if (!scheduleSettings?.importedIcsCalendarUrl) return [];

let busy;
try {
busy = await fetchIcsBusyTimes(decrypt(scheduleSettings.importedIcsCalendarUrl), startDate, endDate);
} catch (error) {
if (error instanceof HttpException) {
throw new HttpException(error.status, `Failed to fetch ICS calendar: ${error.message}`);
}
throw error;
}

if (busy.length === 0) return [];

const busyDays: IcsBusySlots[] = [];
for (let day = new Date(startDate); day < endDate; day.setUTCDate(day.getUTCDate() + 1)) {
const busySlots = busyIntervalsToSlots(busy, day);
if (busySlots.size > 0) busyDays.push({ dateSet: new Date(day), busySlots: Array.from(busySlots) });
}

return busyDays;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Prisma } from '@prisma/client';
import { UserScheduleSettings } from 'shared';
import { UserScheduleSettingsQueryArgs } from '../prisma-query-args/user.query-args.js';
import { decrypt } from '../utils/encryption.utils.js';

const userScheduleSettingsTransformer = (
settings: Prisma.Schedule_SettingsGetPayload<UserScheduleSettingsQueryArgs>
Expand All @@ -9,7 +10,10 @@ const userScheduleSettingsTransformer = (
drScheduleSettingsId: settings.drScheduleSettingsId,
personalGmail: settings.personalGmail,
personalZoomLink: settings.personalZoomLink,
availabilities: settings.availabilities
availabilities: settings.availabilities,
importedIcsCalendarUrl: settings.importedIcsCalendarUrl
? decrypt(settings.importedIcsCalendarUrl)
: settings.importedIcsCalendarUrl
};
};

Expand Down
Loading
Loading