diff --git a/src/CONST/SENTRY_LABEL.ts b/src/CONST/SENTRY_LABEL.ts index a411f7759618..11a42c59ce61 100644 --- a/src/CONST/SENTRY_LABEL.ts +++ b/src/CONST/SENTRY_LABEL.ts @@ -1037,6 +1037,7 @@ const SENTRY_LABEL = { TRIP_ROOM_PREVIEW: { CARD: 'TripRoomPreview-Card', RESERVATION: 'TripRoomPreview-Reservation', + BOOKING: 'TripRoomPreview-Booking', VIEW_BUTTON: 'TripRoomPreview-ViewButton', }, TRIP_DETAILS: { diff --git a/src/components/ReportActionItem/TripDetailsView.tsx b/src/components/ReportActionItem/TripDetailsView.tsx index 2c4ab4427b6b..24454a47dada 100644 --- a/src/components/ReportActionItem/TripDetailsView.tsx +++ b/src/components/ReportActionItem/TripDetailsView.tsx @@ -23,7 +23,14 @@ import variables from '@styles/variables'; import CONST from '@src/CONST'; import type {ReservationData} from '@src/libs/TripReservationUtils'; -import {formatCancelledDescription, formatTransitLocationLabel, getPNRReservationDataFromTripReport, getTripReservationCode, getTripReservationIcon} from '@src/libs/TripReservationUtils'; +import { + formatCancelledDescription, + formatTransitLocationLabel, + getBookingTitle, + getPNRReservationDataFromTripReport, + getTripReservationCode, + getTripReservationIcon, +} from '@src/libs/TripReservationUtils'; import ONYXKEYS from '@src/ONYXKEYS'; import {DYNAMIC_ROUTES} from '@src/ROUTES'; import type {Report} from '@src/types/onyx'; @@ -32,7 +39,6 @@ import type Transaction from '@src/types/onyx/Transaction'; import type {OnyxEntry} from 'react-native-onyx'; -import {differenceInCalendarDays} from 'date-fns'; import {Str} from 'expensify-common'; import React from 'react'; import {View} from 'react-native'; @@ -196,49 +202,6 @@ function TripDetailsView({tripRoomReport, shouldShowHorizontalRule, tripTransact return `${convertToDisplayString(amount, currency)} • ${trips.toLowerCase()}`; }; - const getTripTitle = (reservations: ReservationData[]) => { - if (reservations.length === 0) { - return ''; - } - - const firstReservation = reservations.at(0)?.reservation; - const lastReservation = reservations.at(reservations.length - 1)?.reservation; - - if (!lastReservation || !firstReservation) { - return ''; - } - - switch (firstReservation?.type) { - case CONST.RESERVATION_TYPE.FLIGHT: { - const destinationReservation = reservations.findLast((reservation) => reservation.reservation.legId === firstReservation.legId); - if (!destinationReservation) { - return ''; - } - return `${translate('travel.flightTo')} ${formatTransitLocationLabel(destinationReservation.reservation.end, true)}`; - } - case CONST.RESERVATION_TYPE.TRAIN: - if (reservations.length === 2 && firstReservation.start.shortName === lastReservation.end.shortName) { - return `${translate('travel.trainTo')} ${Str.recapitalize(lastReservation.start.longName ?? '')}`; - } - return `${translate('travel.trainTo')} ${Str.recapitalize(lastReservation.end.longName ?? '')}`; - case CONST.RESERVATION_TYPE.HOTEL: { - const nights = differenceInCalendarDays(new Date(lastReservation?.end.date), new Date(firstReservation.start.date)); - return `${nights} ${nights > 1 ? translate('travel.nightsIn') : translate('travel.nightIn')} ${Str.recapitalize(firstReservation.start.longName ?? '')}`; - } - case CONST.RESERVATION_TYPE.CAR: { - const days = differenceInCalendarDays(new Date(lastReservation.end.date), new Date(firstReservation.start.date)); - - if (days > 0) { - return `${days} ${days > 1 ? translate('common.days') : translate('common.day')}${translate('travel.carRental')}`; - } - - return `${DateUtils.getFormattedDurationBetweenDates(translate, new Date(firstReservation.start.date), new Date(lastReservation.end.date))}${translate('travel.carRental')}`; - } - default: - return ''; - } - }; - const [reportNameValuePairs] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${tripRoomReport?.reportID}`); if (!tripRoomReport) { @@ -263,7 +226,7 @@ function TripDetailsView({tripRoomReport, shouldShowHorizontalRule, tripTransact {reservationsData.map(({reservations, pnrID, currency, totalFareAmount}) => (
void; +}; + +function BookingView({booking, bookingApproval, onPress}: BookingViewProps) { + const theme = useTheme(); + const styles = useThemeStyles(); + const StyleUtils = useStyleUtils(); + const {translate} = useLocalize(); + const expensifyIcons = useMemoizedLazyExpensifyIcons(['Plane', 'PlaneCircleSlash', 'Bed', 'BedCircleSlash', 'CarWithKey', 'CarCircleSlash', 'Train', 'TrainCircleSlash', 'Luggage']); + + const firstReservation = booking.reservations.at(0)?.reservation; + const isCancelled = booking.reservations.every((reservation) => reservation.isCancelled); + const statusBadge = getBookingStatusBadge(translate, theme.reportStatusBadge, bookingApproval); + const description = formatCancelledDescription(translate('iou.canceled'), firstReservation ? translate(`travel.${firstReservation.type}`) : '', isCancelled); + + return ( + // eslint-disable-next-line @typescript-eslint/no-deprecated -- Matches the reservation rows above; the compound MenuItem has no leaf for the trip reservation icon. + + ) + } + /> + ); +} + function TripRoomPreview({action, containerStyles, isHovered = false}: TripRoomPreviewProps) { const styles = useThemeStyles(); + const {isBetaEnabled} = usePermissions(); + const {accountID: currentUserAccountID} = useCurrentUserPersonalDetails(); const {translate, dateFnsLocale} = useLocalize(); const {convertToDisplayString} = useCurrencyListActions(); const {anchor: contextMenuAnchorRef, shouldDisplayContextMenu = true, originalReportID} = useShowContextMenuState(); @@ -134,7 +204,11 @@ function TripRoomPreview({action, containerStyles, isHovered = false}: TripRoomP const chatReportID = chatReport?.reportID ?? linkedReportID; const tripTransactions = useTripTransactions(chatReportID); - const reservationsData: ReservationData[] = getReservationsFromTripReport(chatReport, reportNameValuePairs, tripTransactions); + // With travel approval, the preview lists bookings (the unit approvers decide on) instead of flight legs + const isTravelApprovalEnabled = isBetaEnabled(CONST.BETAS.TRAVEL_APPROVAL); + const reservationsData: ReservationData[] = isTravelApprovalEnabled ? [] : getReservationsFromTripReport(chatReport, reportNameValuePairs, tripTransactions); + const bookingsData: ReservationPNRData[] = isTravelApprovalEnabled ? getPNRReservationDataFromTripReport(chatReport, reportNameValuePairs, tripTransactions) : []; + const shouldShowReview = isTravelApprovalEnabled && canApproveAnyBooking(reportNameValuePairs?.tripData, currentUserAccountID); const dateInfo = reportNameValuePairs?.tripData?.startDate && reportNameValuePairs?.tripData?.endDate ? DateUtils.getFormattedDateRange(translate, dateFnsLocale, new Date(reportNameValuePairs.tripData.startDate), new Date(reportNameValuePairs.tripData.endDate)) @@ -159,6 +233,18 @@ function TripRoomPreview({action, containerStyles, isHovered = false}: TripRoomP /> ); + const renderBooking = ({item}: ListRenderItemInfo) => ( + + ); + + const reservationCount = isTravelApprovalEnabled + ? translate('travel.bookingCount', {count: bookingsData.length}) + : `${reservationsData.length} ${(reservationsData.length < 2 ? translate('travel.trip') : translate('travel.trips')).toLowerCase()}`; + return ( {chatReport?.reportName} - {dateInfo} • {reservationsData.length} {(reservationsData.length < 2 ? translate('travel.trip') : translate('travel.trips')).toLowerCase()} + {dateInfo} • {reservationCount} {reservationsData.length > 0 && ( @@ -197,16 +283,26 @@ function TripRoomPreview({action, containerStyles, isHovered = false}: TripRoomP renderItem={renderItem} /> )} + {bookingsData.length > 0 && ( + item.pnrID} + style={[styles.border, styles.borderRadiusComponentLarge, styles.p4, styles.flexGrow0]} + contentContainerStyle={styles.gap4} + renderItem={renderBooking} + /> + )} {translate('common.total')} {displayAmount} diff --git a/src/languages/de.ts b/src/languages/de.ts index c505efc9c153..1816d7934f1c 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -5244,6 +5244,10 @@ ${amount} für ${merchant} – ${date}`, hardApproval: (time: string) => `Wird automatisch in ${time} storniert, wenn nicht genehmigt.`, }, }, + bookingCount: ({count}: {count: number}) => ({ + one: '1 Buchung', + other: `${count} Buchungen`, + }), }, workspace: { common: { diff --git a/src/languages/el.ts b/src/languages/el.ts index 3b266b974573..e26f39901b21 100644 --- a/src/languages/el.ts +++ b/src/languages/el.ts @@ -5308,6 +5308,10 @@ ${amount} για ${merchant} - ${date}`, hardApproval: (time: string) => `Ακυρώνεται αυτόματα σε ${time} αν δεν εγκριθεί.`, }, }, + bookingCount: ({count}: {count: number}) => ({ + one: '1 κράτηση', + other: `${count} κρατήσεις`, + }), }, proactiveAppReview: { title: 'Σας αρέσει το νέο Expensify;', diff --git a/src/languages/en.ts b/src/languages/en.ts index 8293c49829f4..515515cc081b 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -5351,6 +5351,10 @@ const translations = { viewTripDetails: 'View trip details', trip: 'Trip', trips: 'Trips', + bookingCount: ({count}: {count: number}) => ({ + one: '1 booking', + other: `${count} bookings`, + }), tripSummary: 'Trip summary', departs: 'Departs', errorMessage: 'Something went wrong. Please try again later.', diff --git a/src/languages/es.ts b/src/languages/es.ts index dca804c50178..f792fbaf4a0c 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -5213,6 +5213,10 @@ ${amount} para ${merchant} - ${date}`, hardApproval: (time: string) => `Se cancela automáticamente en ${time} si no se aprueba.`, }, }, + bookingCount: ({count}: {count: number}) => ({ + one: '1 reserva', + other: `${count} reservas`, + }), }, proactiveAppReview: { title: '¿Te gusta New Expensify?', diff --git a/src/languages/fr.ts b/src/languages/fr.ts index 2301664af663..0a383344e56e 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -5255,6 +5255,10 @@ ${amount} pour ${merchant} - ${date}`, hardApproval: (time: string) => `Annulation automatique dans ${time} si non approuvé.`, }, }, + bookingCount: ({count}: {count: number}) => ({ + one: `${count} réservation`, + other: `${count} réservations`, + }), }, workspace: { common: { diff --git a/src/languages/it.ts b/src/languages/it.ts index ce4a3fc5ba89..b9f405fd195d 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -5213,6 +5213,10 @@ ${amount} per ${merchant} - ${date}`, hardApproval: (time: string) => `Annullamento automatico tra ${time} se non approvata.`, }, }, + bookingCount: ({count}: {count: number}) => ({ + one: '1 prenotazione', + other: `${count} prenotazioni`, + }), }, workspace: { common: { diff --git a/src/languages/ja.ts b/src/languages/ja.ts index 4cd98e64e8da..63217e318f6a 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -5164,6 +5164,10 @@ ${integrationName === CONST.ONBOARDING_ACCOUNTING_MAPPING.other ? 'あなたの' hardApproval: (time: string) => `承認されない場合は ${time} で自動的にキャンセルされます。`, }, }, + bookingCount: ({count}: {count: number}) => ({ + one: '1件の予約', + other: `${count}件の予約`, + }), }, workspace: { common: { diff --git a/src/languages/nl.ts b/src/languages/nl.ts index 8e7cb06617b2..6321f90f40bf 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -5210,6 +5210,10 @@ ${amount} voor ${merchant} - ${date}`, hardApproval: (time: string) => `Wordt automatisch geannuleerd over ${time} als deze niet is goedgekeurd.`, }, }, + bookingCount: ({count}: {count: number}) => ({ + one: '1 boeking', + other: `${count} boekingen`, + }), }, workspace: { common: { diff --git a/src/languages/pl.ts b/src/languages/pl.ts index c0d0100db11a..df1c3095ce8d 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -5250,6 +5250,12 @@ ${amount} dla ${merchant} - ${date}`, hardApproval: (time: string) => `Automatycznie anuluje się za ${time}, jeśli nie zostanie zatwierdzone.`, }, }, + bookingCount: ({count}: {count: number}) => ({ + one: '1 rezerwacja', + few: `${count} rezerwacje`, + many: `${count} rezerwacji`, + other: `${count} rezerwacji`, + }), }, workspace: { common: { diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index 92df211d4afa..86e9e6fa1813 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -5216,6 +5216,10 @@ ${amount} para ${merchant} - ${date}`, hardApproval: (time: string) => `Cancela automaticamente em ${time} se não for aprovado.`, }, }, + bookingCount: ({count}: {count: number}) => ({ + one: `${count} reserva`, + other: `${count} reservas`, + }), }, workspace: { common: { diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index c8db780a49ae..f1c52d161306 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -5040,6 +5040,10 @@ ${amount},商户:${merchant} - 日期:${date}`, status: {outstanding: '未结', approved: '已批准', rejected: '已拒绝', canceled: '已取消'}, deadline: {softApproval: (time: string) => `将在 ${time} 后自动批准。在此之前可免费取消。`, hardApproval: (time: string) => `若未获批准,将在 ${time} 后自动取消。`}, }, + bookingCount: ({count}: {count: number}) => ({ + one: '1 个预订', + other: `${count} 个预订`, + }), }, workspace: { common: { diff --git a/src/libs/TravelApprovalUtils.ts b/src/libs/TravelApprovalUtils.ts index ba37c7815caf..419510a006cb 100644 --- a/src/libs/TravelApprovalUtils.ts +++ b/src/libs/TravelApprovalUtils.ts @@ -53,6 +53,11 @@ function canApproveBooking(tripData: TripRoomData, pnrID: string, accountID: num return !!booking.approverAccountIDs?.includes(accountID); } +/** Whether the user can approve or reject at least one booking in the trip */ +function canApproveAnyBooking(tripData: TripRoomData, accountID: number | undefined, now: Date = new Date()): boolean { + return Object.keys(tripData?.bookingApprovalState ?? {}).some((pnrID) => canApproveBooking(tripData, pnrID, accountID, now)); +} + /** The outstanding booking whose deadline comes first, which is the one trip-level places show */ function getEarliestOutstandingBooking(tripData: TripRoomData, now: Date = new Date()): BookingApproval | undefined { let earliestBooking: BookingApproval | undefined; @@ -134,4 +139,4 @@ function getBookingStatusBadge(translate: LocalizedTranslate, badgeColors: Theme return {text: translate(`travel.approval.status.${booking.status}`), backgroundColor: colors.backgroundColor, textColor: colors.textColor}; } -export {canApproveBooking, getBookingDeadlineDate, getBookingStatusBadge, getEarliestOutstandingBooking, getTripDeadlineText}; +export {canApproveAnyBooking, canApproveBooking, getBookingDeadlineDate, getBookingStatusBadge, getEarliestOutstandingBooking, getTripDeadlineText}; diff --git a/src/libs/TripReservationUtils.ts b/src/libs/TripReservationUtils.ts index 33788da1a456..fe95de18bb21 100644 --- a/src/libs/TripReservationUtils.ts +++ b/src/libs/TripReservationUtils.ts @@ -1,3 +1,5 @@ +import type {LocalizedTranslate} from '@components/LocaleContextProvider'; + import CONST from '@src/CONST'; import type {Report} from '@src/types/onyx'; import type ReportNameValuePairs from '@src/types/onyx/ReportNameValuePairs'; @@ -8,8 +10,10 @@ import type IconAsset from '@src/types/utils/IconAsset'; import type {ArrayValues} from 'type-fest'; -import {SafeString} from 'expensify-common'; +import {differenceInCalendarDays} from 'date-fns'; +import {SafeString, Str} from 'expensify-common'; +import DateUtils from './DateUtils'; import {getMoneyRequestSpendBreakdown} from './ReportUtils'; type TripReservationIcons = Record<'Plane' | 'PlaneCircleSlash' | 'Bed' | 'BedCircleSlash' | 'CarWithKey' | 'CarCircleSlash' | 'Train' | 'TrainCircleSlash' | 'Luggage', IconAsset>; @@ -584,6 +588,50 @@ function formatCancelledDescription(cancelledLabel: string, description: string, return `${cancelledLabel} ${CONST.DOT_SEPARATOR} ${description}`; } +/** The title of a booking, as its section in the trip room shows it: "Flight to Oslo", "2 nights in Hanoi" */ +function getBookingTitle(translate: LocalizedTranslate, reservations: ReservationData[]): string { + if (reservations.length === 0) { + return ''; + } + + const firstReservation = reservations.at(0)?.reservation; + const lastReservation = reservations.at(reservations.length - 1)?.reservation; + + if (!lastReservation || !firstReservation) { + return ''; + } + + switch (firstReservation?.type) { + case CONST.RESERVATION_TYPE.FLIGHT: { + const destinationReservation = reservations.findLast((reservation) => reservation.reservation.legId === firstReservation.legId); + if (!destinationReservation) { + return ''; + } + return `${translate('travel.flightTo')} ${formatTransitLocationLabel(destinationReservation.reservation.end, true)}`; + } + case CONST.RESERVATION_TYPE.TRAIN: + if (reservations.length === 2 && firstReservation.start.shortName === lastReservation.end.shortName) { + return `${translate('travel.trainTo')} ${Str.recapitalize(lastReservation.start.longName ?? '')}`; + } + return `${translate('travel.trainTo')} ${Str.recapitalize(lastReservation.end.longName ?? '')}`; + case CONST.RESERVATION_TYPE.HOTEL: { + const nights = differenceInCalendarDays(new Date(lastReservation?.end.date), new Date(firstReservation.start.date)); + return `${nights} ${nights > 1 ? translate('travel.nightsIn') : translate('travel.nightIn')} ${Str.recapitalize(firstReservation.start.longName ?? '')}`; + } + case CONST.RESERVATION_TYPE.CAR: { + const days = differenceInCalendarDays(new Date(lastReservation.end.date), new Date(firstReservation.start.date)); + + if (days > 0) { + return `${days} ${days > 1 ? translate('common.days') : translate('common.day')}${translate('travel.carRental')}`; + } + + return `${DateUtils.getFormattedDurationBetweenDates(translate, new Date(firstReservation.start.date), new Date(lastReservation.end.date))}${translate('travel.carRental')}`; + } + default: + return ''; + } +} + export { getTripReservationIcon, getTripEReceiptIcon, @@ -592,9 +640,10 @@ export { getTripTotal, getReservationDetailsFromSequence, formatTransitLocationLabel, + getBookingTitle, getPNRReservationDataFromTripReport, getAirReservations, isPnrCancelled, formatCancelledDescription, }; -export type {ReservationData}; +export type {ReservationData, ReservationPNRData}; diff --git a/tests/ui/TripRoomPreviewTest.tsx b/tests/ui/TripRoomPreviewTest.tsx new file mode 100644 index 000000000000..222c5bf28087 --- /dev/null +++ b/tests/ui/TripRoomPreviewTest.tsx @@ -0,0 +1,148 @@ +import {act, render, screen} from '@testing-library/react-native'; + +import ComposeProviders from '@components/ComposeProviders'; +import {CurrencyListContextProvider} from '@components/CurrencyListContextProvider'; +import {CurrentUserPersonalDetailsProvider} from '@components/CurrentUserPersonalDetailsProvider'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import TripRoomPreview from '@components/ReportActionItem/TripRoomPreview'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Beta, Report, ReportAction} from '@src/types/onyx'; +import type {BookingApproval} from '@src/types/onyx/ReportNameValuePairs'; +import type {TripData} from '@src/types/onyx/TripData'; + +import React from 'react'; +import Onyx from 'react-native-onyx'; + +import {airReservationPnrData, airReservationTravelers} from '../data/TripAirReservationData'; +import createMock from '../utils/createMock'; +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; +import wrapOnyxWithWaitForBatchedUpdates from '../utils/wrapOnyxWithWaitForBatchedUpdates'; + +jest.mock('@react-navigation/native'); + +const TRIP_ROOM_ID = '7001'; +const APPROVER_ACCOUNT_ID = 24680; +const TRAVELER_ACCOUNT_ID = 13579; +const OUTBOUND_PNR_ID = 'PNR12345'; +const RETURN_PNR_ID = 'PNR67890'; + +// Two round-trip flights, so the trip has two bookings but four flight legs +const tripPayload = createMock({ + pnrs: [ + {...airReservationPnrData, data: {...airReservationPnrData.data, pnrTravelers: airReservationTravelers}}, + {...airReservationPnrData, pnrId: RETURN_PNR_ID, data: {...airReservationPnrData.data, pnrTravelers: airReservationTravelers}}, + ], +}); + +const tripRoom = createMock({ + reportID: TRIP_ROOM_ID, + reportName: 'Trip to Denver', + type: CONST.REPORT.TYPE.CHAT, + chatType: CONST.REPORT.CHAT_TYPE.TRIP_ROOM, +}); + +const tripPreviewAction = createMock({ + reportActionID: '9001', + actionName: CONST.REPORT.ACTIONS.TYPE.TRIP_PREVIEW, + created: '2026-11-01 09:00:00.000', + message: {linkedReportID: TRIP_ROOM_ID}, +}); + +const outstandingBooking: BookingApproval = { + status: CONST.TRAVEL.BOOKING_APPROVAL.STATUS.OUTSTANDING, + approvalType: CONST.TRAVEL.BOOKING_APPROVAL.TYPE.SOFT, + approvalID: 'approval-outbound', + approverAccountIDs: [APPROVER_ACCOUNT_ID], +}; + +async function setUpTrip({accountID, betas, bookingApprovalState}: {accountID: number; betas: Beta[]; bookingApprovalState?: Record}) { + await act(async () => { + await Onyx.set(ONYXKEYS.SESSION, {accountID, email: `${accountID}@test.com`}); + await Onyx.set(ONYXKEYS.BETAS, betas); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${TRIP_ROOM_ID}`, tripRoom); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${TRIP_ROOM_ID}`, {tripData: {tripID: 'trip-denver', payload: tripPayload, bookingApprovalState}}); + }); + await waitForBatchedUpdatesWithAct(); +} + +function renderPreview() { + return render( + + + , + ); +} + +describe('TripRoomPreview', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(() => { + wrapOnyxWithWaitForBatchedUpdates(Onyx); + }); + + afterEach(async () => { + await act(async () => { + await Onyx.clear(); + }); + await waitForBatchedUpdatesWithAct(); + }); + + it('counts bookings instead of flight legs with travel approval', async () => { + // Given a trip with two round-trip flights, which is two bookings but four flight legs + await setUpTrip({accountID: TRAVELER_ACCOUNT_ID, betas: [CONST.BETAS.TRAVEL_APPROVAL]}); + + // When the workspace chat shows its preview + renderPreview(); + await waitForBatchedUpdatesWithAct(); + + // Then the header counts the two bookings, the unit approvers decide on + expect(screen.getByText(/2 bookings/)).toBeOnTheScreen(); + expect(screen.queryByText(/4 trips/)).not.toBeOnTheScreen(); + }); + + it('keeps counting flight legs without travel approval', async () => { + // Given the same trip for a user without the travel approval beta + await setUpTrip({accountID: TRAVELER_ACCOUNT_ID, betas: []}); + + // When the workspace chat shows its preview + renderPreview(); + await waitForBatchedUpdatesWithAct(); + + // Then the preview stays as it was before the beta + expect(screen.getByText(/4 trips/)).toBeOnTheScreen(); + expect(screen.getByText('View')).toBeOnTheScreen(); + }); + + it('asks an approver to review an outstanding booking', async () => { + // Given an outstanding booking the signed-in user approves + await setUpTrip({accountID: APPROVER_ACCOUNT_ID, betas: [CONST.BETAS.TRAVEL_APPROVAL], bookingApprovalState: {[OUTBOUND_PNR_ID]: outstandingBooking}}); + + // When the workspace chat shows its preview + renderPreview(); + await waitForBatchedUpdatesWithAct(); + + // Then the booking shows its badge and the button says Review, since there's a decision waiting on them + expect(screen.getByText('Outstanding')).toBeOnTheScreen(); + expect(screen.getByText('Review')).toBeOnTheScreen(); + expect(screen.queryByText('View')).not.toBeOnTheScreen(); + }); + + it('shows View to everyone else on the trip', async () => { + // Given an outstanding booking someone else approves + await setUpTrip({accountID: TRAVELER_ACCOUNT_ID, betas: [CONST.BETAS.TRAVEL_APPROVAL], bookingApprovalState: {[OUTBOUND_PNR_ID]: outstandingBooking}}); + + // When the traveler sees the preview + renderPreview(); + await waitForBatchedUpdatesWithAct(); + + // Then they see the booking's status, but View, since there's nothing for them to decide + expect(screen.getByText('Outstanding')).toBeOnTheScreen(); + expect(screen.getByText('View')).toBeOnTheScreen(); + expect(screen.queryByText('Review')).not.toBeOnTheScreen(); + }); +}); diff --git a/tests/unit/TravelApprovalUtilsTest.ts b/tests/unit/TravelApprovalUtilsTest.ts index 9238b8c64965..e8023ed881f0 100644 --- a/tests/unit/TravelApprovalUtilsTest.ts +++ b/tests/unit/TravelApprovalUtilsTest.ts @@ -1,4 +1,4 @@ -import {canApproveBooking, getBookingDeadlineDate, getBookingStatusBadge, getEarliestOutstandingBooking, getTripDeadlineText} from '@libs/TravelApprovalUtils'; +import {canApproveAnyBooking, canApproveBooking, getBookingDeadlineDate, getBookingStatusBadge, getEarliestOutstandingBooking, getTripDeadlineText} from '@libs/TravelApprovalUtils'; import type {ThemeColors} from '@styles/theme/types'; @@ -103,6 +103,31 @@ describe('TravelApprovalUtils', () => { }); }); + describe('canApproveAnyBooking', () => { + it('is true when any booking in the trip waits on the user', () => { + // Given a trip with an approved hotel and an outstanding flight the user approves + const tripData = buildTripData({ + [HOTEL_PNR_ID]: buildBooking({status: CONST.TRAVEL.BOOKING_APPROVAL.STATUS.APPROVED}), + [FLIGHT_PNR_ID]: buildBooking(), + }); + + // When we check whether the user has something to decide in the trip + // Then they do for the approver, which is when the trip preview asks them to review, and not for anyone else + expect(canApproveAnyBooking(tripData, APPROVER_ACCOUNT_ID, NOW)).toBe(true); + expect(canApproveAnyBooking(tripData, OTHER_ACCOUNT_ID, NOW)).toBe(false); + }); + + it('is false once nothing in the trip is left to decide', () => { + // Given a trip whose only outstanding booking is past its deadline, and a trip without approval data + const passedTrip = buildTripData({[HOTEL_PNR_ID]: buildBooking({deadline: {iso8601: '2026-12-10T09:00:00', zoneId: 'Europe/Oslo'}})}); + + // When we check whether the approver has something to decide + // Then they don't, so the preview keeps View + expect(canApproveAnyBooking(passedTrip, APPROVER_ACCOUNT_ID, NOW)).toBe(false); + expect(canApproveAnyBooking(undefined, APPROVER_ACCOUNT_ID, NOW)).toBe(false); + }); + }); + describe('deadline', () => { it('reads the saved deadline in its own time zone', () => { // Given the same local deadline saved in two different time zones