cal.pub0.org/packages/lib/date-ranges.ts

197 lines
5.8 KiB
TypeScript
Raw Normal View History

import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import type { Availability } from "@calcom/prisma/client";
export type DateRange = {
start: Dayjs;
end: Dayjs;
};
export type DateOverride = Pick<Availability, "date" | "startTime" | "endTime">;
export type WorkingHours = Pick<Availability, "days" | "startTime" | "endTime">;
export function processWorkingHours({
item,
timeZone,
dateFrom,
dateTo,
}: {
item: WorkingHours;
timeZone: string;
dateFrom: Dayjs;
dateTo: Dayjs;
}) {
const results = [];
for (let date = dateFrom.tz(timeZone).startOf("day"); dateTo.isAfter(date); date = date.add(1, "day")) {
if (!item.days.includes(date.day())) {
continue;
}
const start = date.hour(item.startTime.getUTCHours()).minute(item.startTime.getUTCMinutes()).second(0);
const end = date.hour(item.endTime.getUTCHours()).minute(item.endTime.getUTCMinutes()).second(0);
const startResult = dayjs.max(start, dateFrom.tz(timeZone));
const endResult = dayjs.min(end, dateTo.tz(timeZone));
if (startResult.isAfter(endResult)) {
// if an event ends before start, it's not a result.
continue;
}
results.push({
start: startResult,
end: endResult,
});
}
return results;
}
export function processDateOverride({ item, timeZone }: { item: DateOverride; timeZone: string }) {
const date = dayjs.utc(item.date);
const startTime = dayjs(item.startTime).utc().subtract(dayjs().tz(timeZone).utcOffset(), "minute");
const endTime = dayjs(item.endTime).utc().subtract(dayjs().tz(timeZone).utcOffset(), "minute");
const diffDays = startTime.startOf("day").diff(dayjs.utc(item.startTime).startOf("day"), "day");
return {
start: date.add(diffDays, "day").hour(startTime.hour()).minute(startTime.minute()).second(0).tz(timeZone),
end: date.add(diffDays, "day").hour(endTime.hour()).minute(endTime.minute()).second(0).tz(timeZone),
};
}
export function buildDateRanges({
availability,
timeZone /* Organizer timeZone */,
dateFrom /* Attendee dateFrom */,
dateTo /* `` dateTo */,
}: {
timeZone: string;
availability: (DateOverride | WorkingHours)[];
dateFrom: Dayjs;
dateTo: Dayjs;
}): DateRange[] {
const groupedWorkingHours = groupByDate(
availability.reduce((processed: DateRange[], item) => {
if ("days" in item) {
processed = processed.concat(processWorkingHours({ item, timeZone, dateFrom, dateTo }));
}
return processed;
}, [])
);
const groupedDateOverrides = groupByDate(
availability.reduce((processed: DateRange[], item) => {
if ("date" in item && !!item.date) {
processed.push(processDateOverride({ item, timeZone }));
}
return processed;
}, [])
);
const dateRanges = Object.values({
...groupedWorkingHours,
...groupedDateOverrides,
}).map(
// remove 0-length overrides that were kept to cancel out working dates until now.
(ranges) => ranges.filter((range) => !range.start.isSame(range.end))
);
return dateRanges.flat();
}
export function groupByDate(ranges: DateRange[]): { [x: string]: DateRange[] } {
const results = ranges.reduce(
(
previousValue: {
[date: string]: DateRange[];
},
currentValue
) => {
const dateString = dayjs(currentValue.start).format("YYYY-MM-DD");
previousValue[dateString] =
typeof previousValue[dateString] === "undefined"
? [currentValue]
: [...previousValue[dateString], currentValue];
return previousValue;
},
{}
);
return results;
}
export function intersect(ranges: DateRange[][]): DateRange[] {
if (!ranges.length) return [];
// Get the ranges of the first user
let commonAvailability = ranges[0];
// For each of the remaining users, find the intersection of their ranges with the current common availability
for (let i = 1; i < ranges.length; i++) {
const userRanges = ranges[i];
const intersectedRanges: {
start: Dayjs;
end: Dayjs;
}[] = [];
commonAvailability.forEach((commonRange) => {
userRanges.forEach((userRange) => {
const intersection = getIntersection(commonRange, userRange);
if (intersection !== null) {
// If the current common range intersects with the user range, add the intersected time range to the new array
intersectedRanges.push(intersection);
}
});
});
commonAvailability = intersectedRanges;
}
// If the common availability is empty, there is no time when all users are available
if (commonAvailability.length === 0) {
return [];
}
return commonAvailability;
}
function getIntersection(range1: DateRange, range2: DateRange) {
const start = range1.start.utc().isAfter(range2.start) ? range1.start : range2.start;
const end = range1.end.utc().isBefore(range2.end) ? range1.end : range2.end;
if (start.utc().isBefore(end)) {
return { start, end };
}
return null;
}
fix: seats regression [CAL-2041] ## What does this PR do? <!-- Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. --> - Passes the proper seats data in the new booker component between states and to the backend Fixes #9779 Fixes #9749 Fixes #7967 Fixes #9942 <!-- Please provide a loom video for visual changes to speed up reviews Loom Video: https://www.loom.com/ --> ## Type of change <!-- Please delete bullets that are not relevant. --> - Bug fix (non-breaking change which fixes an issue) ## How should this be tested? <!-- Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration --> **As the organizer** - Create a seated event type - Book at least 2 seats - Reschedule the booking - All attendees should be moved to the new booking - Cancel the booking - The event should be cancelled for all attendees **As an attendee** - [x] Book a seated event - [x] Reschedule that booking to an empty slot - [x] The attendee should be moved to that new slot - [x] Reschedule onto a booking with occupied seats - [x] The attendees should be merged - [x] On that slot reschedule all attendees to a new slot - [x] The former booking should be deleted - [x] As the attendee cancel the booking - [x] Only that attendee should be removed ## Mandatory Tasks - [x] Make sure you have self-reviewed the code. A decent size PR without self-review might be rejected. ## Checklist <!-- Please remove all the irrelevant bullets to your PR -->
2023-07-11 15:11:08 +00:00
export function subtract(
sourceRanges: (DateRange & { [x: string]: unknown })[],
excludedRanges: DateRange[]
) {
const result: DateRange[] = [];
fix: seats regression [CAL-2041] ## What does this PR do? <!-- Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. --> - Passes the proper seats data in the new booker component between states and to the backend Fixes #9779 Fixes #9749 Fixes #7967 Fixes #9942 <!-- Please provide a loom video for visual changes to speed up reviews Loom Video: https://www.loom.com/ --> ## Type of change <!-- Please delete bullets that are not relevant. --> - Bug fix (non-breaking change which fixes an issue) ## How should this be tested? <!-- Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration --> **As the organizer** - Create a seated event type - Book at least 2 seats - Reschedule the booking - All attendees should be moved to the new booking - Cancel the booking - The event should be cancelled for all attendees **As an attendee** - [x] Book a seated event - [x] Reschedule that booking to an empty slot - [x] The attendee should be moved to that new slot - [x] Reschedule onto a booking with occupied seats - [x] The attendees should be merged - [x] On that slot reschedule all attendees to a new slot - [x] The former booking should be deleted - [x] As the attendee cancel the booking - [x] Only that attendee should be removed ## Mandatory Tasks - [x] Make sure you have self-reviewed the code. A decent size PR without self-review might be rejected. ## Checklist <!-- Please remove all the irrelevant bullets to your PR -->
2023-07-11 15:11:08 +00:00
for (const { start: sourceStart, end: sourceEnd, ...passThrough } of sourceRanges) {
let currentStart = sourceStart;
const overlappingRanges = excludedRanges.filter(
({ start, end }) => start.isBefore(sourceEnd) && end.isAfter(sourceStart)
);
overlappingRanges.sort((a, b) => (a.start.isAfter(b.start) ? 1 : -1));
for (const { start: excludedStart, end: excludedEnd } of overlappingRanges) {
if (excludedStart.isAfter(currentStart)) {
result.push({ start: currentStart, end: excludedStart });
}
currentStart = excludedEnd.isAfter(currentStart) ? excludedEnd : currentStart;
}
if (sourceEnd.isAfter(currentStart)) {
fix: seats regression [CAL-2041] ## What does this PR do? <!-- Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. --> - Passes the proper seats data in the new booker component between states and to the backend Fixes #9779 Fixes #9749 Fixes #7967 Fixes #9942 <!-- Please provide a loom video for visual changes to speed up reviews Loom Video: https://www.loom.com/ --> ## Type of change <!-- Please delete bullets that are not relevant. --> - Bug fix (non-breaking change which fixes an issue) ## How should this be tested? <!-- Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration --> **As the organizer** - Create a seated event type - Book at least 2 seats - Reschedule the booking - All attendees should be moved to the new booking - Cancel the booking - The event should be cancelled for all attendees **As an attendee** - [x] Book a seated event - [x] Reschedule that booking to an empty slot - [x] The attendee should be moved to that new slot - [x] Reschedule onto a booking with occupied seats - [x] The attendees should be merged - [x] On that slot reschedule all attendees to a new slot - [x] The former booking should be deleted - [x] As the attendee cancel the booking - [x] Only that attendee should be removed ## Mandatory Tasks - [x] Make sure you have self-reviewed the code. A decent size PR without self-review might be rejected. ## Checklist <!-- Please remove all the irrelevant bullets to your PR -->
2023-07-11 15:11:08 +00:00
result.push({ start: currentStart, end: sourceEnd, ...passThrough });
}
}
return result;
}