Files
calendar/apps/web/modules/troubleshooter/components/LargeCalendar.tsx
T
Hariom BalharaGitHubbot_apkDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>Udit Takkar
a4621da2be feat: make source required on EventBusyDetails for Troubleshooter display (#27088)
* feat: make source required on EventBusyDetails for Troubleshooter display

- Make source a required property on EventBusyDetails type
- Update LimitManager to accept and store source when adding busy times
- Add user-friendly source names for all busy time types:
  - 'Booking Limit' for booking limit busy times
  - 'Duration Limit' for duration limit busy times
  - 'Team Booking Limit' for team booking limit busy times
  - 'Buffer Time' for seated event buffer times
  - 'Calendar' for external calendar busy times
- Ensure all entries in detailedBusyTimes have source set
- Cover includeManagedEventsInLimits and teamBookingLimits branches

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: add limit value and unit metadata to busy time sources

- Include limit value and unit in source strings for Troubleshooter display
- Booking Limit: shows as 'Booking Limit: 5 per day'
- Duration Limit: shows as 'Duration Limit: 120 min per week'
- Team Booking Limit: shows as 'Team Booking Limit: 10 per month'
- Preserves existing calendar sources (e.g., 'google-calendar')

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: enhance busy time management with new limit sources

- Introduced new limit sources for busy times, including event booking and duration limits, with user-friendly titles for display.
- Updated LimitManager to accept and store detailed busy time information, including title and source.
- Refactored busy time addition logic across various services to utilize the new structure, improving clarity and maintainability.

* fixes

* feat: conditionally include source and translate busy time titles

- Add withSource parameter to conditionally include/exclude source from response
- Translate busy time titles on frontend using useLocale hook
- Source is only included when withSource=true (for Troubleshooter display)

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: enhance user availability service and busy time handling

- Updated LargeCalendar component to include event ID check for enabling busy times.
- Added translation for "busy" in common.json for better user experience.
- Refactored getUserAvailability service to include new method for fetching user availability with busy times from limits.
- Introduced parseLimits function to streamline booking and duration limit parsing.
- Improved error handling in user handler for better user feedback.

* refactor: remove unnecessary timeZone: undefined from addBusyTime calls

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: add buffer_time and calendar translation keys for busy times

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: add event source to calendar components and improve busy time handling

- Updated EventList component to include event source in data attributes for better tracking.
- Enhanced LargeCalendar component to pass event

* fix: add missing source property to Date Override calendar event

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: use 'date-override' as source for Date Override calendar events

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Avoid type assertion

* fix: pass both bookingLimits and durationLimits to getStartEndDateforLimitCheck (#27898)

* test: add unit tests for getUserAvailabilityIncludingBusyTimesFromLimits

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: pass both bookingLimits and durationLimits to getStartEndDateforLimitCheck

- Fix bug where bookingLimits || durationLimits was passed as single param
- Skip getBusyTimesForLimitChecks when eventType has no limits
- Remove as never casts, use proper typing for mock dependencies
- Replace expect.any(String) with exact ISO date assertions

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: replace loose assertions with exact values in tests

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: address review feedback on busy time sources

- Fix t("busy") fallback to t("busy_time.busy") for correct translation lookup
- Add missing title property to buffer time entries for Troubleshooter display
- Use descriptive debug strings for buffer time source field
- Fix import ordering in LargeCalendar.tsx

Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
Co-Authored-By: unknown <>

* fix: preserve pre-existing busyTimesFromLimitsBookings from initialData

Address review feedback from @hariombalhara (comment #30, #31):

- Initialize busyTimesFromLimitsBookings from initialData instead of []
  to avoid silently overwriting pre-existing data with an empty array
- Use conditional spread to only include busyTimesFromLimitsBookings
  when it has a value
- Add test verifying pre-existing busyTimesFromLimitsBookings is
  preserved and passed through to _getUserAvailability
- Add test verifying busyTimesFromLimitsBookings is not passed when
  there are no limits and no initialData bookings

Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
Co-Authored-By: bot_apk <apk@cognition.ai>

* fix: pass fetched eventType to _getUserAvailability to avoid duplicate DB query

Addresses Devin Review comment r2863593564: the wrapper method fetches
eventType but wasn't passing it through, causing _getUserAvailability to
re-fetch the same eventType from the database.

Also adds a test verifying eventType is forwarded correctly.

Co-Authored-By: bot_apk <apk@cognition.ai>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: bot_apk <apk@cognition.ai>
2026-03-06 14:53:14 -03:00

143 lines
5.0 KiB
TypeScript

import { useSession } from "next-auth/react";
import { useMemo } from "react";
import dayjs from "@calcom/dayjs";
import { useAvailableTimeSlots } from "@calcom/features/bookings/Booker/hooks/useAvailableTimeSlots";
import { useTimePreferences } from "@calcom/features/bookings/lib/timePreferences";
import { Calendar } from "@calcom/features/calendars/weeklyview/components/Calendar";
import { useTroubleshooterStore } from "@calcom/features/troubleshooter/store";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { BookingStatus } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import { useSchedule } from "~/schedules/hooks/useSchedule";
import { OutOfOfficeInSlots } from "../../bookings/components/OutOfOfficeInSlots";
export const LargeCalendar = ({ extraDays }: { extraDays: number }) => {
const { t } = useLocale();
const { timezone } = useTimePreferences();
const selectedDate = useTroubleshooterStore((state) => state.selectedDate);
const event = useTroubleshooterStore((state) => state.event);
const calendarToColorMap = useTroubleshooterStore((state) => state.calendarToColorMap);
const { data: session } = useSession();
const startDate = selectedDate ? dayjs(selectedDate) : dayjs();
const { data: busyEvents } = trpc.viewer.availability.user.useQuery(
{
username: session?.user?.username || "",
dateFrom: startDate.startOf("day").utc().format(),
dateTo: startDate
.endOf("day")
.add(extraDays - 1, "day")
.utc()
.format(),
eventTypeId: event?.id,
withSource: true,
},
{
// Busy Times need eventTypeId to correctly have all busy times. event.id check here also avoids sending double requests for availability.user
enabled: !!session?.user?.username && !!event?.id,
}
);
const isTeamEvent = !!event?.teamId;
const { data: schedule } = useSchedule({
username: session?.user.orgAwareUsername || "",
// For team events, don't pass eventSlug to avoid slug lookup issues - use eventId instead
eventSlug: isTeamEvent ? null : event?.slug,
eventId: event?.id,
timezone,
month: startDate.format("YYYY-MM"),
orgSlug: session?.user.org?.slug,
isTeamEvent,
});
const endDate = dayjs(startDate)
.add(extraDays - 1, "day")
.toDate();
const availableSlots = useAvailableTimeSlots({ schedule, eventDuration: event?.duration ?? 30 });
const events = useMemo(() => {
if (!busyEvents?.busy) return [];
// TODO: Add buffer times in here as well just requires a bit of logic for fetching event type and then adding buffer time
// start: dayjs(startTime)
// .subtract((eventType?.beforeEventBuffer || 0) + (afterEventBuffer || 0), "minute")
// .toDate(),
// end: dayjs(endTime)
// .add((eventType?.afterEventBuffer || 0) + (beforeEventBuffer || 0), "minute")
// .toDate(),
const calendarEvents = busyEvents?.busy.map((event, idx) => {
const translatedTitle = event.title ? t(event.title) : t("busy_time.busy");
return {
id: idx,
title: translatedTitle,
start: new Date(event.start),
end: new Date(event.end),
source: event.source,
options: {
color:
event.source && calendarToColorMap[event.source] ? calendarToColorMap[event.source] : undefined,
status: BookingStatus.ACCEPTED,
"data-test-id": "troubleshooter-busy-event",
},
};
});
if (busyEvents.dateOverrides) {
busyEvents.dateOverrides.forEach((dateOverride) => {
const dateOverrideStart = dayjs(dateOverride.start);
const dateOverrideEnd = dayjs(dateOverride.end);
if (!dateOverrideStart.isSame(dateOverrideEnd)) {
return;
}
const dayOfWeekNum = dateOverrideStart.day();
const workingHoursForDay = busyEvents.workingHours.find((workingHours) =>
workingHours.days.includes(dayOfWeekNum)
);
if (!workingHoursForDay) return;
calendarEvents.push({
id: calendarEvents.length,
title: "Date Override",
start: dateOverrideStart.add(workingHoursForDay.startTime, "minutes").toDate(),
end: dateOverrideEnd.add(workingHoursForDay.endTime, "minutes").toDate(),
source: "date-override",
options: {
color: "black",
status: BookingStatus.ACCEPTED,
"data-test-id": "troubleshooter-busy-time",
},
});
});
}
return calendarEvents;
}, [busyEvents, calendarToColorMap, t]);
return (
<div className="h-full [--calendar-dates-sticky-offset:66px]">
<Calendar
sortEvents
startHour={0}
endHour={23}
events={events}
availableTimeslots={availableSlots}
startDate={startDate.toDate()}
endDate={endDate}
gridCellsPerHour={60 / (event?.duration || 15)}
hoverEventDuration={30}
hideHeader
timezone={timezone}
renderOutOfOffice={(props) => <OutOfOfficeInSlots {...props} />}
/>
</div>
);
};