The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Add scheduling and time-picker UI (#28865)
Raphaël Bosi57b05efb93e0
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatSchedulingPreferences.tsx b/packages/twenty-front/src/modules/ai/components/AiChatSchedulingPreferences.tsxnew file mode 100644index 00000000000..54d320bfc03--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatSchedulingPreferences.tsx@@ -0,0 +1,381 @@+import { styled } from '@linaria/react';+import { t } from '@lingui/core/macro';+import { useId, useState } from 'react';+import { Temporal } from 'temporal-polyfill';+import {+ getValidTimeZoneOrUndefined,+ isDefined,+ isNonEmptyArray,+} from 'twenty-shared/utils';+import { FormFieldRow, SearchInput } from 'twenty-ui/components/input';+import { Section } from 'twenty-ui/components/layout';+import {+ Button,+ Checkbox,+ Input,+ type SelectOption,+} from 'twenty-ui/primitives/input';+import { Text } from 'twenty-ui/primitives/typography';+import { themeCssVariables } from 'twenty-ui/theme';+import { normalizeSearchText } from 'twenty-ui/utilities';++import { type AiChatSchedulingCalendar } from '@/ai/types/AiChatSchedulingCalendar';+import { type AiChatSchedulingPreferencesValue } from '@/ai/types/AiChatSchedulingPreferencesValue';+import { AVAILABLE_TIMEZONE_OPTIONS } from '@/localization/constants/AvailableTimezoneOptions';+import { findAvailableTimeZoneOption } from '@/localization/utils/findAvailableTimeZoneOption';+import { formatTimeZoneLabel } from '@/localization/utils/formatTimeZoneLabel';+import { getValidPlainTimeOrUndefined } from '@/localization/utils/getValidPlainTimeOrUndefined';+import { Select } from '@/ui/input/components/Select';+import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';++const FIELD_LABEL_WIDTH_PX = 112;+const CALENDAR_LIST_MAX_HEIGHT_PX = 240;++const StyledFields = styled.div`+ border: 1px solid ${themeCssVariables.border.color.medium};+ border-radius: ${themeCssVariables.border.radius.md};+ overflow: hidden;+`;++const StyledFullWidth = styled.div`+ min-width: 0;+ width: 100%;+`;++const StyledChoices = styled.div`+ display: flex;+ flex-wrap: wrap;+ gap: ${themeCssVariables.spacing[3]};+ padding-block: ${themeCssVariables.spacing[2]};+`;++const StyledChoice = styled.label`+ align-items: center;+ cursor: pointer;+ display: flex;+ gap: ${themeCssVariables.spacing[2]};+`;++const StyledCalendarChoices = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[3]};+ max-height: ${CALENDAR_LIST_MAX_HEIGHT_PX}px;+ overflow-y: auto;+ padding-block: ${themeCssVariables.spacing[2]};+`;++const StyledTimeRange = styled.div`+ align-items: center;+ display: flex;+ gap: ${themeCssVariables.spacing[2]};+ white-space: nowrap;+ width: 100%;+`;++const StyledError = styled.div`+ color: ${themeCssVariables.font.color.danger};+ font-size: ${themeCssVariables.font.size.sm};+ padding-block: ${themeCssVariables.spacing[2]};+`;++type AiChatSchedulingPreferencesProps = {+ value: AiChatSchedulingPreferencesValue;+ calendars: AiChatSchedulingCalendar[];+ onChange: (value: AiChatSchedulingPreferencesValue) => void;+ timeZoneOptions?: SelectOption<string>[];+ isDisabled?: boolean;+};++const getOrganizerCalendarDescription = (+ calendar: Pick<+ AiChatSchedulingCalendar,+ 'isDisabled' | 'canOrganize' | 'description'+ >,+) => {+ if (calendar.isDisabled) {+ return t`Unavailable`;+ }++ if (!calendar.canOrganize) {+ return t`Read-only calendar`;+ }++ return calendar.description;+};++export const AiChatSchedulingPreferences = ({+ value,+ calendars,+ onChange,+ timeZoneOptions = AVAILABLE_TIMEZONE_OPTIONS,+ isDisabled = false,+}: AiChatSchedulingPreferencesProps) => {+ const instanceId = useId();+ const [calendarSearch, setCalendarSearch] = useState('');+ const workingHoursStart = getValidPlainTimeOrUndefined(+ value.workingHoursStart,+ );+ const workingHoursEnd = getValidPlainTimeOrUndefined(value.workingHoursEnd);+ const hasWorkingHours =+ isDefined(workingHoursStart) && isDefined(workingHoursEnd);+ const isWorkingHoursOrderInvalid =+ hasWorkingHours &&+ Temporal.PlainTime.compare(workingHoursStart, workingHoursEnd) >= 0;+ const hasWorkingDays = isNonEmptyArray(value.workingDays);+ const hasAvailabilityCalendar = calendars.some(+ ({ id, isDisabled: isCalendarDisabled }) =>+ !isCalendarDisabled && value.availabilityCalendarIds.includes(id),+ );+ const availableCalendarIds = new Set(+ calendars.filter((calendar) => !calendar.isDisabled).map(({ id }) => id),+ );+ const hasUnavailableSelectedCalendars = value.availabilityCalendarIds.some(+ (calendarId) => !availableCalendarIds.has(calendarId),+ );+ const normalizedCalendarSearch = normalizeSearchText(calendarSearch);+ const filteredCalendars = calendars.filter((calendar) =>+ normalizeSearchText(+ `${calendar.name} ${calendar.description ?? ''}`,+ ).includes(normalizedCalendarSearch),+ );+ const hasOrganizerCalendar = calendars.some(+ ({ id, canOrganize, isDisabled: isCalendarDisabled }) =>+ id === value.organizerCalendarId && canOrganize && !isCalendarDisabled,+ );+ const validTimeZone = getValidTimeZoneOrUndefined(value.timeZone);+ const availableTimeZone = findAvailableTimeZoneOption(value.timeZone)?.value;+ const listedTimeZoneOption = timeZoneOptions.find(+ ({ value: timeZone }) =>+ timeZone === value.timeZone || timeZone === availableTimeZone,+ );+ const unlistedTimeZoneOption =+ isDefined(validTimeZone) && !isDefined(listedTimeZoneOption)+ ? {+ value: validTimeZone,+ label: formatTimeZoneLabel({ timeZone: validTimeZone }),+ }+ : undefined;+ const workingDays: {+ value: AiChatSchedulingPreferencesValue['workingDays'][number];+ label: string;+ }[] = [+ { value: 1, label: t`Monday` },+ { value: 2, label: t`Tuesday` },+ { value: 3, label: t`Wednesday` },+ { value: 4, label: t`Thursday` },+ { value: 5, label: t`Friday` },+ { value: 6, label: t`Saturday` },+ { value: 7, label: t`Sunday` },+ ];++ return (+ <Section.Root fullWidth>+ <Section.Header+ title={t`Scheduling preferences`}+ description={t`Choose when you are available and which calendar sends invitations.`}+ />+ <StyledFields>+ <FormFieldRow label={t`Time zone`} labelWidth={FIELD_LABEL_WIDTH_PX}>+ <StyledFullWidth>+ <Select+ dropdownId={`${instanceId}-time-zone`}+ dropdownWidth={GenericDropdownContentWidth.ExtraExtraLarge}+ fullWidth+ value={listedTimeZoneOption?.value ?? value.timeZone}+ options={timeZoneOptions}+ pinnedOption={unlistedTimeZoneOption}+ emptyOption={{ value: '', label: t`Choose a time zone` }}+ disabled={isDisabled}+ onChange={(timeZone) => onChange({ ...value, timeZone })}+ withSearchInput+ needIconCheck+ />+ {!isDefined(validTimeZone) && (+ <StyledError role="alert">{t`Choose a time zone.`}</StyledError>+ )}+ </StyledFullWidth>+ </FormFieldRow>+ <FormFieldRow label={t`Working days`} labelWidth={FIELD_LABEL_WIDTH_PX}>+ <StyledFullWidth>+ <StyledChoices>+ {workingDays.map(({ value: day, label }) => (+ <StyledChoice key={day}>+ <Checkbox+ checked={value.workingDays.includes(day)}+ disabled={isDisabled}+ onCheckedChange={(isChecked) =>+ onChange({+ ...value,+ workingDays: isChecked+ ? [...value.workingDays, day].sort()+ : value.workingDays.filter(+ (workingDay) => workingDay !== day,+ ),+ })+ }+ />+ <Text render={<span />}>{label}</Text>+ </StyledChoice>+ ))}+ </StyledChoices>+ {!hasWorkingDays && (+ <StyledError role="alert">{t`Select at least one working day.`}</StyledError>+ )}+ </StyledFullWidth>+ </FormFieldRow>+ <FormFieldRow+ label={t`Working hours`}+ labelWidth={FIELD_LABEL_WIDTH_PX}+ >+ <StyledFullWidth>+ <StyledTimeRange>+ <Input+ type="time"+ aria-label={t`Working hours start`}+ aria-invalid={+ !isDefined(workingHoursStart) || isWorkingHoursOrderInvalid+ }+ value={value.workingHoursStart}+ disabled={isDisabled}+ onValueChange={(workingHoursStart) =>+ onChange({ ...value, workingHoursStart })+ }+ />+ <Text render={<span />} color="tertiary">{t`to`}</Text>+ <Input+ type="time"+ aria-label={t`Working hours end`}+ aria-invalid={+ !isDefined(workingHoursEnd) || isWorkingHoursOrderInvalid+ }+ value={value.workingHoursEnd}+ disabled={isDisabled}+ onValueChange={(workingHoursEnd) =>+ onChange({ ...value, workingHoursEnd })+ }+ />+ </StyledTimeRange>+ {!hasWorkingHours && (+ <StyledError role="alert">{t`Enter a start and end time.`}</StyledError>+ )}+ {isWorkingHoursOrderInvalid && (+ <StyledError role="alert">{t`End time must be after start time.`}</StyledError>+ )}+ </StyledFullWidth>+ </FormFieldRow>+ <FormFieldRow+ label={t`Availability calendars`}+ labelWidth={FIELD_LABEL_WIDTH_PX}+ >+ <StyledFullWidth>+ {isNonEmptyArray(calendars) && (+ <SearchInput+ type="search"+ aria-label={t`Search availability calendars`}+ placeholder={t`Search calendars`}+ value={calendarSearch}+ onValueChange={setCalendarSearch}+ disabled={isDisabled}+ />+ )}+ <StyledCalendarChoices>+ {filteredCalendars.map((calendar) => (+ <StyledChoice key={calendar.id}>+ <Checkbox+ checked={value.availabilityCalendarIds.includes(+ calendar.id,+ )}+ disabled={isDisabled || calendar.isDisabled}+ onCheckedChange={(isChecked) =>+ onChange({+ ...value,+ availabilityCalendarIds: isChecked+ ? [...value.availabilityCalendarIds, calendar.id]+ : value.availabilityCalendarIds.filter(+ (calendarId) => calendarId !== calendar.id,+ ),+ })+ }+ />+ <div>+ <Text>{calendar.name}</Text>+ <Text size="sm" color="tertiary">+ {calendar.isDisabled+ ? t`Unavailable`+ : calendar.description}+ </Text>+ </div>+ </StyledChoice>+ ))}+ {!isNonEmptyArray(filteredCalendars) && (+ <Text color="tertiary">+ {isNonEmptyArray(calendars)+ ? t`No calendars match your search.`+ : t`No calendars available.`}+ </Text>+ )}+ </StyledCalendarChoices>+ {hasUnavailableSelectedCalendars && (+ <>+ <StyledError role="alert">{t`Some selected calendars are no longer available.`}</StyledError>+ <Button+ variant="link"+ size="sm"+ disabled={isDisabled}+ onClick={() =>+ onChange({+ ...value,+ availabilityCalendarIds:+ value.availabilityCalendarIds.filter((calendarId) =>+ availableCalendarIds.has(calendarId),+ ),+ })+ }+ >+ {t`Remove unavailable calendars`}+ </Button>+ </>+ )}+ {!hasAvailabilityCalendar && (+ <StyledError role="alert">{t`Select at least one available calendar to check for conflicts.`}</StyledError>+ )}+ </StyledFullWidth>+ </FormFieldRow>+ <FormFieldRow+ label={t`Organizer`}+ labelWidth={FIELD_LABEL_WIDTH_PX}+ hasDivider={false}+ >+ <StyledFullWidth>+ <Select+ dropdownId={`${instanceId}-organizer`}+ dropdownWidth={GenericDropdownContentWidth.ExtraLarge}+ fullWidth+ value={value.organizerCalendarId}+ options={calendars.map((calendar) => ({+ value: calendar.id,+ label: calendar.name,+ contextualText: getOrganizerCalendarDescription(calendar),+ disabled: calendar.isDisabled || !calendar.canOrganize,+ }))}+ emptyOption={{+ value: '',+ label: t`Choose an organizer calendar`,+ }}+ disabled={isDisabled || !isNonEmptyArray(calendars)}+ onChange={(organizerCalendarId) =>+ onChange({ ...value, organizerCalendarId })+ }+ withSearchInput+ needIconCheck+ />+ {!hasOrganizerCalendar && (+ <StyledError role="alert">{t`Choose an available calendar that can send invitations.`}</StyledError>+ )}+ </StyledFullWidth>+ </FormFieldRow>+ </StyledFields>+ </Section.Root>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatSchedulingSlots.tsx b/packages/twenty-front/src/modules/ai/components/AiChatSchedulingSlots.tsxnew file mode 100644index 00000000000..801f0b35633--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatSchedulingSlots.tsx@@ -0,0 +1,206 @@+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';+import { fromZonedTime } from 'date-fns-tz';+import { doNotTranslate } from 'twenty-shared/i18n';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';+import { InlineBanner } from 'twenty-ui/components/feedback';+import { IconClock } from 'twenty-ui/icon';+import { Radio, RadioGroup } from 'twenty-ui/primitives/input';+import { ListItem } from 'twenty-ui/primitives/navigation';+import { themeCssVariables } from 'twenty-ui/theme';++import { type AiChatSchedulingAvailability } from '@/ai/types/AiChatSchedulingAvailability';+import { type AiChatSchedulingSlot } from '@/ai/types/AiChatSchedulingSlot';+import { hasMixedTimeZoneOffsets } from '@/ai/utils/hasMixedTimeZoneOffsets';+import { TimeFormat } from '@/localization/constants/TimeFormat';+import { formatTimeZoneLabel } from '@/localization/utils/formatTimeZoneLabel';+import { resolveTimeFormat } from '@/localization/utils/resolveTimeFormat';++const StyledSlots = styled.div`+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[2]};+ min-width: 0;+ padding: ${themeCssVariables.spacing[2]};+`;++const StyledDate = styled.div`+ color: ${themeCssVariables.font.color.tertiary};+ font-size: ${themeCssVariables.font.size.sm};+ padding: 0 ${themeCssVariables.spacing[1]};+`;++const StyledMessage = styled.div`+ color: ${themeCssVariables.font.color.secondary};+ font-size: ${themeCssVariables.font.size.md};+ padding: ${themeCssVariables.spacing[2]};+`;++type AiChatSchedulingSlotsProps = {+ availability: AiChatSchedulingAvailability;+ date: string | null;+ slots: readonly AiChatSchedulingSlot[];+ selectedSlotId: string | null;+ onSlotChange: (slotId: string | null) => void;+ onRetry: () => void;+ timeZone: string;+ locale: string;+ timeFormat: TimeFormat;+ disabled: boolean;+};++const formatDateLabel = ({+ date,+ locale,+}: {+ date: string | null;+ locale: string;+}) => {+ if (!isDefined(date)) {+ return null;+ }++ return new Intl.DateTimeFormat(locale, {+ weekday: 'long',+ month: 'long',+ day: 'numeric',+ calendar: 'gregory',+ timeZone: doNotTranslate('UTC'),+ }).format(new Date(doNotTranslate(`${date}T00:00:00Z`)));+};++export const AiChatSchedulingSlots = ({+ availability,+ date,+ slots,+ selectedSlotId,+ onSlotChange,+ onRetry,+ timeZone,+ locale,+ timeFormat,+ disabled,+}: AiChatSchedulingSlotsProps) => {+ const { t } = useLingui();+ const dateLabel = formatDateLabel({ date, locale }) ?? t`Choose a date`;+ const resolvedTimeFormat = resolveTimeFormat(timeFormat);+ const timeFormatter = new Intl.DateTimeFormat(locale, {+ hour: resolvedTimeFormat === TimeFormat.HOUR_24 ? '2-digit' : 'numeric',+ minute: '2-digit',+ timeZone,+ hourCycle: resolvedTimeFormat === TimeFormat.HOUR_24 ? 'h23' : 'h12',+ timeZoneName: hasMixedTimeZoneOffsets({ slots, timeZone })+ ? 'short'+ : undefined,+ });+ const selectedSlot = slots.find((slot) => slot.id === selectedSlotId);+ const referenceSlot = selectedSlot ?? slots[0];+ const getTimeZoneReferenceDate = () => {+ if (isDefined(referenceSlot)) {+ return new Date(referenceSlot.startsAt);+ }++ if (isDefined(date)) {+ return fromZonedTime(doNotTranslate(`${date}T12:00:00`), timeZone);+ }++ return undefined;+ };+ const timeZoneLabel = formatTimeZoneLabel({+ timeZone,+ referenceDate: getTimeZoneReferenceDate(),+ });+ const isAvailabilityForSelectedDate =+ isDefined(date) && availability.date === date;+ const isStale = isDefined(date) && !isAvailabilityForSelectedDate;+ const isLoading =+ isAvailabilityForSelectedDate && availability.status === 'loading';+ const isSelectedSlotUnavailable =+ isAvailabilityForSelectedDate &&+ availability.status === 'ready' &&+ isDefined(selectedSlotId) &&+ !isDefined(selectedSlot);++ return (+ <StyledSlots aria-busy={isLoading}>+ <StyledDate>{dateLabel}</StyledDate>+ <StyledDate>{timeZoneLabel}</StyledDate>+ {isAvailabilityForSelectedDate && availability.status === 'error' && (+ <InlineBanner+ role="alert"+ status="error"+ layout="compact"+ action={+ <InlineBanner.Action onClick={onRetry} disabled={disabled}>+ {t`Try again`}+ </InlineBanner.Action>+ }+ >+ {availability.message ??+ t`Calendar availability could not be checked.`}+ </InlineBanner>+ )}+ {isSelectedSlotUnavailable && (+ <InlineBanner role="alert" status="warning" layout="compact">+ {t`That time is no longer available. Choose another time.`}+ </InlineBanner>+ )}+ {isStale && (+ <InlineBanner+ role="status"+ status="info"+ layout="compact"+ action={+ <InlineBanner.Action onClick={onRetry} disabled={disabled}>+ {t`Refresh`}+ </InlineBanner.Action>+ }+ >+ {t`Refresh availability for this date.`}+ </InlineBanner>+ )}+ <div role="status" aria-atomic="true">+ {!isDefined(date) && (+ <StyledMessage>{t`Choose a date to see available times.`}</StyledMessage>+ )}+ {isLoading && (+ <StyledMessage>{t`Checking calendar availability…`}</StyledMessage>+ )}+ {isAvailabilityForSelectedDate &&+ availability.status === 'ready' &&+ !isNonEmptyArray(slots) && (+ <StyledMessage>+ {t`No available times. Choose another date.`}+ </StyledMessage>+ )}+ </div>+ {isNonEmptyArray(slots) && (+ <RadioGroup+ aria-label={t`Available times`}+ value={selectedSlot?.id ?? null}+ onValueChange={onSlotChange}+ disabled={disabled}+ >+ {slots.map((slot) => (+ <Radio.Root+ key={slot.id}+ value={slot.id}+ render={+ <ListItem+ selected={selectedSlotId === slot.id}+ startIcon={<IconClock size={16} aria-hidden="true" />}+ description={slot.isRecommended ? t`Recommended` : undefined}+ />+ }+ >+ {timeFormatter.format(new Date(slot.startsAt))}+ {' – '}+ {timeFormatter.format(new Date(slot.endsAt))}+ </Radio.Root>+ ))}+ </RadioGroup>+ )}+ </StyledSlots>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatTimePickerCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatTimePickerCard.tsxnew file mode 100644index 00000000000..4bcffb07947--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatTimePickerCard.tsx@@ -0,0 +1,257 @@+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';+import { type ReactElement } from 'react';+import {+ getValidTimeZoneOrUndefined,+ isDefined,+ isNonEmptyArray,+} from 'twenty-shared/utils';+import { InlineBanner } from 'twenty-ui/components/feedback';+import { DatePicker } from 'twenty-ui/components/input';+import { IconCalendarEvent } from 'twenty-ui/icon';+import { Button } from 'twenty-ui/primitives/input';+import { Card } from 'twenty-ui/primitives/surfaces';+import { themeCssVariables } from 'twenty-ui/theme';++import { AiChatSchedulingSlots } from '@/ai/components/AiChatSchedulingSlots';+import { type AiChatSchedulingAvailability } from '@/ai/types/AiChatSchedulingAvailability';+import { type AiChatSchedulingSelection } from '@/ai/types/AiChatSchedulingSelection';+import { type TimeFormat } from '@/localization/constants/TimeFormat';+import { detectTimeZone } from '@/localization/utils/detection/detectTimeZone';+import { getDatePickerWeekdayLabels } from '@/localization/utils/getDatePickerWeekdayLabels';+import { formatDisplayList } from '~/utils/format/formatDisplayList';++const CALENDAR_WIDTH_PX = 268;+const STACKED_LAYOUT_WIDTH_PX = 560;+const HINT_MIN_WIDTH_PX = 240;++const StyledTitle = styled.div`+ align-items: center;+ color: ${themeCssVariables.font.color.primary};+ display: flex;+ font-size: ${themeCssVariables.font.size.md};+ font-weight: ${themeCssVariables.font.weight.medium};+ gap: ${themeCssVariables.spacing[2]};+ min-height: ${themeCssVariables.spacing[6]};+ padding-left: ${themeCssVariables.spacing[1]};+`;++const StyledBody = styled.div`+ background: ${themeCssVariables.background.primary};+ border: 1px solid ${themeCssVariables.border.color.medium};+ border-radius: ${themeCssVariables.border.radius.sm};+ container-type: inline-size;+ overflow: hidden;+`;++const StyledLayout = styled.div`+ display: flex;+ min-width: 0;++ @container (max-width: ${STACKED_LAYOUT_WIDTH_PX}px) {+ flex-direction: column;+ }+`;++const StyledCalendar = styled.div`+ border-right: 1px solid ${themeCssVariables.border.color.light};+ flex: 0 0 ${CALENDAR_WIDTH_PX}px;+ min-width: 0;++ @container (max-width: ${STACKED_LAYOUT_WIDTH_PX}px) {+ align-self: center;+ border-right: 0;+ flex-basis: auto;+ max-width: 100%;+ width: ${CALENDAR_WIDTH_PX}px;+ }+`;++const StyledReviewFields = styled.div`+ border-top: 1px solid ${themeCssVariables.border.color.light};+`;++const StyledNotice = styled.div`+ padding: ${themeCssVariables.spacing[2]};+`;++const StyledFooter = styled.div`+ align-items: center;+ display: flex;+ flex-wrap: wrap;+ gap: ${themeCssVariables.spacing[2]};+`;++const StyledHint = styled.div`+ color: ${themeCssVariables.font.color.tertiary};+ flex: 1 1 ${HINT_MIN_WIDTH_PX}px;+ font-size: ${themeCssVariables.font.size.sm};+ overflow-wrap: anywhere;+ padding-left: ${themeCssVariables.spacing[1]};+`;++const StyledActions = styled.div`+ display: flex;+ gap: ${themeCssVariables.spacing[2]};+ margin-left: auto;+`;++type AiChatTimePickerCardProps = {+ title: string;+ hint: string;+ date: string | null;+ onDateChange: (date: string) => void;+ viewedMonth: string;+ onViewedMonthChange: (month: string) => void;+ selectedSlotId: string | null;+ onSlotChange: (slotId: string | null) => void;+ availability: AiChatSchedulingAvailability;+ timeZone: string;+ locale: string;+ timeFormat: TimeFormat;+ weekStart: 0 | 1 | 2 | 3 | 4 | 5 | 6;+ onSendInvite: (selection: AiChatSchedulingSelection) => void;+ onSkip: () => void;+ onRetry: () => void;+ isDateUnavailable?: (date: string) => boolean;+ uncheckedAttendees?: readonly string[];+ reviewFields?: ReactElement;+ disabled?: boolean;+ isSending?: boolean;+};++export const AiChatTimePickerCard = ({+ title,+ hint,+ date,+ onDateChange,+ viewedMonth,+ onViewedMonthChange,+ selectedSlotId,+ onSlotChange,+ availability,+ timeZone,+ locale,+ timeFormat,+ weekStart,+ onSendInvite,+ onSkip,+ onRetry,+ isDateUnavailable,+ uncheckedAttendees = [],+ reviewFields,+ disabled = false,+ isSending = false,+}: AiChatTimePickerCardProps) => {+ const { t } = useLingui();+ const resolvedTimeZone =+ getValidTimeZoneOrUndefined(timeZone) ?? detectTimeZone();+ const slots =+ availability.status === 'ready' && availability.date === date+ ? availability.slots+ : [];+ const selectedSlot = slots.find((slot) => slot.id === selectedSlotId);+ const areControlsDisabled = disabled || isSending;+ const canSend =+ isDefined(date) && isDefined(selectedSlot) && !areControlsDisabled;+ const uncheckedAttendeeList = formatDisplayList([...uncheckedAttendees]);++ const handleDateChange = (nextDate: string) => {+ onDateChange(nextDate);+ onSlotChange(null);+ };++ const handleSend = () => {+ if (!canSend || !isDefined(date) || !isDefined(selectedSlot)) {+ return;+ }++ onSendInvite({ date, slotId: selectedSlot.id, timeZone: resolvedTimeZone });+ };++ return (+ <Card.Root fullWidth variant="compact" role="group" aria-label={title}>+ <Card.Header>+ <StyledTitle>+ <IconCalendarEvent+ size={16}+ color={themeCssVariables.font.color.secondary}+ aria-hidden="true"+ />+ {title}+ </StyledTitle>+ </Card.Header>+ <Card.Content>+ <StyledBody>+ <StyledLayout>+ <StyledCalendar>+ <DatePicker+ aria-label={t`Choose a date`}+ value={date}+ onValueChange={handleDateChange}+ viewedMonth={viewedMonth}+ onViewedMonthChange={onViewedMonthChange}+ weekStart={weekStart}+ locale={locale}+ weekdayLabels={getDatePickerWeekdayLabels(locale)}+ previousMonthLabel={t`Previous month`}+ nextMonthLabel={t`Next month`}+ monthLabel={t`Month`}+ yearLabel={t`Year`}+ isDateUnavailable={isDateUnavailable}+ disabled={areControlsDisabled}+ />+ </StyledCalendar>+ <AiChatSchedulingSlots+ availability={availability}+ date={date}+ slots={slots}+ selectedSlotId={selectedSlotId}+ onSlotChange={onSlotChange}+ onRetry={onRetry}+ timeZone={resolvedTimeZone}+ locale={locale}+ timeFormat={timeFormat}+ disabled={areControlsDisabled}+ />+ </StyledLayout>+ {isNonEmptyArray(uncheckedAttendees) && (+ <StyledNotice>+ <InlineBanner status="warning" layout="compact">+ {t`Availability was not checked for ${uncheckedAttendeeList}. You can still send an invite.`}+ </InlineBanner>+ </StyledNotice>+ )}+ {isDefined(reviewFields) && (+ <StyledReviewFields>{reviewFields}</StyledReviewFields>+ )}+ </StyledBody>+ </Card.Content>+ <Card.Footer divider={false}>+ <StyledFooter>+ <StyledHint>{hint}</StyledHint>+ <StyledActions>+ <Button+ size="sm"+ variant="outline"+ disabled={areControlsDisabled}+ onClick={onSkip}+ >+ {t`Skip`}+ </Button>+ <Button+ size="sm"+ color="accent"+ variant="solid"+ disabled={!canSend}+ loading={isSending}+ onClick={handleSend}+ >+ {t`Send invite`}+ </Button>+ </StyledActions>+ </StyledFooter>+ </Card.Footer>+ </Card.Root>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatSchedulingPreferences.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatSchedulingPreferences.stories.tsxnew file mode 100644index 00000000000..f35fa9f2175--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatSchedulingPreferences.stories.tsx@@ -0,0 +1,280 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { type ComponentProps, useState } from 'react';+import { expect, fn, userEvent, within } from 'storybook/test';+import { ComponentDecorator } from 'twenty-ui/testing';++import { AiChatSchedulingPreferences } from '@/ai/components/AiChatSchedulingPreferences';+import { type AiChatSchedulingCalendar } from '@/ai/types/AiChatSchedulingCalendar';+import { type AiChatSchedulingPreferencesValue } from '@/ai/types/AiChatSchedulingPreferencesValue';+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';+import { RootDecorator } from '~/testing/decorators/RootDecorator';++const CALENDARS: AiChatSchedulingCalendar[] = [+ {+ id: 'work',+ name: 'Work calendar',+ description: '[email protected]',+ canOrganize: true,+ },+ {+ id: 'personal',+ name: 'Personal calendar',+ description: 'Private events',+ canOrganize: true,+ },+ { id: 'team', name: 'Team calendar', canOrganize: false },+ {+ id: 'disconnected',+ name: 'Old calendar',+ canOrganize: true,+ isDisabled: true,+ },+];++const PREFERENCES: AiChatSchedulingPreferencesValue = {+ timeZone: 'Europe/Paris',+ workingDays: [1, 2, 3, 4, 5],+ workingHoursStart: '09:00',+ workingHoursEnd: '18:00',+ availabilityCalendarIds: ['work'],+ organizerCalendarId: 'work',+};++const PreferencesExample = ({+ value: initialValue,+ calendars,+ timeZoneOptions,+ onChange,+ isDisabled,+}: ComponentProps<typeof AiChatSchedulingPreferences>) => {+ const [value, setValue] = useState(initialValue);++ return (+ <AiChatSchedulingPreferences+ value={value}+ calendars={calendars}+ timeZoneOptions={timeZoneOptions}+ onChange={(nextValue) => {+ setValue(nextValue);+ onChange(nextValue);+ }}+ isDisabled={isDisabled}+ />+ );+};++const meta = {+ title: 'Modules/AI/AiChatSchedulingPreferences',+ component: PreferencesExample,+ decorators: [ComponentDecorator, MemoryRouterDecorator, RootDecorator],+ parameters: { container: { width: 680 } },+ args: {+ value: PREFERENCES,+ calendars: CALENDARS,+ timeZoneOptions: [+ { value: 'Europe/Paris', label: 'Paris (GMT+01:00)' },+ { value: 'America/New_York', label: 'New York (GMT-05:00)' },+ { value: 'Asia/Tokyo', label: 'Tokyo (GMT+09:00)' },+ ],+ onChange: fn(),+ },+} satisfies Meta<typeof PreferencesExample>;++export default meta;++type Story = StoryObj<typeof meta>;++export const Editable: Story = {+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(canvas.getByRole('checkbox', { name: 'Monday' }));+ await expect(args.onChange).toHaveBeenLastCalledWith({+ ...PREFERENCES,+ workingDays: [2, 3, 4, 5],+ });++ await userEvent.click(+ canvas.getByRole('checkbox', { name: /Personal calendar/ }),+ );+ await expect(args.onChange).toHaveBeenLastCalledWith({+ ...PREFERENCES,+ workingDays: [2, 3, 4, 5],+ availabilityCalendarIds: ['work', 'personal'],+ });++ await userEvent.click(+ within(canvas.getByRole('group', { name: 'Organizer' })).getByRole(+ 'button',+ { name: /Work calendar/ },+ ),+ );+ const page = within(canvasElement.ownerDocument.body);+ await expect(+ page.getByRole('option', { name: /Team calendar/ }),+ ).toBeDisabled();+ await userEvent.click(+ page.getByRole('option', { name: /Personal calendar/ }),+ );+ await expect(args.onChange).toHaveBeenLastCalledWith({+ ...PREFERENCES,+ workingDays: [2, 3, 4, 5],+ availabilityCalendarIds: ['work', 'personal'],+ organizerCalendarId: 'personal',+ });++ const unavailableCalendar = canvas.getByRole('checkbox', {+ name: /Old calendar/,+ });++ await expect(unavailableCalendar).toHaveAttribute('aria-disabled', 'true');+ await userEvent.click(unavailableCalendar);+ await expect(args.onChange).toHaveBeenCalledTimes(3);++ await userEvent.type(+ canvas.getByRole('searchbox', { name: 'Search availability calendars' }),+ 'Personal',+ );+ await expect(+ canvas.getByRole('checkbox', { name: /Personal calendar/ }),+ ).toBeChecked();+ await expect(+ canvas.queryByRole('checkbox', { name: /Work calendar/ }),+ ).not.toBeInTheDocument();+ },+};++export const SearchTimeZone: Story = {+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(canvas.getByText('Paris (GMT+01:00)'));+ const page = within(canvasElement.ownerDocument.body);+ await userEvent.type(+ page.getByRole('searchbox', { name: 'Search' }),+ 'Tokyo',+ );+ await userEvent.click(+ page.getByRole('option', { name: 'Tokyo (GMT+09:00)' }),+ );+ await expect(args.onChange).toHaveBeenLastCalledWith({+ ...PREFERENCES,+ timeZone: 'Asia/Tokyo',+ });+ },+};++export const InvalidPreferences: Story = {+ args: {+ value: {+ ...PREFERENCES,+ workingDays: [],+ workingHoursStart: '18:00',+ workingHoursEnd: '09:00',+ availabilityCalendarIds: [],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(+ canvas.getByText('Select at least one working day.'),+ ).toBeVisible();+ await expect(+ canvas.getByText('End time must be after start time.'),+ ).toBeVisible();+ await expect(+ canvas.getByText(+ 'Select at least one available calendar to check for conflicts.',+ ),+ ).toBeVisible();++ await userEvent.click(canvas.getByRole('checkbox', { name: 'Monday' }));+ await expect(+ canvas.queryByText('Select at least one working day.'),+ ).not.toBeInTheDocument();+ },+};++export const MissingWorkingHours: Story = {+ args: { value: { ...PREFERENCES, workingHoursStart: '' } },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByText('Enter a start and end time.')).toBeVisible();+ await expect(+ canvas.queryByText('End time must be after start time.'),+ ).not.toBeInTheDocument();+ },+};++export const TimeZoneAlias: Story = {+ args: {+ value: { ...PREFERENCES, timeZone: 'America/Buenos_Aires' },+ timeZoneOptions: [+ { value: 'Europe/Paris', label: 'Paris (GMT+01:00)' },+ {+ value: 'America/Argentina/Buenos_Aires',+ label: 'Buenos Aires (GMT-03:00)',+ },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByText('Buenos Aires (GMT-03:00)')).toBeVisible();+ await expect(+ canvas.queryByText('Choose a time zone.'),+ ).not.toBeInTheDocument();+ },+};++export const UnlistedTimeZone: Story = {+ args: { value: { ...PREFERENCES, timeZone: 'Europe/Berlin' } },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByText(/Berlin/)).toBeVisible();+ await expect(+ canvas.queryByText('Choose a time zone.'),+ ).not.toBeInTheDocument();+ },+};++export const NoCalendars: Story = {+ args: {+ calendars: [],+ value: {+ ...PREFERENCES,+ availabilityCalendarIds: [],+ organizerCalendarId: '',+ },+ },+};++export const UnavailableSelection: Story = {+ args: {+ value: {+ ...PREFERENCES,+ availabilityCalendarIds: ['work', 'removed', 'disconnected'],+ },+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(+ canvas.getByText('Some selected calendars are no longer available.'),+ ).toBeVisible();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Remove unavailable calendars' }),+ );+ await expect(args.onChange).toHaveBeenLastCalledWith(PREFERENCES);+ await expect(+ canvas.queryByText('Some selected calendars are no longer available.'),+ ).not.toBeInTheDocument();+ },+};++export const Disabled: Story = {+ args: { isDisabled: true },+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatTimePickerCard.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatTimePickerCard.stories.tsxnew file mode 100644index 00000000000..fd9734af817--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatTimePickerCard.stories.tsx@@ -0,0 +1,425 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';+import { FormFieldRow } from 'twenty-ui/components/input';+import { Text } from 'twenty-ui/primitives/typography';+import { ComponentDecorator } from 'twenty-ui/testing';++import { AiChatTimePickerExample } from '@/ai/components/__stories__/AiChatTimePickerExample';+import { AI_CHAT_TIME_PICKER_FIXTURE } from '@/ai/components/__stories__/aiChatTimePickerFixture';+import { TimeFormat } from '@/localization/constants/TimeFormat';+import { ARGOS_CAPTURE_DISABLED } from '~/testing/constants/ArgosCaptureDisabled';+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';+import { RootDecorator } from '~/testing/decorators/RootDecorator';++const meta = {+ title: 'Modules/AI/AiChatTimePickerCard',+ component: AiChatTimePickerExample,+ decorators: [ComponentDecorator, MemoryRouterDecorator, RootDecorator],+ parameters: { container: { width: 688 }, argos: { fitToContent: false } },+ play: async ({ canvasElement }) => {+ await within(canvasElement).findByRole('combobox', { name: 'Month' });+ },+ args: {+ onDateChange: fn(),+ onViewedMonthChange: fn(),+ onSlotChange: fn(),+ onSendInvite: fn(),+ onSkip: fn(),+ onRetry: fn(),+ },+} satisfies Meta<typeof AiChatTimePickerExample>;++export default meta;++type Story = StoryObj<typeof meta>;++export const Default: Story = {+ args: { initialSelectedSlotId: 'slot-1100' },+};++export const LocalizedTimeAndDate: Story = {+ args: {+ timeZone: 'America/Los_Angeles',+ timeFormat: TimeFormat.HOUR_12,+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByText('Wednesday, October 7')).toBeVisible();+ await expect(+ canvas.getByText('(GMT-07:00) Pacific Daylight Time - Los Angeles'),+ ).toBeVisible();+ await expect(+ canvas.getByRole('radio', { name: /12:30 AM.*1:00 AM/ }),+ ).toBeVisible();+ },+};++export const MidnightUsesZeroHour: Story = {+ args: { timeZone: 'America/Los_Angeles' },+ play: async ({ canvasElement }) => {+ await expect(+ within(canvasElement).getByRole('radio', { name: '00:30 – 01:00' }),+ ).toBeVisible();+ },+};++export const DaylightSavingSelection: Story = {+ args: {+ timeZone: 'America/Los_Angeles',+ initialDate: '2026-11-01',+ initialViewedMonth: '2026-11',+ initialSelectedSlotId: 'before-clock-change',+ initialAvailability: {+ status: 'ready',+ date: '2026-11-01',+ slots: [+ {+ id: 'before-clock-change',+ startsAt: '2026-11-01T08:00:00Z',+ endsAt: '2026-11-01T08:30:00Z',+ },+ {+ id: 'after-clock-change',+ startsAt: '2026-11-01T09:00:00Z',+ endsAt: '2026-11-01T09:30:00Z',+ },+ ],+ },+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(+ canvas.getByText('(GMT-07:00) Pacific Daylight Time - Los Angeles'),+ ).toBeVisible();+ await expect(+ canvas.getByRole('radio', { name: '01:00 PDT – 01:30 PDT' }),+ ).toBeChecked();+ await userEvent.click(+ canvas.getByRole('radio', { name: '01:00 PST – 01:30 PST' }),+ );+ await expect(+ canvas.getByText('(GMT-08:00) Pacific Standard Time - Los Angeles'),+ ).toBeVisible();+ await userEvent.click(canvas.getByRole('button', { name: 'Send invite' }));+ await expect(args.onSendInvite).toHaveBeenCalledWith({+ date: '2026-11-01',+ slotId: 'after-clock-change',+ timeZone: 'America/Los_Angeles',+ });+ },+};++export const SystemTimeZone: Story = {+ args: { timeZone: 'system', initialSelectedSlotId: 'slot-1100' },+ parameters: { argos: ARGOS_CAPTURE_DISABLED },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(canvas.getByRole('button', { name: 'Send invite' }));+ await expect(args.onSendInvite).toHaveBeenCalledWith({+ date: AI_CHAT_TIME_PICKER_FIXTURE.date,+ slotId: 'slot-1100',+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ });+ },+};++export const NoDateSelected: Story = {+ args: { initialDate: null },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByText('Choose a date')).toBeVisible();+ await expect(+ canvas.getByText('Choose a date to see available times.'),+ ).toBeVisible();+ await expect(+ canvas.queryByRole('button', { name: 'Refresh' }),+ ).not.toBeInTheDocument();+ await expect(+ canvas.getByRole('button', { name: 'Send invite' }),+ ).toBeDisabled();+ },+};++export const SelectAndSend: Story = {+ args: { initialSelectedSlotId: null },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const sendInvite = canvas.getByRole('button', { name: 'Send invite' });+ const recommendedTime = canvas.getByRole('radio', { name: /11:00.*11:30/ });++ await expect(sendInvite).toBeDisabled();+ await userEvent.click(recommendedTime);+ await expect(recommendedTime).toBeChecked();+ await expect(args.onSlotChange).toHaveBeenCalledWith('slot-1100');+ await expect(sendInvite).toBeEnabled();+ await userEvent.click(sendInvite);+ await expect(args.onSendInvite).toHaveBeenCalledTimes(1);+ await expect(args.onSendInvite).toHaveBeenCalledWith({+ date: AI_CHAT_TIME_PICKER_FIXTURE.date,+ slotId: 'slot-1100',+ timeZone: AI_CHAT_TIME_PICKER_FIXTURE.timeZone,+ });+ },+};++export const BrowseMonthAndChangeDate: Story = {+ args: { initialSelectedSlotId: 'slot-1100' },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const sendInvite = canvas.getByRole('button', { name: 'Send invite' });++ await userEvent.click(+ await canvas.findByRole('button', { name: 'Next month' }),+ );+ await waitFor(() =>+ expect(args.onViewedMonthChange).toHaveBeenCalledWith('2026-11'),+ );+ await expect(+ canvas.getByRole('radio', { name: /11:00.*11:30/ }),+ ).toBeChecked();+ await expect(sendInvite).toBeEnabled();+ await expect(args.onDateChange).not.toHaveBeenCalled();+ await expect(args.onSlotChange).not.toHaveBeenCalled();++ await userEvent.click(+ canvas.getByRole('button', { name: 'Previous month' }),+ );+ await userEvent.click(+ await canvas.findByRole('gridcell', {+ name: 'Choose Thursday, October 8th, 2026',+ }),+ );+ await waitFor(() =>+ expect(args.onDateChange).toHaveBeenCalledWith('2026-10-08'),+ );+ await expect(args.onSlotChange).toHaveBeenCalledTimes(1);+ await expect(args.onSlotChange).toHaveBeenCalledWith(null);+ await expect(sendInvite).toBeDisabled();+ await expect(canvas.queryByRole('radio')).not.toBeInTheDocument();+ await expect(args.onSendInvite).not.toHaveBeenCalled();+ },+};++export const StaleAvailability: Story = {+ args: {+ initialDate: '2026-10-08',+ initialSelectedSlotId: 'slot-1100',+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const sendInvite = canvas.getByRole('button', { name: 'Send invite' });++ await expect(canvas.queryByRole('radio')).not.toBeInTheDocument();+ await expect(sendInvite).toBeDisabled();+ await userEvent.click(sendInvite);+ await expect(args.onSendInvite).not.toHaveBeenCalled();+ await expect(+ canvas.getByText('Refresh availability for this date.'),+ ).toBeVisible();+ await userEvent.click(canvas.getByRole('button', { name: 'Refresh' }));+ await expect(args.onRetry).toHaveBeenCalledTimes(1);+ },+};++export const AvailabilityChanged: Story = {+ args: {+ initialSelectedSlotId: 'slot-1100',+ availabilityAfterRefresh: {+ status: 'ready',+ date: AI_CHAT_TIME_PICKER_FIXTURE.date,+ slots: AI_CHAT_TIME_PICKER_FIXTURE.availability.slots.filter(+ ({ id }) => id !== 'slot-1100',+ ),+ },+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const sendInvite = canvas.getByRole('button', { name: 'Send invite' });++ await expect(sendInvite).toBeEnabled();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Refresh availability' }),+ );+ await expect(+ canvas.getByText(+ 'That time is no longer available. Choose another time.',+ ),+ ).toBeVisible();+ await expect(sendInvite).toBeDisabled();+ await expect(+ canvas.queryByRole('radio', { name: /11:00.*11:30/ }),+ ).not.toBeInTheDocument();+ await expect(args.onSendInvite).not.toHaveBeenCalled();++ const afternoonTime = canvas.getByRole('radio', { name: /14:00.*14:30/ });++ await userEvent.click(afternoonTime);+ await expect(afternoonTime).toBeChecked();+ await expect(+ canvas.queryByText(+ 'That time is no longer available. Choose another time.',+ ),+ ).not.toBeInTheDocument();+ await expect(sendInvite).toBeEnabled();+ await userEvent.click(sendInvite);+ await expect(args.onSendInvite).toHaveBeenCalledTimes(1);+ await expect(args.onSendInvite).toHaveBeenCalledWith({+ date: AI_CHAT_TIME_PICKER_FIXTURE.date,+ slotId: 'slot-1400',+ timeZone: AI_CHAT_TIME_PICKER_FIXTURE.timeZone,+ });+ },+};++export const AvailabilityError: Story = {+ args: {+ initialAvailability: {+ status: 'error',+ date: AI_CHAT_TIME_PICKER_FIXTURE.date,+ message: 'Your calendar could not be reached.',+ },+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(+ canvas.getByText('Your calendar could not be reached.'),+ ).toBeVisible();+ await expect(+ canvas.getByRole('button', { name: 'Send invite' }),+ ).toBeDisabled();+ await userEvent.click(canvas.getByRole('button', { name: 'Try again' }));+ await expect(args.onRetry).toHaveBeenCalledTimes(1);+ await userEvent.click(canvas.getByRole('button', { name: 'Skip' }));+ await expect(args.onSkip).toHaveBeenCalledTimes(1);+ await expect(args.onSendInvite).not.toHaveBeenCalled();++ await userEvent.click(+ await canvas.findByRole('gridcell', {+ name: 'Choose Thursday, October 8th, 2026',+ }),+ );+ await expect(+ canvas.queryByText('Your calendar could not be reached.'),+ ).not.toBeInTheDocument();+ await expect(+ canvas.getByText('Refresh availability for this date.'),+ ).toBeVisible();+ },+};++export const Disabled: Story = {+ args: { disabled: true, initialSelectedSlotId: 'slot-1100' },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(+ canvas.getByRole('button', { name: 'Send invite' }),+ ).toBeDisabled();+ await expect(canvas.getByRole('button', { name: 'Skip' })).toBeDisabled();+ await expect(+ await canvas.findByRole('button', { name: 'Next month' }),+ ).toBeDisabled();+ await expect(+ canvas.getByRole('combobox', { name: 'Month' }),+ ).toBeDisabled();+ await userEvent.click(canvas.getByRole('radio', { name: /14:00.*14:30/ }));+ await userEvent.click(+ canvas.getByRole('gridcell', {+ name: 'Not available Thursday, October 8th, 2026',+ }),+ );+ await expect(args.onSlotChange).not.toHaveBeenCalled();+ await expect(args.onDateChange).not.toHaveBeenCalled();+ await expect(args.onSendInvite).not.toHaveBeenCalled();+ },+};++export const Sending: Story = {+ args: { isSending: true, initialSelectedSlotId: 'slot-1100' },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const sendInvite = canvas.getByRole('button', { name: 'Send invite' });++ await expect(sendInvite).toBeDisabled();+ await expect(sendInvite).toHaveAttribute('aria-busy', 'true');+ await expect(canvas.getByRole('button', { name: 'Skip' })).toBeDisabled();+ await expect(+ await canvas.findByRole('button', { name: 'Next month' }),+ ).toBeDisabled();+ await userEvent.click(sendInvite);+ await expect(args.onSendInvite).not.toHaveBeenCalled();+ },+};++export const Loading: Story = {+ args: {+ initialAvailability: {+ status: 'loading',+ date: AI_CHAT_TIME_PICKER_FIXTURE.date,+ },+ },+};++export const Empty: Story = {+ args: {+ initialAvailability: {+ status: 'ready',+ date: AI_CHAT_TIME_PICKER_FIXTURE.date,+ slots: [],+ },+ },+};++export const UncheckedAttendees: Story = {+ args: {+ uncheckedAttendees: ['[email protected]'],+ initialSelectedSlotId: 'slot-1100',+ },+};++export const CalendarReviewFields: Story = {+ args: {+ reviewFields: (+ <>+ <FormFieldRow label="Time zone">+ <Text>Europe/Paris</Text>+ </FormFieldRow>+ <FormFieldRow label="Availability calendars">+ <Text>Work calendar, Personal calendar</Text>+ </FormFieldRow>+ <FormFieldRow label="Organizer" hasDivider={false}>+ <Text>[email protected]</Text>+ </FormFieldRow>+ </>+ ),+ },+};++export const Narrow: Story = {+ parameters: { container: { width: 344 } },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await canvas.findByRole('gridcell', {+ name: 'Choose Wednesday, October 7th, 2026',+ });++ const card = canvas.getByRole('group', {+ name: 'Call with Patrick Collison · 30 min',+ });+ const calendar = within(card).getByRole('group', { name: 'Choose a date' });+ const times = canvas.getByRole('radiogroup', { name: 'Available times' });+ const calendarBounds = calendar.getBoundingClientRect();+ const timesBounds = times.getBoundingClientRect();+ const cardBounds = card.getBoundingClientRect();++ await expect(timesBounds.top).toBeGreaterThanOrEqual(calendarBounds.bottom);+ await expect(timesBounds.right).toBeLessThanOrEqual(cardBounds.right);+ await expect(card.scrollWidth).toBeLessThanOrEqual(card.clientWidth);+ },+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatTimePickerExample.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatTimePickerExample.tsxnew file mode 100644index 00000000000..b2bedc70366--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatTimePickerExample.tsx@@ -0,0 +1,111 @@+import { styled } from '@linaria/react';+import { type ReactElement, useState } from 'react';+import { isDefined } from 'twenty-shared/utils';+import { Button } from 'twenty-ui/primitives/input';+import { themeCssVariables } from 'twenty-ui/theme';++import { AiChatTimePickerCard } from '@/ai/components/AiChatTimePickerCard';+import { AI_CHAT_TIME_PICKER_FIXTURE } from '@/ai/components/__stories__/aiChatTimePickerFixture';+import { type AiChatSchedulingAvailability } from '@/ai/types/AiChatSchedulingAvailability';+import { type AiChatSchedulingSelection } from '@/ai/types/AiChatSchedulingSelection';+import { TimeFormat } from '@/localization/constants/TimeFormat';++const StyledExample = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[3]};+ min-width: 0;+ width: 100%;+`;++type AiChatTimePickerExampleProps = {+ initialDate?: string | null;+ initialViewedMonth?: string;+ initialSelectedSlotId?: string | null;+ initialAvailability?: AiChatSchedulingAvailability;+ availabilityAfterRefresh?: AiChatSchedulingAvailability;+ uncheckedAttendees?: readonly string[];+ disabled?: boolean;+ isSending?: boolean;+ reviewFields?: ReactElement;+ timeZone?: string;+ locale?: string;+ timeFormat?: TimeFormat;+ onDateChange: (date: string) => void;+ onViewedMonthChange: (month: string) => void;+ onSlotChange: (slotId: string | null) => void;+ onSendInvite: (selection: AiChatSchedulingSelection) => void;+ onSkip: () => void;+ onRetry: () => void;+};++export const AiChatTimePickerExample = ({+ initialDate = AI_CHAT_TIME_PICKER_FIXTURE.date,+ initialViewedMonth = AI_CHAT_TIME_PICKER_FIXTURE.viewedMonth,+ initialSelectedSlotId = null,+ initialAvailability = AI_CHAT_TIME_PICKER_FIXTURE.availability,+ availabilityAfterRefresh,+ uncheckedAttendees,+ disabled,+ isSending,+ reviewFields,+ timeZone = AI_CHAT_TIME_PICKER_FIXTURE.timeZone,+ locale = 'en-US',+ timeFormat = TimeFormat.HOUR_24,+ onDateChange,+ onViewedMonthChange,+ onSlotChange,+ onSendInvite,+ onSkip,+ onRetry,+}: AiChatTimePickerExampleProps) => {+ const [date, setDate] = useState(initialDate);+ const [viewedMonth, setViewedMonth] = useState(initialViewedMonth);+ const [selectedSlotId, setSelectedSlotId] = useState(initialSelectedSlotId);+ const [availability, setAvailability] = useState(initialAvailability);++ return (+ <StyledExample>+ <AiChatTimePickerCard+ title="Call with Patrick Collison · 30 min"+ hint="Invite goes to [email protected] with a meeting link"+ date={date}+ onDateChange={(nextDate) => {+ setDate(nextDate);+ onDateChange(nextDate);+ }}+ viewedMonth={viewedMonth}+ onViewedMonthChange={(nextMonth) => {+ setViewedMonth(nextMonth);+ onViewedMonthChange(nextMonth);+ }}+ selectedSlotId={selectedSlotId}+ onSlotChange={(slotId) => {+ setSelectedSlotId(slotId);+ onSlotChange(slotId);+ }}+ availability={availability}+ timeZone={timeZone}+ locale={locale}+ timeFormat={timeFormat}+ weekStart={1}+ onSendInvite={onSendInvite}+ onSkip={onSkip}+ onRetry={onRetry}+ uncheckedAttendees={uncheckedAttendees}+ disabled={disabled}+ isSending={isSending}+ reviewFields={reviewFields}+ />+ {isDefined(availabilityAfterRefresh) && (+ <Button+ size="sm"+ variant="outline"+ onClick={() => setAvailability(availabilityAfterRefresh)}+ >+ Refresh availability+ </Button>+ )}+ </StyledExample>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/aiChatTimePickerFixture.ts b/packages/twenty-front/src/modules/ai/components/__stories__/aiChatTimePickerFixture.tsnew file mode 100644index 00000000000..bc3efc08ca2--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/aiChatTimePickerFixture.ts@@ -0,0 +1,39 @@+import { type AiChatSchedulingAvailability } from '@/ai/types/AiChatSchedulingAvailability';++export const AI_CHAT_TIME_PICKER_FIXTURE = {+ date: '2026-10-07',+ viewedMonth: '2026-10',+ timeZone: 'Europe/Paris',+ availability: {+ status: 'ready',+ date: '2026-10-07',+ slots: [+ {+ id: 'slot-0930',+ startsAt: '2026-10-07T07:30:00Z',+ endsAt: '2026-10-07T08:00:00Z',+ },+ {+ id: 'slot-1100',+ startsAt: '2026-10-07T09:00:00Z',+ endsAt: '2026-10-07T09:30:00Z',+ isRecommended: true,+ },+ {+ id: 'slot-1400',+ startsAt: '2026-10-07T12:00:00Z',+ endsAt: '2026-10-07T12:30:00Z',+ },+ {+ id: 'slot-1600',+ startsAt: '2026-10-07T14:00:00Z',+ endsAt: '2026-10-07T14:30:00Z',+ },+ ],+ },+} as const satisfies {+ date: string;+ viewedMonth: string;+ timeZone: string;+ availability: AiChatSchedulingAvailability;+};diff --git a/packages/twenty-front/src/modules/ai/types/AiChatSchedulingAvailability.ts b/packages/twenty-front/src/modules/ai/types/AiChatSchedulingAvailability.tsnew file mode 100644index 00000000000..280a5534dd0--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AiChatSchedulingAvailability.ts@@ -0,0 +1,10 @@+import { type AiChatSchedulingSlot } from '@/ai/types/AiChatSchedulingSlot';++export type AiChatSchedulingAvailability =+ | { status: 'loading'; date: string }+ | { status: 'error'; date: string; message?: string }+ | {+ status: 'ready';+ date: string;+ slots: readonly AiChatSchedulingSlot[];+ };diff --git a/packages/twenty-front/src/modules/ai/types/AiChatSchedulingCalendar.ts b/packages/twenty-front/src/modules/ai/types/AiChatSchedulingCalendar.tsnew file mode 100644index 00000000000..08bf182de74--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AiChatSchedulingCalendar.ts@@ -0,0 +1,7 @@+export type AiChatSchedulingCalendar = {+ id: string;+ name: string;+ description?: string;+ canOrganize: boolean;+ isDisabled?: boolean;+};diff --git a/packages/twenty-front/src/modules/ai/types/AiChatSchedulingPreferencesValue.ts b/packages/twenty-front/src/modules/ai/types/AiChatSchedulingPreferencesValue.tsnew file mode 100644index 00000000000..58ecbfdd6a3--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AiChatSchedulingPreferencesValue.ts@@ -0,0 +1,8 @@+export type AiChatSchedulingPreferencesValue = {+ timeZone: string;+ workingDays: (1 | 2 | 3 | 4 | 5 | 6 | 7)[];+ workingHoursStart: string;+ workingHoursEnd: string;+ availabilityCalendarIds: string[];+ organizerCalendarId: string;+};diff --git a/packages/twenty-front/src/modules/ai/types/AiChatSchedulingSelection.ts b/packages/twenty-front/src/modules/ai/types/AiChatSchedulingSelection.tsnew file mode 100644index 00000000000..b6ba0fe25d2--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AiChatSchedulingSelection.ts@@ -0,0 +1,5 @@+export type AiChatSchedulingSelection = {+ date: string;+ slotId: string;+ timeZone: string;+};diff --git a/packages/twenty-front/src/modules/ai/types/AiChatSchedulingSlot.ts b/packages/twenty-front/src/modules/ai/types/AiChatSchedulingSlot.tsnew file mode 100644index 00000000000..a64d2fbc5d7--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AiChatSchedulingSlot.ts@@ -0,0 +1,6 @@+export type AiChatSchedulingSlot = {+ id: string;+ startsAt: string;+ endsAt: string;+ isRecommended?: boolean;+};diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/hasMixedTimeZoneOffsets.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/hasMixedTimeZoneOffsets.test.tsnew file mode 100644index 00000000000..1b93ae94028--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/hasMixedTimeZoneOffsets.test.ts@@ -0,0 +1,58 @@+import { hasMixedTimeZoneOffsets } from '@/ai/utils/hasMixedTimeZoneOffsets';++describe('hasMixedTimeZoneOffsets', () => {+ it('should detect slots on both sides of a daylight saving time change', () => {+ expect(+ hasMixedTimeZoneOffsets({+ timeZone: 'America/Los_Angeles',+ slots: [+ {+ id: 'before-clock-change',+ startsAt: '2026-11-01T08:00:00Z',+ endsAt: '2026-11-01T08:30:00Z',+ },+ {+ id: 'after-clock-change',+ startsAt: '2026-11-01T09:00:00Z',+ endsAt: '2026-11-01T09:30:00Z',+ },+ ],+ }),+ ).toBe(true);+ });++ it('should detect a single slot spanning a daylight saving time change', () => {+ expect(+ hasMixedTimeZoneOffsets({+ timeZone: 'America/Los_Angeles',+ slots: [+ {+ id: 'across-clock-change',+ startsAt: '2026-11-01T08:30:00Z',+ endsAt: '2026-11-01T09:00:00Z',+ },+ ],+ }),+ ).toBe(true);+ });++ it('should not flag slots sharing the same offset', () => {+ expect(+ hasMixedTimeZoneOffsets({+ timeZone: 'Europe/Paris',+ slots: [+ {+ id: 'morning',+ startsAt: '2026-10-07T07:30:00Z',+ endsAt: '2026-10-07T08:00:00Z',+ },+ {+ id: 'afternoon',+ startsAt: '2026-10-07T14:00:00Z',+ endsAt: '2026-10-07T14:30:00Z',+ },+ ],+ }),+ ).toBe(false);+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/hasMixedTimeZoneOffsets.ts b/packages/twenty-front/src/modules/ai/utils/hasMixedTimeZoneOffsets.tsnew file mode 100644index 00000000000..d909305bbd8--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/hasMixedTimeZoneOffsets.ts@@ -0,0 +1,24 @@+import { type AiChatSchedulingSlot } from '@/ai/types/AiChatSchedulingSlot';++export const hasMixedTimeZoneOffsets = ({+ slots,+ timeZone,+}: {+ slots: readonly AiChatSchedulingSlot[];+ timeZone: string;+}) => {+ const offsetFormatter = new Intl.DateTimeFormat('en-US', {+ timeZone,+ timeZoneName: 'longOffset',+ });+ const offsets = slots.flatMap(({ startsAt, endsAt }) =>+ [startsAt, endsAt].map(+ (instant) =>+ offsetFormatter+ .formatToParts(new Date(instant))+ .find(({ type }) => type === 'timeZoneName')?.value,+ ),+ );++ return new Set(offsets).size > 1;+};diff --git a/packages/twenty-front/src/modules/keyboard-shortcut-menu/components/__stories__/KeyboardShortcutMenu.stories.tsx b/packages/twenty-front/src/modules/keyboard-shortcut-menu/components/__stories__/KeyboardShortcutMenu.stories.tsxindex 9df6b4bb139..9a1fa71de39 100644--- a/packages/twenty-front/src/modules/keyboard-shortcut-menu/components/__stories__/KeyboardShortcutMenu.stories.tsx+++ b/packages/twenty-front/src/modules/keyboard-shortcut-menu/components/__stories__/KeyboardShortcutMenu.stories.tsx@@ -51,7 +51,7 @@ export const Default: Story = {);}await userEvent.tab();- expect(closeButton).toHaveFocus();+ await waitFor(() => expect(closeButton).toHaveFocus());await userEvent.keyboard('{Escape}');await waitFor(() => expect(dialog).not.toBeInTheDocument());await waitFor(() => expect(trigger).toHaveFocus());diff --git a/packages/twenty-front/src/modules/localization/constants/AvailableTimezoneOptionsByLabel.ts b/packages/twenty-front/src/modules/localization/constants/AvailableTimezoneOptionsByLabel.tsindex f9dd1a96535..f4978daec66 100644--- a/packages/twenty-front/src/modules/localization/constants/AvailableTimezoneOptionsByLabel.ts+++ b/packages/twenty-front/src/modules/localization/constants/AvailableTimezoneOptionsByLabel.ts@@ -1,35 +1,37 @@import { IANA_TIME_ZONES } from 'twenty-shared/constants';+import { AVAILABLE_TIME_ZONE_OPTIONS_REFERENCE_DATE } from '@/localization/constants/AvailableTimezoneOptionsReferenceDate';import { formatTimeZoneLabel } from '@/localization/utils/formatTimeZoneLabel';import { type SelectOption } from 'twenty-ui/primitives/input';import { doNotTranslate } from 'twenty-shared/i18n';const { AVAILABLE_TIME_ZONE_OPTIONS_BY_LABEL } = {- AVAILABLE_TIME_ZONE_OPTIONS_BY_LABEL: IANA_TIME_ZONES.reduce<- Record<string, SelectOption>- >((result, ianaTimeZone) => {- if (- formatTimeZoneLabel(ianaTimeZone)- .slice(11)- .includes(doNotTranslate('GMT')) ||- formatTimeZoneLabel(ianaTimeZone)- .slice(11)- .includes(doNotTranslate('UTC')) ||- formatTimeZoneLabel(ianaTimeZone)- .slice(11)- .includes(doNotTranslate('UCT')) ||- formatTimeZoneLabel(ianaTimeZone) in result- ) {- return result;- }+ AVAILABLE_TIME_ZONE_OPTIONS_BY_LABEL: IANA_TIME_ZONES.map((ianaTimeZone) => ({+ ianaTimeZone,+ timeZoneLabel: formatTimeZoneLabel({+ timeZone: ianaTimeZone,+ referenceDate: AVAILABLE_TIME_ZONE_OPTIONS_REFERENCE_DATE,+ }),+ })).reduce<Record<string, SelectOption>>(+ (result, { ianaTimeZone, timeZoneLabel }) => {+ if (+ timeZoneLabel.slice(11).includes(doNotTranslate('GMT')) ||+ timeZoneLabel.slice(11).includes(doNotTranslate('UTC')) ||+ timeZoneLabel.slice(11).includes(doNotTranslate('UCT')) ||+ timeZoneLabel in result+ ) {+ return result;+ }- return {- ...result,- [formatTimeZoneLabel(ianaTimeZone)]: {- label: formatTimeZoneLabel(ianaTimeZone),- value: ianaTimeZone,- },- };- }, {}),+ return {+ ...result,+ [timeZoneLabel]: {+ label: timeZoneLabel,+ value: ianaTimeZone,+ },+ };+ },+ {},+ ),};export { AVAILABLE_TIME_ZONE_OPTIONS_BY_LABEL };diff --git a/packages/twenty-front/src/modules/localization/constants/AvailableTimezoneOptionsReferenceDate.ts b/packages/twenty-front/src/modules/localization/constants/AvailableTimezoneOptionsReferenceDate.tsnew file mode 100644index 00000000000..b36932d4ae7--- /dev/null+++ b/packages/twenty-front/src/modules/localization/constants/AvailableTimezoneOptionsReferenceDate.ts@@ -0,0 +1 @@+export const AVAILABLE_TIME_ZONE_OPTIONS_REFERENCE_DATE = new Date();diff --git a/packages/twenty-front/src/modules/localization/utils/__tests__/findAvailableTimeZoneOption.test.ts b/packages/twenty-front/src/modules/localization/utils/__tests__/findAvailableTimeZoneOption.test.tsindex 0694d332d52..68125ebd3c6 100644--- a/packages/twenty-front/src/modules/localization/utils/__tests__/findAvailableTimeZoneOption.test.ts+++ b/packages/twenty-front/src/modules/localization/utils/__tests__/findAvailableTimeZoneOption.test.ts@@ -1,6 +1,19 @@import { findAvailableTimeZoneOption } from '@/localization/utils/findAvailableTimeZoneOption';+jest.mock(+ '@/localization/constants/AvailableTimezoneOptionsReferenceDate',+ () => ({+ AVAILABLE_TIME_ZONE_OPTIONS_REFERENCE_DATE: new Date(+ '2026-10-24T12:00:00.000Z',+ ),+ }),+);+describe('findAvailableTimeZoneOption', () => {+ afterEach(() => {+ jest.useRealTimers();+ });+it('should find the matching available IANA time zone select option from a given IANA time zone', () => {const ianaTimeZone = 'Europe/Paris';@@ -11,4 +24,12 @@ describe('findAvailableTimeZoneOption', () => {// We don't test the exact label since it's time-dependent (DST changes)expect(option?.label).toMatch(/^\(GMT[+-]\d{2}:\d{2}\) .+ - Paris$/);});++ it('should still find the option after a daylight saving time change', () => {+ jest.useFakeTimers().setSystemTime(new Date('2026-10-26T12:00:00.000Z'));++ expect(findAvailableTimeZoneOption('Europe/Paris')?.value).toBe(+ 'Europe/Paris',+ );+ });});diff --git a/packages/twenty-front/src/modules/localization/utils/__tests__/formatTimeZoneLabel.test.ts b/packages/twenty-front/src/modules/localization/utils/__tests__/formatTimeZoneLabel.test.tsindex 50def87edb6..7adb380ea99 100644--- a/packages/twenty-front/src/modules/localization/utils/__tests__/formatTimeZoneLabel.test.ts+++ b/packages/twenty-front/src/modules/localization/utils/__tests__/formatTimeZoneLabel.test.ts@@ -6,7 +6,7 @@ describe('formatTimeZoneLabel', () => {const ianaTimeZone = 'Europe/Paris';const expectedLabel = '(GMT+01:00) Central European Standard Time - Paris';- const formattedLabel = formatTimeZoneLabel(ianaTimeZone);+ const formattedLabel = formatTimeZoneLabel({ timeZone: ianaTimeZone });expect(expectedLabel).toEqual(formattedLabel);});@@ -15,8 +15,25 @@ describe('formatTimeZoneLabel', () => {const ianaTimeZone = 'America/New_York';const expectedLabel = '(GMT-05:00) Eastern Standard Time - New York';- const formattedLabel = formatTimeZoneLabel(ianaTimeZone);+ const formattedLabel = formatTimeZoneLabel({ timeZone: ianaTimeZone });expect(formattedLabel).toEqual(expectedLabel);});++ it('should use the reference date offset instead of the current date offset', () => {+ const formattedLabel = formatTimeZoneLabel({+ timeZone: 'Europe/Paris',+ referenceDate: new Date('2024-07-01T12:00:00.000Z'),+ });++ expect(formattedLabel).toBe(+ '(GMT+02:00) Central European Summer Time - Paris',+ );+ });++ it('should preserve the time zone identifier when it cannot be formatted', () => {+ expect(formatTimeZoneLabel({ timeZone: 'Invalid/TimeZone' })).toBe(+ 'Invalid/TimeZone',+ );+ });});diff --git a/packages/twenty-front/src/modules/localization/utils/__tests__/getDatePickerWeekdayLabels.test.ts b/packages/twenty-front/src/modules/localization/utils/__tests__/getDatePickerWeekdayLabels.test.tsnew file mode 100644index 00000000000..1b8a4c69ba3--- /dev/null+++ b/packages/twenty-front/src/modules/localization/utils/__tests__/getDatePickerWeekdayLabels.test.ts@@ -0,0 +1,27 @@+import { getDatePickerWeekdayLabels } from '@/localization/utils/getDatePickerWeekdayLabels';++describe('getDatePickerWeekdayLabels', () => {+ it('should return short weekday labels starting on Sunday', () => {+ expect(getDatePickerWeekdayLabels('en-US')).toEqual([+ 'Sun',+ 'Mon',+ 'Tue',+ 'Wed',+ 'Thu',+ 'Fri',+ 'Sat',+ ]);+ });++ it('should format the weekday labels in the given locale', () => {+ expect(getDatePickerWeekdayLabels('fr-FR')).toEqual([+ 'dim.',+ 'lun.',+ 'mar.',+ 'mer.',+ 'jeu.',+ 'ven.',+ 'sam.',+ ]);+ });+});diff --git a/packages/twenty-front/src/modules/localization/utils/__tests__/getValidPlainTimeOrUndefined.test.ts b/packages/twenty-front/src/modules/localization/utils/__tests__/getValidPlainTimeOrUndefined.test.tsnew file mode 100644index 00000000000..17fd6744d36--- /dev/null+++ b/packages/twenty-front/src/modules/localization/utils/__tests__/getValidPlainTimeOrUndefined.test.ts@@ -0,0 +1,16 @@+import { getValidPlainTimeOrUndefined } from '@/localization/utils/getValidPlainTimeOrUndefined';++describe('getValidPlainTimeOrUndefined', () => {+ it('should parse times with or without seconds', () => {+ expect(getValidPlainTimeOrUndefined('09:30')?.toString()).toBe('09:30:00');+ expect(getValidPlainTimeOrUndefined('18:00:00')?.toString()).toBe(+ '18:00:00',+ );+ });++ it('should return undefined for an empty or malformed time', () => {+ expect(getValidPlainTimeOrUndefined('')).toBeUndefined();+ expect(getValidPlainTimeOrUndefined('25:00')).toBeUndefined();+ expect(getValidPlainTimeOrUndefined('not a time')).toBeUndefined();+ });+});diff --git a/packages/twenty-front/src/modules/localization/utils/findAvailableTimeZoneOption.ts b/packages/twenty-front/src/modules/localization/utils/findAvailableTimeZoneOption.tsindex d1336c3aaff..484fe94c3e7 100644--- a/packages/twenty-front/src/modules/localization/utils/findAvailableTimeZoneOption.ts+++ b/packages/twenty-front/src/modules/localization/utils/findAvailableTimeZoneOption.ts@@ -1,5 +1,11 @@import { formatTimeZoneLabel } from '@/localization/utils/formatTimeZoneLabel';import { AVAILABLE_TIME_ZONE_OPTIONS_BY_LABEL } from '@/localization/constants/AvailableTimezoneOptionsByLabel';+import { AVAILABLE_TIME_ZONE_OPTIONS_REFERENCE_DATE } from '@/localization/constants/AvailableTimezoneOptionsReferenceDate';export const findAvailableTimeZoneOption = (value: string) =>- AVAILABLE_TIME_ZONE_OPTIONS_BY_LABEL[formatTimeZoneLabel(value)];+ AVAILABLE_TIME_ZONE_OPTIONS_BY_LABEL[+ formatTimeZoneLabel({+ timeZone: value,+ referenceDate: AVAILABLE_TIME_ZONE_OPTIONS_REFERENCE_DATE,+ })+ ];diff --git a/packages/twenty-front/src/modules/localization/utils/formatTimeZoneLabel.ts b/packages/twenty-front/src/modules/localization/utils/formatTimeZoneLabel.tsindex 8213d2003fa..723a951a62b 100644--- a/packages/twenty-front/src/modules/localization/utils/formatTimeZoneLabel.ts+++ b/packages/twenty-front/src/modules/localization/utils/formatTimeZoneLabel.ts@@ -1,29 +1,36 @@import { formatInTimeZone } from 'date-fns-tz';import { enUS as defaultLocale } from 'date-fns/locale/en-US';+import { isNonEmptyString } from '@sniptt/guards';import { doNotTranslate } from 'twenty-shared/i18n';// 'Europe/Paris' => '(GMT+01:00) Central European Time - Paris'-export const formatTimeZoneLabel = (ianaTimeZone: string) => {+export const formatTimeZoneLabel = ({+ timeZone,+ referenceDate = new Date(),+}: {+ timeZone: string;+ referenceDate?: Date;+}) => {let timeZoneWithGmtOffset: string;try {timeZoneWithGmtOffset = formatInTimeZone(- Date.now(),- ianaTimeZone,+ referenceDate,+ timeZone,doNotTranslate(`(OOOO) zzzz`),{ locale: defaultLocale },);} catch {- return ianaTimeZone;+ return timeZone;}- const ianaTimeZoneParts = ianaTimeZone.split('/');+ const ianaTimeZoneParts = timeZone.split('/');const location =ianaTimeZoneParts.length > 1? ianaTimeZoneParts.slice(-1)[0].replaceAll('_', ' '): undefined;const timeZoneLabel =- !location || timeZoneWithGmtOffset.includes(location)+ !isNonEmptyString(location) || timeZoneWithGmtOffset.includes(location)? timeZoneWithGmtOffset: [timeZoneWithGmtOffset, location].join(' - ');diff --git a/packages/twenty-front/src/modules/localization/utils/getDatePickerWeekdayLabels.ts b/packages/twenty-front/src/modules/localization/utils/getDatePickerWeekdayLabels.tsnew file mode 100644index 00000000000..42b1a4cc15c--- /dev/null+++ b/packages/twenty-front/src/modules/localization/utils/getDatePickerWeekdayLabels.ts@@ -0,0 +1,28 @@+import { doNotTranslate } from 'twenty-shared/i18n';+import { type DatePickerProps } from 'twenty-ui/components/input';++const REFERENCE_SUNDAY_TIMESTAMP = Date.UTC(2023, 0, 1);+const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;++export const getDatePickerWeekdayLabels = (+ locale: string,+): NonNullable<DatePickerProps['weekdayLabels']> => {+ const weekdayFormatter = new Intl.DateTimeFormat(locale, {+ weekday: 'short',+ timeZone: doNotTranslate('UTC'),+ });+ const formatWeekday = (dayIndex: number) =>+ weekdayFormatter.format(+ new Date(REFERENCE_SUNDAY_TIMESTAMP + dayIndex * MILLISECONDS_PER_DAY),+ );++ return [+ formatWeekday(0),+ formatWeekday(1),+ formatWeekday(2),+ formatWeekday(3),+ formatWeekday(4),+ formatWeekday(5),+ formatWeekday(6),+ ];+};diff --git a/packages/twenty-front/src/modules/localization/utils/getValidPlainTimeOrUndefined.ts b/packages/twenty-front/src/modules/localization/utils/getValidPlainTimeOrUndefined.tsnew file mode 100644index 00000000000..3915563de71--- /dev/null+++ b/packages/twenty-front/src/modules/localization/utils/getValidPlainTimeOrUndefined.ts@@ -0,0 +1,16 @@+import { isNonEmptyString } from '@sniptt/guards';+import { Temporal } from 'temporal-polyfill';++export const getValidPlainTimeOrUndefined = (+ time: string,+): Temporal.PlainTime | undefined => {+ if (!isNonEmptyString(time)) {+ return undefined;+ }++ try {+ return Temporal.PlainTime.from(time);+ } catch {+ return undefined;+ }+};