Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions src/features/receipt/ReceiptContainer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ describe('ReceiptContainer', () => {

expect(
screen.getByRole('link', {
name: /Kopi av din kvittering er sendt til ditt arkiv/i,
name: /Din kvittering er lagret og tilgjengelig i din innboks/i,
}),
).toBeInTheDocument();

Expand All @@ -271,7 +271,7 @@ describe('ReceiptContainer', () => {

expect(
screen.getByRole('link', {
name: /Kopi av din kvittering er sendt til ditt arkiv/i,
name: /Din kvittering er lagret og tilgjengelig i din innboks/i,
}),
).toBeInTheDocument();

Expand Down
12 changes: 1 addition & 11 deletions src/layout/Address/AddressComponent.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import React from 'react';

import { act, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import mockAxios from 'jest-mock-axios';

import { AddressComponent } from 'src/layout/Address/AddressComponent';
import { renderGenericComponentTest } from 'src/testUtils';
Expand Down Expand Up @@ -229,16 +228,7 @@ describe('AddressComponent', () => {
},
});

mockAxios.mockResponseFor(
{ url: 'https://api.bring.com/shippingguide/api/postalCode.json' },
{
data: {
valid: true,
result: 'OSLO',
},
},
);

// The postal codes mock from testUtils.tsx has 0001 -> OSLO
await screen.findByDisplayValue('OSLO');

expect(handleDataChange).toHaveBeenCalledWith('OSLO', { key: 'postPlace' });
Expand Down
84 changes: 33 additions & 51 deletions src/layout/Address/AddressComponent.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import React from 'react';

import { LegacyTextField } from '@digdir/design-system-react';
import axios from 'axios';

import { Label } from 'src/components/form/Label';
import { useDelayedSavedState } from 'src/hooks/useDelayedSavedState';
import { useLanguage } from 'src/hooks/useLanguage';
import { useStateDeepEqual } from 'src/hooks/useStateDeepEqual';
import classes from 'src/layout/Address/AddressComponent.module.css';
import { httpGet } from 'src/utils/network/sharedNetworking';
import { usePostPlace } from 'src/layout/Address/usePostPlace';
import { renderValidationMessagesForComponent } from 'src/utils/render';
import type { PropsFromGenericComponent } from 'src/layout';
import type { IComponentValidations } from 'src/utils/validation/types';
Expand All @@ -31,9 +30,6 @@
}

export function AddressComponent({ formData, handleDataChange, componentValidations, node }: IAddressComponentProps) {
// eslint-disable-next-line import/no-named-as-default-member
const cancelToken = axios.CancelToken;
const source = cancelToken.source();
const { id, required, readOnly, labelSettings, simplified, saveWhileTyping } = node.item;
const { lang, langAsString } = useLanguage();

Expand Down Expand Up @@ -73,8 +69,9 @@
);

const [validations, setValidations] = useStateDeepEqual<IAddressValidationErrors>({});
const prevZipCode = React.useRef<string | undefined>(undefined);
const hasFetchedPostPlace = React.useRef<boolean>(false);
const isValidZipCode = formData.zipCode?.match(/^\d{4}$/);
const postPlaceFromHook = usePostPlace(isValidZipCode ? formData.zipCode : undefined, true);
const hasLookedUp = React.useRef<boolean>(false);

const validate = React.useCallback(() => {
const validationErrors: IAddressValidationErrors = {};
Expand Down Expand Up @@ -108,54 +105,39 @@
);

React.useEffect(() => {
if (!formData.zipCode || !formData.zipCode.match(/^\d{4}$/)) {
setPostPlace('');
return;
}

if (prevZipCode.current === formData.zipCode && hasFetchedPostPlace.current === true) {
if (!formData.zipCode || !isValidZipCode) {
if (postPlace !== '') {
setPostPlace('');
}
hasLookedUp.current = false;
return;
}

const fetchPostPlace = async (pnr: string, cancellationToken: any) => {
hasFetchedPostPlace.current = false;
try {
prevZipCode.current = formData.zipCode;
const response = await httpGet('https://api.bring.com/shippingguide/api/postalCode.json', {
params: {
clientUrl: window.location.href,
pnr,
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
cancelToken: cancellationToken,
});
if (response.valid) {
setPostPlace(response.result);
setValidations({ ...validations, zipCode: undefined });
onSaveField(AddressKeys.postPlace, response.result);
} else {
const errorMessage = langAsString('address_component.validation_error_zipcode');
setPostPlace('');
setValidations({ ...validations, zipCode: errorMessage });
}
hasFetchedPostPlace.current = true;
} catch (err) {
// eslint-disable-next-line import/no-named-as-default-member
if (axios.isCancel(err)) {
// Intentionally ignored
} else {
window.logError(`AddressComponent (${id}):\n`, err);
}
if (postPlaceFromHook) {
setPostPlace(postPlaceFromHook);
setValidations({ ...validations, zipCode: undefined });
handleDataChange(postPlaceFromHook, { key: AddressKeys.postPlace });
hasLookedUp.current = true;
} else if (hasLookedUp.current || postPlaceFromHook === '') {

Check warning on line 121 in src/layout/Address/AddressComponent.tsx

View workflow job for this annotation

GitHub Actions / Type-checks, eslint, unit tests and SonarCloud

Merge this if statement with the nested one
// If we've looked up before and got empty result, or hook returned empty string for valid format
// This means the zip code format is valid but doesn't exist in the registry
if (postPlaceFromHook === '' && hasLookedUp.current) {
const errorMessage = langAsString('address_component.validation_error_zipcode');
setPostPlace('');
setValidations({ ...validations, zipCode: errorMessage });
}
};

fetchPostPlace(formData.zipCode, source.token);
return function cleanup() {
source.cancel('ComponentWillUnmount');
};
}, [formData.zipCode, langAsString, source, onSaveField, validations, setPostPlace, id, setValidations]);
}
}, [
formData.zipCode,
isValidZipCode,
postPlaceFromHook,
postPlace,
setPostPlace,
handleDataChange,
langAsString,
setValidations,
validations,
]);

const updateField = (key: AddressKeys, saveImmediately: boolean, event: any): void => {
const changedFieldValue: string = event.target.value;
Expand Down
40 changes: 40 additions & 0 deletions src/layout/Address/usePostPlace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useQuery } from '@tanstack/react-query';

import { useAppQueriesContext } from 'src/contexts/appQueriesContext';
import type { PostalCodesRegistry } from 'src/types/shared';

const __default__ = '';

function lookupPostPlace(data: PostalCodesRegistry, zip: string): string {
const index = parseInt(zip, 10);
if (isNaN(index) || index < 0 || index >= data.mapping.length) {
return '';
}
const placeIndex = data.mapping[index];
if (placeIndex === 0) {
return '';
}
return data.places[placeIndex] ?? '';
}

/**
* Looks up the post place for a given zip code by fetching postal code data.
* This hook was designed primarily for use in the Address component.
*/
export function usePostPlace(zipCode: string | undefined, enabled: boolean) {
const { fetchPostalCodes } = useAppQueriesContext();
const _enabled = enabled && Boolean(zipCode?.length) && zipCode !== __default__ && zipCode !== '0';

const { data } = useQuery({
queryKey: ['postalCodes'],
queryFn: fetchPostalCodes,
staleTime: Infinity,
enabled: _enabled,
});

if (!_enabled || !data) {
return __default__;
}

return lookupPostPlace(data, zipCode!);
}
6 changes: 5 additions & 1 deletion src/queries/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
getJsonSchemaUrl,
getLayoutSetsUrl,
getPartyValidationUrl,
postalCodesUrl,
profileApiUrl,
refreshJwtTokenUrl,
validPartiesUrl,
Expand All @@ -20,7 +21,7 @@ import { orgsListUrl } from 'src/utils/urls/urlHelper';
import type { IApplicationMetadata } from 'src/features/applicationMetadata';
import type { IFooterLayout } from 'src/features/footer/types';
import type { ILayoutSets, ISimpleInstance } from 'src/types';
import type { IAltinnOrgs, IApplicationSettings, IProfile } from 'src/types/shared';
import type { IAltinnOrgs, IApplicationSettings, IProfile, PostalCodesRegistry } from 'src/types/shared';

export const doPartyValidation = async (partyId: string) => (await httpPost(getPartyValidationUrl(partyId))).data;

Expand Down Expand Up @@ -52,3 +53,6 @@ export const fetchDataModelSchema = (dataTypeName: string): Promise<JSONSchema7>
httpGet(getJsonSchemaUrl() + dataTypeName);

export const fetchFormData = (url: string, options?: AxiosRequestConfig): Promise<any> => httpGet(url, options);

export const fetchPostalCodes = async (): Promise<PostalCodesRegistry> =>
(await fetch(postalCodesUrl, { referrerPolicy: 'no-referrer' })).json();
10 changes: 10 additions & 0 deletions src/testUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@ export const renderWithProviders = (
fetchParties: () => Promise.resolve({}),
fetchRefreshJwtToken: () => Promise.resolve({}),
fetchFormData: () => Promise.resolve({}),
fetchPostalCodes: () =>
Promise.resolve({
places: [null, 'OSLO', 'BERGEN'],
mapping: (() => {
const m = new Array(10000).fill(0);
m[1] = 1; // 0001 -> OSLO
m[2] = 2; // 0002 -> BERGEN
return m;
})(),
}),
} as AppQueriesContext;
const mockedQueries = { ...allMockedQueries, ...queries };

Expand Down
5 changes: 5 additions & 0 deletions src/types/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,8 @@ export type IAuthContext = {
read: boolean;
write: boolean;
} & { [action in IActionType]: boolean };

export interface PostalCodesRegistry {
places: (string | null)[];
mapping: number[];
}
1 change: 1 addition & 0 deletions src/utils/urls/appUrlHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const validPartiesUrl = `${appPath}/api/v1/parties?allowedtoinstantiatefi
export const currentPartyUrl = `${appPath}/api/authorization/parties/current?returnPartyObject=true`;
export const instancesControllerUrl = `${appPath}/instances`;
export const refreshJwtTokenUrl = `${appPath}/api/authentication/keepAlive`;
export const postalCodesUrl = 'https://altinncdn.no/postcodes/registry.json';

export const updateCookieUrl = (partyId: string) => `${appPath}/api/v1/parties/${partyId}`;

Expand Down
16 changes: 1 addition & 15 deletions test/e2e/integration/frontend-test/components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,25 +170,11 @@ describe('UI Components', () => {
it('address component fetches post place from zip code', () => {
cy.goto('changename');

// Mock zip code API, so that we don't rely on external services for our tests
cy.intercept('GET', 'https://api.bring.com/shippingguide/api/postalCode.json**', (req) => {
req.reply((res) => {
res.send({
body: {
postalCodeType: 'NORMAL',
result: 'KARDEMOMME BY', // Intentionally wrong, to test that our mock is used
valid: true,
},
});
});
}).as('zipCodeApi');

cy.get(appFrontend.changeOfName.address.street_name).type('Sesame Street 1A');
cy.get(appFrontend.changeOfName.address.street_name).blur();
cy.get(appFrontend.changeOfName.address.zip_code).type('0123');
cy.get(appFrontend.changeOfName.address.zip_code).type('4609');
cy.get(appFrontend.changeOfName.address.zip_code).blur();
cy.get(appFrontend.changeOfName.address.post_place).should('have.value', 'KARDEMOMME BY');
cy.get('@zipCodeApi').its('request.url').should('include', '0123');
});

it('radios, checkboxes and other components can be readOnly', () => {
Expand Down
Loading