Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

only show routes from current service week #1259

Merged
merged 18 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
543 changes: 543 additions & 0 deletions __tests__/components/viewers/__snapshots__/nearby-view.js.snap

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions example-config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,8 @@ disableSingleItineraryDays: false
# maxRealtimeVehicleAge: 60
# # Interval for refreshing vehicle positions
# vehiclePositionRefreshSeconds: 30 # defaults to 30 seconds.
# # Enable this to restrict listing to routes active within the last to next Sunday
# onlyShowCurrentServiceWeek: true

# API key to make Mapillary API calls. These are used to show street imagery.
# Mapillary calls these "Client Tokens". They can be created at https://www.mapillary.com/dashboard/developers
Expand Down
4 changes: 2 additions & 2 deletions lib/actions/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -370,8 +370,8 @@ export function vehicleRentalQuery(
export const fetchNearbyResponse = createAction('FETCH_NEARBY_RESPONSE')
export const fetchNearbyError = createAction('FETCH_NEARBY_ERROR')

export function fetchNearby(coords, map) {
return executeOTPAction('fetchNearby', coords, map)
export function fetchNearby(coords, map, currentServiceWeek) {
return executeOTPAction('fetchNearby', coords, map, currentServiceWeek)
}

// Single trip lookup query
Expand Down
24 changes: 19 additions & 5 deletions lib/actions/apiV2.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
isValidSubsequence,
queryIsValid
} from '../util/state'
import { getCurrentServiceWeek } from '../util/current-service-week'
import {
getRouteColorBasedOnSettings,
getRouteIdForPattern,
Expand Down Expand Up @@ -379,14 +380,15 @@ export const fetchNearbyFromStopId = (stopId) => {
)
}

export const fetchNearby = (position, radius) => {
export const fetchNearby = (position, radius, currentServiceWeek) => {
const { lat, lon } = position

return createGraphQLQueryAction(
`query Nearby(
$lat: Float!
$lon: Float!
$radius: Int
$currentServiceWeek: LocalDateRangeInput
) {
nearest(lat:$lat, lon:$lon, maxDistance: $radius, first: 100, filterByPlaceTypes: [STOP, VEHICLE_RENT, BIKE_PARK, CAR_PARK]) {
edges {
Expand Down Expand Up @@ -436,11 +438,15 @@ export const fetchNearby = (position, radius) => {
lon
code
gtfsId
stopRoutes: routes (serviceDates: $currentServiceWeek) {
miles-grant-ibigroup marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm getting a "Unknown field argument" graphql error back when I try to view a stop

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only works on the latest version of OTP. Are you testing against an older OTP version? I'm happy to delay merging this until newer OTP is more widespread

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh gotcha, yes the instance of OTP I was using to test looks like the only one of ours this would break! We can discuss that internally

gtfsId
}
stoptimesForPatterns {
pattern {
headsign
desc: name
route {
gtfsId
agency {
name
gtfsId
Expand Down Expand Up @@ -474,7 +480,7 @@ export const fetchNearby = (position, radius) => {
}
}
}`,
{ lat, lon, radius },
{ currentServiceWeek, lat, lon, radius },
fetchNearbyResponse,
fetchNearbyError,
{
Expand Down Expand Up @@ -857,10 +863,18 @@ export const findRoute = (params) =>

export function findRoutes() {
return function (dispatch, getState) {
// Only calculate current service week if the setting for it is enabled
const currentServiceWeek =
getState().otp?.config?.routeViewer?.onlyShowCurrentServiceWeek === true
? getCurrentServiceWeek()
: undefined

dispatch(
createGraphQLQueryAction(
`{
routes {
`query Routes(
$currentServiceWeek: LocalDateRangeInput
) {
routes (serviceDates: $currentServiceWeek) {
id: gtfsId
agency {
id: gtfsId
Expand All @@ -875,7 +889,7 @@ export function findRoutes() {
}
}
`,
{},
{ currentServiceWeek },
findRoutesResponse,
findRoutesError,
{
Expand Down
35 changes: 30 additions & 5 deletions lib/components/viewers/nearby/nearby-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import * as apiActions from '../../../actions/api'
import * as mapActions from '../../../actions/map'
import * as uiActions from '../../../actions/ui'
import { AppReduxState } from '../../../util/state-types'
import { getCurrentServiceWeek } from '../../../util/current-service-week'
import { SetLocationHandler, ZoomToPlaceHandler } from '../../util/types'
import Loading from '../../narrative/loading'
import MobileContainer from '../../mobile/container'
Expand All @@ -31,13 +32,19 @@ const AUTO_REFRESH_INTERVAL = 15000
// TODO: use lonlat package
type LatLonObj = { lat: number; lon: number }
type CurrentPosition = { coords?: { latitude: number; longitude: number } }
type ServiceWeek = { end: string; start: string }

type Props = {
currentPosition?: CurrentPosition
currentServiceWeek?: ServiceWeek
defaultLatLon: LatLonObj | null
displayedCoords?: LatLonObj
entityId?: string
fetchNearby: (latLon: LatLonObj, radius?: number) => void
fetchNearby: (
latLon: LatLonObj,
radius?: number,
currentServiceWeek?: ServiceWeek
) => void
hideBackButton?: boolean
location: string
mobile?: boolean
Expand Down Expand Up @@ -102,6 +109,7 @@ function getNearbyCoordsFromUrlOrLocationOrMapCenter(

function NearbyView({
currentPosition,
currentServiceWeek,
defaultLatLon,
displayedCoords,
entityId,
Expand Down Expand Up @@ -175,10 +183,10 @@ function NearbyView({
firstItemRef.current?.scrollIntoView({ behavior: 'smooth' })
}
if (finalNearbyCoords) {
fetchNearby(finalNearbyCoords, radius)
fetchNearby(finalNearbyCoords, radius, currentServiceWeek)
setLoading(true)
const interval = setInterval(() => {
fetchNearby(finalNearbyCoords, radius)
fetchNearby(finalNearbyCoords, radius, currentServiceWeek)
setLoading(true)
}, AUTO_REFRESH_INTERVAL)
return function cleanup() {
Expand All @@ -204,6 +212,16 @@ function NearbyView({
finalNearbyCoords?.lat !== displayedCoords?.lat ||
finalNearbyCoords?.lon !== displayedCoords?.lon

// Build list of nearby routes for filtering within the stop card
const nearbyRoutes = Array.from(
new Set(
nearby
?.map((n: any) =>
n.place?.stopRoutes?.map((sr: { gtfsId?: string }) => sr?.gtfsId)
)
.flat(Infinity)
)
)
const nearbyItemList =
nearby?.map &&
nearby?.map((n: any) => (
Expand All @@ -223,7 +241,7 @@ function NearbyView({
/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */
tabIndex={0}
>
{getNearbyItem({ ...n.place, distance: n.distance })}
{getNearbyItem({ ...n.place, distance: n.distance, nearbyRoutes })}
</div>
</li>
))
Expand Down Expand Up @@ -290,15 +308,22 @@ function NearbyView({

const mapStateToProps = (state: AppReduxState) => {
const { config, location, transitIndex, ui } = state.otp
const { map } = state.otp.config
const { map, routeViewer } = config
const { nearbyViewCoords } = ui
const { nearby } = transitIndex
const { entityId } = state.router.location.query
const { currentPosition } = location
const defaultLatLon =
map?.initLat && map?.initLon ? { lat: map.initLat, lon: map.initLon } : null

const currentServiceWeek =
routeViewer?.onlyShowCurrentServiceWeek === true
? getCurrentServiceWeek()
: undefined

return {
currentPosition,
currentServiceWeek,
defaultLatLon,
displayedCoords: nearby?.coords,
entityId: entityId && decodeURIComponent(entityId),
Expand Down
11 changes: 9 additions & 2 deletions lib/components/viewers/nearby/stop.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Calendar } from '@styled-icons/fa-solid'
import { connect } from 'react-redux'
import { FormattedMessage } from 'react-intl'
import { TransitOperator } from '@opentripplanner/types'
import coreUtils from '@opentripplanner/core-utils'
import React from 'react'

Expand All @@ -25,7 +24,7 @@ type Props = {
homeTimezone: string
nearbyViewConfig?: NearbyViewConfig
routeSortComparator: (a: PatternStopTime, b: PatternStopTime) => number
stopData: StopData
stopData: StopData & { nearbyRoutes?: string[] }
}

const Stop = ({
Expand Down Expand Up @@ -70,6 +69,14 @@ const Stop = ({
const sortedStopTimes = st.stoptimes.sort(
(a: StopTime, b: StopTime) => fullTimestamp(a) - fullTimestamp(b)
)
if (
// NearbyRoutes if present is populated with a list of routes that appear
// in the current service period.
stopData.nearbyRoutes &&
!stopData.nearbyRoutes.includes(st?.pattern?.route?.gtfsId)
) {
return <></>
miles-grant-ibigroup marked this conversation as resolved.
Show resolved Hide resolved
}
return (
<PatternRow
alwaysShowLongName={nearbyViewConfig?.alwaysShowLongName}
Expand Down
2 changes: 2 additions & 0 deletions lib/util/config-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,8 @@ export interface RouteViewerConfig {
hideRouteShapesWithinFlexZones?: boolean
/** Remove vehicles from the map if they haven't sent an update in a number of seconds */
maxRealtimeVehicleAge?: number
/** Use OTP date limiting to only show current service week in list */
onlyShowCurrentServiceWeek?: boolean
/** Disable vehicle highlight if necessary (e.g. custom or inverted icons) */
vehicleIconHighlight?: boolean
/** Customize vehicle icon padding (the default iconPadding is 2px in otp-ui) */
Expand Down
10 changes: 10 additions & 0 deletions lib/util/current-service-week.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { addDays, nextSunday, previousSunday } from 'date-fns'
/** Gets the current service week */
export const getCurrentServiceWeek = (): {
end: string
start: string
} => {
const start = previousSunday(new Date()).toISOString().split('T')[0]
const end = addDays(nextSunday(new Date()), 1).toISOString().split('T')[0]
return { end, start }
}
Loading
Loading