Skip to content

Commit

Permalink
Revert "Handle missing auth and improve error handling"
Browse files Browse the repository at this point in the history
This reverts commit 76103b6.
  • Loading branch information
cskrov committed Oct 2, 2024
1 parent d717144 commit 917da68
Show file tree
Hide file tree
Showing 15 changed files with 102 additions and 136 deletions.
75 changes: 53 additions & 22 deletions frontend/src/components/autosave-progress/autosave-progress.tsx
Original file line number Diff line number Diff line change
@@ -1,45 +1,76 @@
import { useTranslation } from '@app/language/use-translation';
import { CheckmarkIcon } from '@navikt/aksel-icons';
import { Tooltip } from '@navikt/ds-react';
import { formatDate, isToday, parseISO } from 'date-fns';
import { CheckmarkIcon, XMarkOctagonIcon } from '@navikt/aksel-icons';
import { Popover } from '@navikt/ds-react';
import { formatDate, formatISO, isToday } from 'date-fns';
import { useRef, useState } from 'react';
import { styled } from 'styled-components';

interface Props {
lastSaved: string;
isLoading: boolean;
isError: boolean;
isSuccess: boolean;
lastSaved: Date;
}

const AutosaveContainer = styled.div`
display: flex;
justify-content: flex-start;
align-items: center;
text-align: right;
column-gap: 4px;
margin-top: 4px;
color: var(--a-text-subtle);
`;

