@kiwicom/smart-faq
Version:
112 lines (94 loc) • 2.73 kB
JavaScript
// @flow
import * as React from 'react';
import differenceInHours from 'date-fns/difference_in_hours';
import { graphql, createFragmentContainer } from 'react-relay';
import LogContext from '@kiwicom/nitro/lib/services/log/context';
import type { Context as LogContextType } from '@kiwicom/nitro/lib/services/log/context';
import bookingTypes from '../common/booking/bookingTypes';
import type { BookingAnalyticsTracker_booking as BookingAnalyticsTrackerType } from './__generated__/BookingAnalyticsTracker_booking.graphql';
import { events } from '../../const/events';
type Props = {|
booking: BookingAnalyticsTrackerType,
|};
class BookingAnalyticsTracker extends React.Component<Props> {
context: LogContextType;
static contextType = LogContext;
componentDidMount() {
this.trackBooking();
}
componentDidUpdate(prevProps: Props) {
if (prevProps.booking.id === this.props.booking.id) {
return;
}
this.trackBooking();
}
trackBooking() {
const data = this.getAnalyticsData();
this.context.log(events.BOOKING_LOADED, data);
}
getAnalyticsData() {
const { booking } = this.props;
const upcomingDeparture = booking.upcomingDeparture?.departure?.time;
let firstDeparture = null;
switch (booking.type) {
case bookingTypes.ONE_WAY:
firstDeparture = booking.trip?.departure?.time;
break;
case bookingTypes.RETURN:
firstDeparture = booking.outbound?.departure?.time;
break;
case bookingTypes.MULTICITY:
firstDeparture = booking.start?.time;
break;
}
const timeToSegment = upcomingDeparture
? differenceInHours(upcomingDeparture, new Date())
: false;
const timeToDeparture = firstDeparture
? differenceInHours(firstDeparture, new Date())
: false;
return {
timeToDeparture: timeToDeparture
? Math.round(timeToDeparture)
: timeToDeparture,
timeToSegment: timeToSegment ? Math.round(timeToSegment) : timeToSegment,
};
}
render() {
return null;
}
}
export const RawBookingAnalyticsTracker = BookingAnalyticsTracker;
export default createFragmentContainer(
BookingAnalyticsTracker,
graphql`
fragment BookingAnalyticsTracker_booking on BookingInterface {
id
type: __typename
upcomingDeparture: upcomingLeg {
departure {
time
}
}
... on BookingOneWay {
trip {
departure {
time
}
}
}
... on BookingReturn {
outbound {
departure {
time
}
}
}
... on BookingMulticity {
start {
time
}
}
}
`,
);