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
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,6 @@
"marked": "16.4.2",
"marked-mangle": "1.1.12",
"node-polyfill-webpack-plugin": "4.1.0",
"norway-postal-codes": "^4.1.0",
"react": "19.2.3",
"react-compiler-webpack": "0.2.1",
"react-content-loader": "7.1.1",
Expand Down
10 changes: 0 additions & 10 deletions src/layout/Address/AddressComponent.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,6 @@ import { AddressComponent } from 'src/layout/Address/AddressComponent';
import { renderGenericComponentTest } from 'src/test/renderWithProviders';
import type { RenderGenericComponentTestProps } from 'src/test/renderWithProviders';

jest.mock('norway-postal-codes', () => ({
__esModule: true,
default: {
'0001': 'OSLO',
'0002': 'BERGEN',
'1613': 'FREDRIKSTAD',
'4609': 'KARDEMOMME BY',
},
}));

const render = async ({ component, ...rest }: Partial<RenderGenericComponentTestProps<'Address'>> = {}) =>
await renderGenericComponentTest({
type: 'Address',
Expand Down
32 changes: 27 additions & 5 deletions src/layout/Address/usePostPlace.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,40 @@
import postalCodes from 'norway-postal-codes';
import { useQuery } from '@tanstack/react-query';

import { useAppQueries } from 'src/core/contexts/AppQueriesProvider';
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 using the norway-postal-codes package.
* 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 } = useAppQueries();
const _enabled = enabled && Boolean(zipCode?.length) && zipCode !== __default__ && zipCode !== '0';

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

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

const postPlace = postalCodes[zipCode!];
return postPlace ?? __default__;
return lookupPostPlace(data, zipCode!);
}
4 changes: 4 additions & 0 deletions src/queries/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
getUpdateFileTagsUrl,
getValidationUrl,
instancesControllerUrl,
postalCodesUrl,
profileApiUrl,
refreshJwtTokenUrl,
selectedPartyUrl,
Expand Down Expand Up @@ -85,6 +86,7 @@ import type {
IParty,
IProcess,
IProfile,
PostalCodesRegistry,
} from 'src/types/shared';

export const doSetSelectedParty = (partyId: number | string) =>
Expand Down Expand Up @@ -382,3 +384,5 @@ export function fetchExternalApi({
const externalApiUrl = `${appPath}/instances/${instanceId}/api/external/${externalApiId}`;
return httpGet(externalApiUrl);
}

export const fetchPostalCodes = async (): Promise<PostalCodesRegistry> => (await axios.get(postalCodesUrl)).data;
14 changes: 14 additions & 0 deletions src/test/renderWithProviders.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,19 @@ export const makeMutationMocks = <T extends (name: keyof AppMutations) => any>(
doSubformEntryDelete: makeMock('doSubformEntryDelete'),
});

// Mock postal codes data for testing. Uses the indexed format where:
// - places array contains unique place names (index 0 is null for "not found")
// - mapping array maps zip code (as index) to places array index
const defaultPostalCodesMock = (() => {
const places: (string | null)[] = [null, 'OSLO', 'BERGEN', 'FREDRIKSTAD', 'KARDEMOMME BY'];
const mapping = new Array(4610).fill(0);
mapping[1] = 1; // 0001 -> OSLO
mapping[2] = 2; // 0002 -> BERGEN
mapping[1613] = 3; // 1613 -> FREDRIKSTAD
mapping[4609] = 4; // 4609 -> KARDEMOMME BY
return { places, mapping };
})();

const defaultQueryMocks: AppQueries = {
fetchLogo: async () => getLogoMock(),
fetchActiveInstances: async () => [],
Expand Down Expand Up @@ -156,6 +169,7 @@ const defaultQueryMocks: AppQueries = {
fetchBackendValidationsForDataElement: async () => [],
fetchPaymentInformation: async () => paymentResponsePayload,
fetchOrderDetails: async () => orderDetailsResponsePayload,
fetchPostalCodes: async () => defaultPostalCodesMock,
};

function makeProxy<Name extends keyof FormDataMethods>(name: Name, ref: InitialRenderRef) {
Expand Down
5 changes: 5 additions & 0 deletions src/types/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,3 +312,8 @@ export type ProblemDetails = {
detail: string;
status: number;
};

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 @@ -14,6 +14,7 @@ export const selectedPartyUrl = `${appPath}/api/authorization/parties/current?re
export const instancesControllerUrl = `${appPath}/instances`;
export const refreshJwtTokenUrl = `${appPath}/api/authentication/keepAlive`;
export const applicationLanguagesUrl = `${appPath}/api/v1/applicationlanguages`;
export const postalCodesUrl = 'https://altinncdn.no/postcodes/registry.json';

export const getInstantiateUrl = (language?: string) => {
const queryString = getQueryStringFromObject({ language });
Expand Down
3 changes: 2 additions & 1 deletion test/e2e/integration/multiple-datamodels-test/saving.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ describe('saving multiple data models', () => {
cy.findByRole('textbox', { name: /poststed/i }).should('have.value', 'KARDEMOMME BY');

cy.waitUntilSaved();
cy.get('@saveFormData.all').should('have.length', 4);
cy.get('@saveFormData.all').should('have.length.at.least', 4);
cy.get('@saveFormData.all').should('have.length.at.most', 5);
cy.get('@saveFormData.all').should(haveTheSameUrls);

cy.get(appFrontend.altinnError).should('not.exist');
Expand Down
Loading
Loading