export const AutosaveProgressIndicator = ({ lastSaved }: Props) => {
const AutosaveContent = styled.div`
cursor: pointer;
> svg {
margin-right: 5px;
}
display: flex;
flex-flow: row wrap;
align-items: center;
`;

export const AutosaveProgressIndicator = (props: Props) => {
const { skjema } = useTranslation();
const { tooltip: popover, saved } = skjema.begrunnelse.autosave;
const { popover, saved, failed } = skjema.begrunnelse.autosave;
const anchor = useRef<HTMLDivElement>(null);
const [isOpen, setIsOpen] = useState(false);

return (
<Tooltip content={popover}>
<AutosaveContainer>
<CheckmarkIcon aria-hidden />
<span>
{saved} {getDate(lastSaved)}
</span>
</AutosaveContainer>
</Tooltip>
<AutosaveContainer style={{ color: props.isError ? 'var(--a-text-danger)' : 'var(--a-text-subtle)' }}>
<AutosaveContent ref={anchor} onClick={() => setIsOpen(!isOpen)}>
{getContent(props, saved, failed)}
</AutosaveContent>
<Popover open={isOpen} anchorEl={anchor.current} onClose={() => setIsOpen(false)} placement="top-end">
<Popover.Content>{popover}</Popover.Content>
</Popover>
</AutosaveContainer>
);
};

const getDate = (date: string) => {
const parsed = parseISO(date);
const getContent = (status: Props, saved: string, failed: string) => {
if (status.isError) {
return (
<>
<XMarkOctagonIcon aria-hidden />
{failed}
</>
);
}

return (
<>
<CheckmarkIcon aria-hidden />
<span>
{saved} {getDate(status.lastSaved)}
</span>
</>
);
};

if (isToday(parsed)) {
return <time dateTime={date}>{formatDate(parsed, 'HH:mm:ss')}</time>;
const getDate = (date: Date) => {
if (isToday(date)) {
return <time dateTime={formatISO(date)}>{formatDate(date, 'HH:mm:ss')}</time>;
}

return <time dateTime={date}>{formatDate(parsed, 'dd.MM.yyyy HH:mm:ss')}</time>;
return <time dateTime={formatISO(date)}>{formatDate(date, 'dd.MM.yyyy HH:mm:ss')}</time>;
};
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const DigitalFormContainer = ({
page_title,
}: Props) => {
const [undertittel] = useInnsendingsytelseName(innsendingsytelse);
const { isAuthenticated } = useIsAuthenticated();
const { data: isAuthenticated } = useIsAuthenticated();

usePageInit(`${steps[activeStep - 1] ?? ''} \u2013 ${title_fragment}`);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { type Case, CaseStatus, CaseType, type CaseUpdatable } from '@app/redux-
import { API_PATH } from '@app/redux-api/common';
import { CenteredContainer } from '@app/styled-components/common';
import { Alert, BodyLong, Button, GuidePanel } from '@navikt/ds-react';
import { parseISO } from 'date-fns';
import { useCallback, useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { DeleteCaseButton } from '../../../delete-case-button/delete-case-button';
Expand All @@ -35,9 +36,9 @@ interface Props {
const RenderCasebegrunnelsePage = ({ data }: Props) => {
const navigate = useNavigate();
const language = useLanguage();
const { user, isLoadingUser } = useUser();
const { data: user } = useUser();

const { skjema, user_loader } = useTranslation();
const { skjema } = useTranslation();

const [updateCase] = useUpdateCaseMutation();
const [deleteAttachment] = useDeleteAttachmentMutation();
Expand Down Expand Up @@ -88,6 +89,8 @@ const RenderCasebegrunnelsePage = ({ data }: Props) => {
const isKlage = data.type === CaseType.KLAGE;
const isEttersendelseKlage = data.type === CaseType.ETTERSENDELSE_KLAGE;

const modified = parseISO(data.modifiedByUser);

const onChange = useCallback(
async <T extends keyof CaseUpdatable>(key: T, value: CaseUpdatable[T]) => {
await updateCase({ key, value, id: data.id });
Expand All @@ -109,13 +112,12 @@ const RenderCasebegrunnelsePage = ({ data }: Props) => {
<BodyLong>{skjema.employer_info[data.type]}</BodyLong>
</GuidePanel>

<PersonligeOpplysningerSummary
fornavn={isLoadingUser ? user_loader.loading_user : user.navn.fornavn}
etternavn={isLoadingUser ? user_loader.loading_user : user.navn.etternavn}
f_or_d_number={
isLoadingUser ? user_loader.loading_user : user.folkeregisteridentifikator?.identifikasjonsnummer
}
/>
{user !== undefined ? (
<PersonligeOpplysningerSummary
{...user.navn}
f_or_d_number={user.folkeregisteridentifikator?.identifikasjonsnummer}
/>
) : null}

{isKlage ? (
<Reasons
Expand Down Expand Up @@ -155,7 +157,7 @@ const RenderCasebegrunnelsePage = ({ data }: Props) => {
placeholder={skjema.begrunnelse.begrunnelse_text.placeholder[data.type]}
label={skjema.begrunnelse.begrunnelse_text.title[data.type]}
error={errors[FormFieldsIds.FRITEKST]}
modified={data.modifiedByUser}
modified={modified}
/>

<AttachmentsSection
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { AutosaveProgressIndicator } from '@app/components/autosave-progress/autosave-progress';
import { FormFieldsIds } from '@app/components/case/common/form-fields-ids';
import { useOnUnmount } from '@app/hooks/use-on-unmount';
import { useTranslation } from '@app/language/use-translation';
import { useUpdateCaseMutation } from '@app/redux-api/case/api';
import { Textarea, type TextareaProps } from '@navikt/ds-react';
import { useCallback, useEffect, useState } from 'react';
Expand All @@ -10,20 +9,19 @@ interface Props extends Omit<TextareaProps, 'label' | 'onError' | 'onChange'> {
caseId: string;
value: string;
label: string;
modified: string;
error: string | undefined;
modified: Date;
}

export const BegrunnelseText = ({ caseId, value, modified, error, ...props }: Props) => {
export const BegrunnelseText = ({ caseId, value, modified, ...props }: Props) => {
const [localValue, setLocalValue] = useState(value);
const [updateCase, status] = useUpdateCaseMutation();
const [lastSaved, setLastSaved] = useState<string>(modified);
const { skjema } = useTranslation();
const { failed } = skjema.begrunnelse.autosave;
const [lastSaved, setLastSaved] = useState<Date>(modified);

const updateFritekst = useCallback(
async (newValue: string) => {
const { modifiedByUser } = await updateCase({ key: 'fritekst', value: newValue, id: caseId }).unwrap();
setLastSaved(modifiedByUser);
await updateCase({ key: 'fritekst', value: newValue, id: caseId });
setLastSaved(new Date());
},
[caseId, updateCase],
);
Expand Down Expand Up @@ -54,7 +52,6 @@ export const BegrunnelseText = ({ caseId, value, modified, error, ...props }: Pr
onChange={({ target }) => setLocalValue(target.value)}
value={localValue}
placeholder="Skriv her"
error={status.isError ? failed : error}
{...props}
/>
<AutosaveProgressIndicator {...status} lastSaved={lastSaved} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const FinalizeDigitalCase = ({ setError, status, id, fritekst, type, vedl
const navigate = useNavigate();
const { skjema, common } = useTranslation();
const [loading, setIsLoading] = useState<boolean>(false);
const { isAuthenticated } = useIsAuthenticated();
const { data: isAuthenticated } = useIsAuthenticated();

const errorTranslation = skjema.summary.submit_error;
const nextTranslation = skjema.summary.next;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,21 @@ interface Props {
}

const DigitalCaseOppsummeringPage = ({ data }: Props) => {
const { common, skjema, user_loader, icons } = useTranslation();
const { isAuthenticated } = useIsAuthenticated();
const { common, skjema, icons } = useTranslation();
const { data: isAuthenticated } = useIsAuthenticated();
const validate = useCaseErrors(data.type);
const [isValid] = validate(data);

const [error, setError] = useState<string | null>(null);

const { user, isLoadingUser } = useUser();
const { data: user, isLoading: userIsLoading } = useUser();

useGoToBegrunnelseOnError(isValid);

if (userIsLoading || user === undefined) {
return null;
}

const incompleteStatus = data.status === CaseStatus.DRAFT || data.status === CaseStatus.DOWNLOADED;

return (
Expand All @@ -66,11 +70,8 @@ const DigitalCaseOppsummeringPage = ({ data }: Props) => {
</Heading>
<BodyLong spacing>{skjema.summary.sections.person.info_from}</BodyLong>
<PersonligeOpplysningerSummary
fornavn={isLoadingUser ? user_loader.loading_user : user.navn.fornavn}
etternavn={isLoadingUser ? user_loader.loading_user : user.navn.etternavn}
f_or_d_number={
isLoadingUser ? user_loader.loading_user : user.folkeregisteridentifikator?.identifikasjonsnummer
}
{...user.navn}
f_or_d_number={user.folkeregisteridentifikator?.identifikasjonsnummer ?? ''}
/>
</Section>

Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/case/uinnlogget/session-loader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ interface Props {
}

export const KlageSessionLoader = ({ Component, innsendingsytelse, type }: Props) => {
const { isAuthenticated, isLoadingAuth } = useIsAuthenticated();
const { data: isAuthenticated, isLoading: userIsLoading, isFetching: userIsFetching } = useIsAuthenticated();
const [query] = useSearchParams();
const internalSaksnummer = getQueryValue(query.get('saksnummer'));
const [data, isLoading] = useSessionCase(type, innsendingsytelse, internalSaksnummer);
const { case_loader: klage_loader, user_loader } = useTranslation();
const language = useLanguage();

if (isLoadingAuth) {
if (userIsLoading || userIsFetching) {
return <LoadingPage>{user_loader.loading_user}</LoadingPage>;
}

Expand Down
51 changes: 6 additions & 45 deletions frontend/src/hooks/use-user.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,14 @@
import { useGetSessionQuery, useGetUserQuery } from '@app/redux-api/user/api';
import type { IUser } from '@app/redux-api/user/types';
import { type SkipToken, skipToken } from '@reduxjs/toolkit/query';

interface LoadingAuth {
isAuthenticated: undefined;
isLoadingAuth: true;
}
export const useIsAuthenticated = (skip?: SkipToken) => {
const { data, ...rest } = useGetSessionQuery(skip, { refetchOnFocus: true, refetchOnReconnect: true });

interface LoadedAuth {
isAuthenticated: boolean;
isLoadingAuth: false;
}

type AuthResult = LoadingAuth | LoadedAuth;

export const useIsAuthenticated = (skip?: SkipToken): AuthResult => {
const { isAuthenticated, isLoading } = useGetSessionQuery(skip, {
refetchOnFocus: true,
refetchOnReconnect: true,
selectFromResult: ({ data, isLoading }) => ({ isLoading, isAuthenticated: data?.session.active }),
});

if (isLoading || isAuthenticated === undefined) {
return { isAuthenticated: undefined, isLoadingAuth: true };
}

return { isAuthenticated, isLoadingAuth: false };
return { ...rest, data: data?.session.active ?? false };
};

interface LoadedUser {
user: IUser;
isLoadingUser: false;
}

interface LoadingUser {
user: undefined;
isLoadingUser: true;
}

type UserResult = LoadedUser | LoadingUser;

export const useUser = (): UserResult => {
const { isAuthenticated } = useIsAuthenticated();

const { data: user } = useGetUserQuery(isAuthenticated === true ? undefined : skipToken);

if (user === undefined) {
return { user: undefined, isLoadingUser: true };
}
export const useUser = () => {
const { data } = useIsAuthenticated();

return { user, isLoadingUser: false };
return useGetUserQuery(data === true ? undefined : skipToken);
};
2 changes: 1 addition & 1 deletion frontend/src/language/en.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export const en: Translations = {
},
begrunnelse: {
autosave: {
tooltip: 'We are saving your changes automatically.',
popover: 'We are saving your changes automatically.',
saved: 'Last saved',
failed: 'Failed to save',
},
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/language/nb.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ export const nb = {
},
begrunnelse: {
autosave: {
tooltip: 'Vi lagrer endringene dine automatisk.',
popover: 'Vi lagrer endringene dine automatisk.',
saved: 'Sist lagret',
failed: 'Kunne ikke lagre',
failed: 'Klarte ikke lagre',
},
attachments: {
clear_errors: 'Fjern feilmeldinger',
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/language/nn.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export const nn: Translations = {
},
begrunnelse: {
autosave: {
tooltip: 'Vi lagrar endringane dine automatisk.',
popover: 'Vi lagrar endringane dine automatisk.',
saved: 'Sist lagra',
failed: 'Klarte ikkje å lagre',
},
Expand Down
1 change: 0 additions & 1 deletion frontend/src/logging/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,4 @@ export enum AppEventEnum {
UPLOAD_FILES_DONE = 'Done uploading files',
UPLOAD_FILES_START = 'Start uploading files',
USER_LOGIN = 'Login',
MISSING_AUTH = 'Missing authentication',
}
Loading

0 comments on commit 917da68

Please sign in to comment.