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

feat: extend line filtering to support nfk #261

Merged
merged 13 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion orgs/atb.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "./schema-validation.json",
"orgId": "atb",
"orgLineIdPrefix": "ATB:Line:2_",
"authorityId": "ATB:Authority:2",

"supportEmail": "kundeservice@atb.no",

Expand Down
2 changes: 1 addition & 1 deletion orgs/fram.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"$schema": "./schema-validation.json",

"orgId": "fram",
"orgLineIdPrefix": "MOR:Line:",
"authorityId": "MOR:Authority:MOR",

"supportEmail": "fram@mrfylke.no",

Expand Down
2 changes: 1 addition & 1 deletion orgs/nfk.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "./schema-validation.json",
"orgId": "nfk",
"orgLineIdPrefix": "NOR:Line:12_",
"authorityId": "NOR:Authority:12",

"supportEmail": "sentrumsterminalen@boreal.no",

Expand Down
2 changes: 1 addition & 1 deletion orgs/schema-validation.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"enum": ["atb", "fram", "nfk", "troms"],
"type": "string"
},
"orgLineIdPrefix": {
"authorityId": {
"type": "string"
},
"$schema": {
Expand Down
2 changes: 1 addition & 1 deletion orgs/troms.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "./schema-validation.json",
"orgId": "troms",
"orgLineIdPrefix": "TRO:Line:1_",
"authorityId": "TRO:Authority:1",

"supportEmail": "",

Expand Down
2 changes: 1 addition & 1 deletion src/modules/org-data/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export type TranslatableUrl = { default: string } & Partial<{
}>;
export type OrgData = {
orgId: WEBSHOP_ORGS;
orgLineIdPrefix: string;
authorityId: string;
supportEmail: string;

fylkeskommune?: {
Expand Down
6 changes: 6 additions & 0 deletions src/page-modules/assistant/__tests__/assistant.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ describe('assistant page', function () {
async singleTrip() {
return {} as any;
},
async lines() {
return {} as any;
},
client: null as any,
};

Expand Down Expand Up @@ -312,6 +315,9 @@ describe('assistant page', function () {
async singleTrip() {
return {} as any;
},
async lines() {
return {} as any;
},
client: null as any,
};

Expand Down
2 changes: 2 additions & 0 deletions src/page-modules/assistant/client/journey-planner/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ import useSWRInfinite from 'swr/infinite';
import { createTripQuery, tripQueryToQueryString } from '../../utils';
import { useEffect, useState } from 'react';
import { formatLocalTimeToCET } from '@atb/utils/date';
import { LineData } from '../../server/journey-planner/validators';

const MAX_NUMBER_OF_INITIAL_SEARCH_ATTEMPTS = 3;
const INITIAL_NUMBER_OF_WANTED_TRIP_PATTERNS = 6;

export type TripApiReturnType = TripData;
export type NonTransitTripApiReturnType = NonTransitTripData;
export type LinesApiReturnType = LineData;

function createKeyGetterOfQuery(query: TripQuery) {
return (pageIndex: number, previousPageData: TripApiReturnType) => {
Expand Down
40 changes: 31 additions & 9 deletions src/page-modules/assistant/line-filter/index.tsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,61 @@
import { Typo } from '@atb/components/typography';
import { PageText, useTranslation } from '@atb/translations';
import { ChangeEvent, useState } from 'react';
import { ChangeEvent, useEffect, useState } from 'react';
import style from './line-filter.module.css';
import { getOrgData } from '@atb/modules/org-data';
import LabeledInput from '@atb/components/labled-input';
import useSWR from 'swr';
type LineFilterProps = {
filterState: string[] | null;
onChange: (lineFilter: string[] | null) => void;
};

const fetcher = (url: string) => fetch(url).then((res) => res.json());
jonasbrunvoll marked this conversation as resolved.
Show resolved Hide resolved

export default function LineFilter({ filterState, onChange }: LineFilterProps) {
const { t } = useTranslation();

const { orgLineIdPrefix } = getOrgData();
const { authorityId } = getOrgData();

const [localFilterState, setLocalFilterState] = useState(
filterState?.map((line) => line.replace(orgLineIdPrefix, '')).join(', ') ??
'',
const { data, error, isLoading } = useSWR(
`api/assistant/lines/${authorityId}`,
fetcher,
);

const [localFilterState, setLocalFilterState] = useState('');
const onChangeWrapper = (event: ChangeEvent<HTMLInputElement>) => {
if (error || isLoading) return;
const lineFilter = event.target.value;
setLocalFilterState(lineFilter);

if (!lineFilter) {
onChange(null);
} else {
const linesWithPrefix = lineFilter
const publicCodes = lineFilter
.split(',')
.map((line) => `${orgLineIdPrefix}${line.trim()}`);
.map((publicCode) => `${publicCode.trim()}`);
jonasbrunvoll marked this conversation as resolved.
Show resolved Hide resolved

onChange(linesWithPrefix);
const lines = publicCodes
.map((publicCode) => data.publicCodeLineList[publicCode])
.filter((line) => line !== undefined);

onChange(lines);
}
};

useEffect(() => {
const mapFromLineIdToPublicCode = () => {
if (!data) return;
const lines =
filterState
?.map((line) => data.linePublicCodeList[line])
.filter((line, index, lines) => lines.indexOf(line) === index)
.join(', ') ?? '';
return lines;
};
const lines = mapFromLineIdToPublicCode();
if (lines) setLocalFilterState(lines);
}, [data]);

return (
<div className={style.container}>
<Typo.h3 textType="body__primary--bold" className={style.heading}>
Expand Down
45 changes: 45 additions & 0 deletions src/page-modules/assistant/server/journey-planner/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
TripsQueryVariables,
} from './journey-gql/trip.generated';
import {
LineData,
TripData,
TripPatternWithDetails,
nonTransitSchema,
Expand All @@ -21,6 +22,7 @@ import {
} from './validators';
import type {
FromToTripQuery,
LineInput,
NonTransitData,
NonTransitTripData,
NonTransitTripInput,
Expand Down Expand Up @@ -59,6 +61,12 @@ import {
addAssistantTripToCache,
getAssistantTripIfCached,
} from '../trip-cache';
import {
LineFragment,
LinesDocument,
LinesQuery,
LinesQueryVariables,
} from './journey-gql/lines.generated';

const DEFAULT_JOURNEY_CONFIG = {
numTripPatterns: 8, // The maximum number of trip patterns to return.
Expand All @@ -73,6 +81,7 @@ export type JourneyPlannerApi = {
trip(input: TripInput): Promise<TripData>;
nonTransitTrips(input: NonTransitTripInput): Promise<NonTransitTripData>;
singleTrip(input: string): Promise<TripPatternWithDetails | undefined>;
lines(input: LineInput): Promise<LineData>;
};

export function createJourneyApi(
Expand Down Expand Up @@ -156,6 +165,20 @@ export function createJourneyApi(
return nonTransits;
},

async lines(input) {
const result = await client.query<LinesQuery, LinesQueryVariables>({
query: LinesDocument,
variables: { authorities: input.authorities },
jonasbrunvoll marked this conversation as resolved.
Show resolved Hide resolved
});

if (result.error || result.errors) {
throw result.error || result.errors;
}

const publicCodeLineList = createPublicCodeLineList(result.data.lines);
const linePublicCodeList = createLinePublicCodeList(result.data.lines);
return { publicCodeLineList, linePublicCodeList };
},
async trip(input) {
const journeyModes = {
accessMode: StreetMode.Foot,
Expand Down Expand Up @@ -784,3 +807,25 @@ async function getSortedViaTrips(
};
return sortedData;
}

function createPublicCodeLineList(lines: LineFragment[]) {
const publicCodeLineList: Record<string, string[]> = {};
lines.forEach((line) => {
if (line.publicCode) {
if (publicCodeLineList.hasOwnProperty(line.publicCode)) {
publicCodeLineList[line.publicCode].push(line.id);
} else {
publicCodeLineList[line.publicCode] = [line.id];
}
}
});
return publicCodeLineList;
}

function createLinePublicCodeList(lines: LineFragment[]) {
const linePublicCodeList: Record<string, string> = {};
lines.forEach((line) => {
if (line.publicCode) linePublicCodeList[line.id] = line.publicCode;
});
return linePublicCodeList;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
query Lines($authorities: [String]) {
lines(authorities: $authorities) {
...line
}
}

fragment line on Line {
id
publicCode
}
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,11 @@ export const tripPatternWithDetailsSchema = z.object({
),
});

export const linesSchema = z.object({
publicCodeLineList: z.record(z.array(z.string())),
linePublicCodeList: z.record(z.string()),
});

export type TripData = z.infer<typeof tripSchema>;
export type NonTransitData = z.infer<typeof nonTransitSchema>;
export type TripPattern = z.infer<typeof tripPatternSchema>;
Expand All @@ -154,3 +159,4 @@ export type Quay = z.infer<typeof quaySchema>;
export type TripPatternWithDetails = z.infer<
typeof tripPatternWithDetailsSchema
>;
export type LineData = z.infer<typeof linesSchema>;
4 changes: 4 additions & 0 deletions src/page-modules/assistant/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,7 @@ export type NonTransitTripData = {
footTrip?: NonTransitData;
bikeRentalTrip?: NonTransitData;
};

export type LineInput = {
authorities: string[];
};
22 changes: 22 additions & 0 deletions src/pages/api/assistant/lines/[authorityId].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { tryResult } from '@atb/modules/api-server';
import { LinesApiReturnType } from '@atb/page-modules/assistant/client';
import { handlerWithAssistantClient } from '@atb/page-modules/assistant/server';

export default handlerWithAssistantClient<LinesApiReturnType>({
async GET(req, res, { client, ok }) {
const { authorityId } = req.query;
const authorities: string[] = [];

if (typeof authorityId === 'string') {
authorities.push(authorityId);
}

return tryResult(req, res, async () => {
return ok(
await client.lines({
authorities: authorities,
}),
);
});
},
});
Loading