Skip to content

Commit

Permalink
Rydding i utils (#6908)
Browse files Browse the repository at this point in the history
* Forbedrer typing i utils

* Rydder bort ubrukte funksjoner

* fiks
  • Loading branch information
hallvardastark authored Dec 16, 2024
1 parent 3b46079 commit 93d600c
Show file tree
Hide file tree
Showing 20 changed files with 183 additions and 300 deletions.
21 changes: 0 additions & 21 deletions packages/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,14 @@ export { diff, isEqual, omit } from './src/objectUtils';
export { buildPath, formatQueryString, parseQueryString } from './src/urlUtils';
export {
ariaCheck,
arrayMinLength,
dateAfterOrEqual,
dateAfterOrEqualToToday,
dateAfterToday,
dateBeforeOrEqual,
dateBeforeOrEqualToToday,
dateBeforeToday,
dateIsAfter,
dateIsBefore,
dateRangesNotOverlapping,
dateRangesNotOverlappingCrossTypes,
hasValidDate,
hasValidDecimal,
hasValidDecimalMaxNumberOfDecimals,
Expand All @@ -38,45 +35,27 @@ export {
hasValidInteger,
hasValidName,
hasValidOrgNumber,
hasValidOrgNumberOrFodselsnr,
hasValidPeriod,
hasValidPeriodIncludingOtherErrors,
hasValidSaksnummerOrFodselsnummerFormat,
hasValidText,
hasValidValue,
isArbeidsProsentVidUtsettelse100,
isDatesEqual,
isTrekkdagerMerEnnNullUtsettelse,
isUkerOgDagerVidNullUtbetalningsgrad,
isUtbetalingMerEnnNullUtsettelse,
isUtbetalingsgradMerSamitidigUttaksprosent,
isWithinOpptjeningsperiode,
isutbetalingPlusArbeidsprosentMerEn100,
maxLength,
maxLengthOrFodselsnr,
maxValue,
maxValueFormatted,
minLength,
minValue,
minValueFormatted,
notDash,
required,
requiredIfCustomFunctionIsTrue,
requiredIfNotPristine,
validPeriodeFomTom,
validateProsentandel,
} from './src/validation/validators';

export {
dateNotAfterOrEqualMessage,
dateNotBeforeOrEqualMessage,
dateRangesOverlappingBetweenPeriodTypesMessage,
dateRangesOverlappingMessage,
invalidDateMessage,
invalidDecimalMessage,
invalidPeriodMessage,
isRequiredMessage,
sammeFodselsnummerSomSokerMessage,
} from './src/validation/messages';

export { findAksjonspunkt } from './src/micro-frontends/findAksjonspunkt';
Expand Down
2 changes: 1 addition & 1 deletion packages/utils/src/arbeidsforholdUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ArbeidsforholdV2, ArbeidsgiverOpplysningerPerId } from '@k9-sak-web/types';

const getEndCharFromId = id => (id ? `...${id.substring(id.length - 4, id.length)}` : '');
const getEndCharFromId = (id: string) => (id ? `...${id.substring(id.length - 4, id.length)}` : '');

export const utledArbeidsforholdNavn = (
arbeidsforhold: ArbeidsforholdV2,
Expand Down
8 changes: 4 additions & 4 deletions packages/utils/src/arrayUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export const range = length => [...Array(length).keys()];
export const range = (length: number) => [...Array(length).keys()];

export const haystack = (object, keys, defaultValue = null) => {
export const haystack = (object: unknown, keys: string | string[], defaultValue = null) => {
const keysArray = Array.isArray(keys) ? keys : keys.replace(/(\[(\d+)\])/g, '.$2').split('.');
const currentObject = object[keysArray[0]];
if (currentObject && keysArray.length > 1) {
Expand All @@ -9,7 +9,7 @@ export const haystack = (object, keys, defaultValue = null) => {
return currentObject === undefined ? defaultValue : currentObject;
};

export const makeArrayWithoutDuplicates = (array: any[]) => {
export const makeArrayWithoutDuplicates = (array: unknown[]) => {
const arrayWithoutDuplicates = [];
array.forEach(value => {
if (!arrayWithoutDuplicates.includes(value)) {
Expand All @@ -19,5 +19,5 @@ export const makeArrayWithoutDuplicates = (array: any[]) => {
return arrayWithoutDuplicates;
};

export const getArrayDifference = (baseArray: any[], otherArray: any[]) =>
export const getArrayDifference = (baseArray: string[], otherArray: string[]) =>
baseArray.filter(value => otherArray.includes(value) === false);
8 changes: 4 additions & 4 deletions packages/utils/src/beregning/VilkarMapper.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Vilkar as FTVilkarType } from '@navikt/ft-types';
import { BeregningReferanse } from '@k9-sak-web/types';
import { Vilkar as FTVilkarType } from '@navikt/ft-types';
import { VilkårMedPerioderDto } from '@navikt/k9-sak-typescript-client';

type Periode = { fom: string; tom: string };

Expand All @@ -11,8 +12,7 @@ const erForlengelse = (beregningreferanserTilVurdering: BeregningReferanse[], pe
return undefined;
};

// TODO: Legg til type for vilkar når kodeverkjobben er gjort. Formattering her skal vere på nytt format (må gjøres utenfor)
const mapVilkar = (vilkar, beregningreferanserTilVurdering: BeregningReferanse[]): FTVilkarType =>
const mapVilkar = (vilkar: VilkårMedPerioderDto, beregningreferanserTilVurdering: BeregningReferanse[]): FTVilkarType =>
({
vilkarType: vilkar.vilkarType,
overstyrbar: vilkar.overstyrbar,
Expand All @@ -26,6 +26,6 @@ const mapVilkar = (vilkar, beregningreferanserTilVurdering: BeregningReferanse[]
vilkarStatus: p.vilkarStatus,
erForlengelse: erForlengelse(beregningreferanserTilVurdering, p.periode),
})),
} as FTVilkarType);
}) as FTVilkarType;

export default mapVilkar;
10 changes: 5 additions & 5 deletions packages/utils/src/currencyUtils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
export const formatCurrencyWithKr = value => {
export const formatCurrencyWithKr = (value: string | number) => {
const formattedValue = Number(value).toLocaleString('nb-NO').replace(/,|\s/g, ' ');
return `${formattedValue} kr`;
};

export const formatCurrencyNoKr = value => {
export const formatCurrencyNoKr = (value: string | number) => {
if (value === null || value === undefined) {
return undefined;
}
Expand All @@ -12,18 +12,18 @@ export const formatCurrencyNoKr = value => {
if (Number.isNaN(newVal)) {
return undefined;
}
return Number(Math.round(newVal)).toLocaleString('nb-NO').replace(/,|\s/g, ' ');
return Number(Math.round(+newVal)).toLocaleString('nb-NO').replace(/,|\s/g, ' ');
};

export const removeSpacesFromNumber = (input: number | string): number => {
if (!input || input === Number(input)) {
return input as number;
}
const parsedValue = parseInt((input as string).replace(/\s/g, ''), 10);
return Number.isNaN(parsedValue) ? input as number : parsedValue;
return Number.isNaN(parsedValue) ? (input as number) : parsedValue;
};

export const parseCurrencyInput = input => {
export const parseCurrencyInput = (input: number | string) => {
const inputNoSpace = input.toString().replace(/\s/g, '');
const parsedValue = parseInt(inputNoSpace, 10);
return Number.isNaN(parsedValue) ? '' : formatCurrencyNoKr(parsedValue);
Expand Down
2 changes: 1 addition & 1 deletion packages/utils/src/date-utils/dateComparison.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const isDayAfter = (d1: dayjs.Dayjs, d2: dayjs.Dayjs) => {
return dayAfterD1.isSame(d2Day);
};

export function isSameOrBefore(date, otherDate) {
export function isSameOrBefore(date: dayjs.Dayjs | string, otherDate: dayjs.Dayjs | string) {
const dateFormats = ['YYYY-MM-DD', 'DD.MM.YYYY'];
const dateInQuestion = dayjs(date, dateFormats).utc(true);
const formattedOtherDate = dayjs(otherDate, dateFormats).utc(true);
Expand Down
2 changes: 1 addition & 1 deletion packages/utils/src/date-utils/isValid.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// eslint-disable-next-line no-restricted-globals
const isValid = (date: any) => !isNaN(new Date(date) as any);
const isValid = (date: string) => !isNaN(new Date(date) as any);

export default isValid;
2 changes: 1 addition & 1 deletion packages/utils/src/decodeHtmlEntity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Decoder for decoding html entity navn og entity code
* på sikkerhetshensyn '<(&lt; &#60;)' og '> (&gt; &#62;)' er ikke decodert
*/
const decodeHtmlEntity = str => {
const decodeHtmlEntity = (str: string) => {
if (str === null || str === undefined) {
return str;
}
Expand Down
16 changes: 11 additions & 5 deletions packages/utils/src/findStatusForVedtak.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
import aksjonspunktCodes from '@fpsak-frontend/kodeverk/src/aksjonspunktCodes';
import { isAksjonspunktOpen } from '@fpsak-frontend/kodeverk/src/aksjonspunktStatus';
import { isAvslag } from '@fpsak-frontend/kodeverk/src/behandlingResultatType';
import aksjonspunktCodes from '@fpsak-frontend/kodeverk/src/aksjonspunktCodes';
import vilkarUtfallType from '@fpsak-frontend/kodeverk/src/vilkarUtfallType';
import { Aksjonspunkt, Behandlingsresultat, Vilkar } from '@k9-sak-web/types';

const hasOnlyClosedAps = (aksjonspunkter, vedtakAksjonspunkter) =>
const hasOnlyClosedAps = (aksjonspunkter: Aksjonspunkt[], vedtakAksjonspunkter: Aksjonspunkt[]) =>
aksjonspunkter
.filter(ap => !vedtakAksjonspunkter.some(vap => vap.definisjon.kode === ap.definisjon.kode))
.every(ap => !isAksjonspunktOpen(ap.status.kode));

const hasAksjonspunkt = ap => ap.definisjon.kode === aksjonspunktCodes.OVERSTYR_BEREGNING;
const hasAksjonspunkt = (ap: Aksjonspunkt) => ap.definisjon.kode === aksjonspunktCodes.OVERSTYR_BEREGNING;

const isAksjonspunktOpenAndOfType = ap => hasAksjonspunkt(ap) && isAksjonspunktOpen(ap.status.kode);
const isAksjonspunktOpenAndOfType = (ap: Aksjonspunkt) => hasAksjonspunkt(ap) && isAksjonspunktOpen(ap.status.kode);

const findStatusForVedtak = (vilkar, aksjonspunkter, vedtakAksjonspunkter, behandlingsresultat) => {
const findStatusForVedtak = (
vilkar: Vilkar[],
aksjonspunkter: Aksjonspunkt[],
vedtakAksjonspunkter: Aksjonspunkt[],
behandlingsresultat: Behandlingsresultat,
) => {
if (vilkar.length === 0) {
return vilkarUtfallType.IKKE_VURDERT;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/utils/src/fodselsnummerUtils.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
export const fodselsnummerPattern = /^\d{11}$/;

const sum = (fodselsnummer, faktors) => {
const sum = (fodselsnummer: string, faktors: number[]) => {
let s = 0;
for (let i = 0; i < faktors.length; i += 1) {
s += parseInt(fodselsnummer[i], 10) * faktors[i];
}
return s;
};

export const isValidFodselsnummer = input => {
export const isValidFodselsnummer = (input: string | number) => {
const fodselsnummer = `${input}`;
if (!fodselsnummerPattern.test(fodselsnummer)) {
return false;
Expand Down
7 changes: 4 additions & 3 deletions packages/utils/src/kodeverkUtils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { KodeverkMedNavn, Kodeverk } from '@k9-sak-web/types';
import { KodeverkObject } from '@k9-sak-web/lib/kodeverk/types.js';
import { Kodeverk } from '@k9-sak-web/types';

export const getKodeverknavnFraKode = (
alleKodeverk: { [key: string]: KodeverkMedNavn[] },
alleKodeverk: { [key: string]: KodeverkObject[] },
kodeverkType: string,
kode: string,
undertype?: string,
Expand All @@ -18,7 +19,7 @@ export const getKodeverknavnFraKode = (
return kodeverk ? kodeverk.navn : '';
};
export const getKodeverknavnFn =
(alleKodeverk: { [key: string]: KodeverkMedNavn[] }, kodeverkTyper: { [key: string]: string }) =>
(alleKodeverk: { [key: string]: KodeverkObject[] }, kodeverkTyper: { [key: string]: string }) =>
(kodeverkOjekt: Kodeverk, undertype?: string) =>
getKodeverknavnFraKode(alleKodeverk, kodeverkTyper[kodeverkOjekt.kodeverk], kodeverkOjekt.kode, undertype);

Expand Down
4 changes: 2 additions & 2 deletions packages/utils/src/languageUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import getPackageIntl from '../i18n/getPackageIntl';

const intl = getPackageIntl();

export const replaceNorwegianCharacters = str => {
export const replaceNorwegianCharacters = (str: string) => {
let result = str.split('æ').join('ae');
result = result.split('ø').join('oe');
return result.split('å').join('aa');
};

// TODO Fjern bruk av denne
export const getLanguageCodeFromSprakkode = sprakkode => {
export const getLanguageCodeFromSprakkode = (sprakkode: Kodeverk) => {
if (!sprakkode) {
return 'Malform.Bokmal';
}
Expand Down
14 changes: 7 additions & 7 deletions packages/utils/src/objectUtils.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
export const isEqual = (obj1, obj2) => JSON.stringify(obj1) === JSON.stringify(obj2);
export const isEqual = (obj1: object, obj2: object) => JSON.stringify(obj1) === JSON.stringify(obj2);

export const omit = (object, ...keysToOmit) =>
export const omit = (object: object, ...keysToOmit: string[]) =>
Object.keys(object)
.filter(key => !keysToOmit.includes(key))
.map(key => ({ [key]: object[key] }))
.reduce((a, b) => Object.assign(a, b), {});

const isNullOrUndefined = obj => obj === null || typeof obj === 'undefined';
const isNotNullAndObject = obj => obj !== null && typeof obj === 'object' && obj.constructor;
const isNullOrUndefined = (value: unknown): boolean => value === null || value === undefined;
const isNotNullAndObject = (value: unknown): value is object => value !== null && typeof value === 'object';

const redefineIfUndefined = (obj, otherObjOfType) => {
const redefineIfUndefined = <T>(obj: T, otherObjOfType: T): T | null => {
if (isNullOrUndefined(obj) && isNotNullAndObject(otherObjOfType)) {
try {
return new otherObjOfType.constructor();
return new (otherObjOfType.constructor as { new (): T })();
} catch {
return null;
}
}
return obj;
};

export const diff = (a, b) => {
export const diff = (a: unknown, b: unknown) => {
const thing1 = redefineIfUndefined(a, b);
const thing2 = redefineIfUndefined(b, a);
if (typeof thing1 !== typeof thing2) {
Expand Down
2 changes: 1 addition & 1 deletion packages/utils/src/period-utils/findHolesInPeriods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { initializeDate } from '@k9-sak-web/lib/dateUtils/initializeDate.js';
import Period from './Period';
import sortPeriodsByFomDate from './sortPeriodsByFomDate';

const checkIfPeriodsAreEdgeToEdge = (period, otherPeriod) => {
const checkIfPeriodsAreEdgeToEdge = (period: Period, otherPeriod: Period) => {
const dayAfterPeriod = initializeDate(period.tom).add(1, 'day');
const startOfNextPeriod = initializeDate(otherPeriod.fom);
return dayAfterPeriod.isSame(startOfNextPeriod);
Expand Down
4 changes: 2 additions & 2 deletions packages/utils/src/stringUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export const joinNonNullStrings = (strings: any[]): string => strings.filter(s => !!s).join('');
export const joinNonNullStrings = (strings: string[]): string => strings.filter(s => !!s).join('');

export function safeJSONParse(str) {
export function safeJSONParse(str: any) {
try {
return JSON.parse(str);
} catch {
Expand Down
Loading

0 comments on commit 93d600c

Please sign in to comment.