Skip to content

Commit

Permalink
feat(concept:changeRequest): api call update change request
Browse files Browse the repository at this point in the history
  • Loading branch information
terjesyl committed Oct 19, 2023
1 parent f7405fc commit 92a7a5f
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 37 deletions.
24 changes: 21 additions & 3 deletions apps/concept-catalog/hooks/change-requests.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { ChangeRequestUpdateBody } from '@catalog-frontend/types';
import { validOrganizationNumber, validUUID } from '@catalog-frontend/utils';
import { useMutation, useQuery } from '@tanstack/react-query';
import { error } from 'console';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/router';

export const useGetChangeRequests = (catalogId: string) => {
Expand Down Expand Up @@ -66,9 +65,28 @@ export const useCreateChangeRequest = ({ catalogId }) => {
};

export const useUpdateChangeRequest = ({ catalogId, changeRequestId }) => {
const queryClient = useQueryClient();

return useMutation({
mutationFn: async (changeRequest: ChangeRequestUpdateBody) => {
return Promise.reject('Not implemented');
if (!validOrganizationNumber(catalogId)) {
return Promise.reject('Invalid catalog id');
}
if (!validUUID(changeRequestId)) {
return Promise.reject('Invalid change request id');
}

const response = await fetch(`/api/change-requests/${catalogId}/updateChangeRequest/${changeRequestId}`, {
method: 'POST',
body: JSON.stringify(changeRequest),
});

if (response.status === 401) {
return Promise.reject('Unauthorized');
}
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['getChangeRequests', catalogId] });
},
});
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,28 @@ import { useCatalogDesign } from '../../../../context/catalog-design';
import { localization as loc, getTranslateText as translate } from '@catalog-frontend/utils';
import styles from './change-request-page.module.css';
import { useState } from 'react';
import {
ChangeRequest,
ChangeRequestUpdateBody,
Concept,
ISOLanguage,
JsonPatchOperation,
} from '@catalog-frontend/types';
import { Concept, ISOLanguage } from '@catalog-frontend/types';
import { FieldArray, Form, Formik } from 'formik';
import { ConceptFormField } from '../../../../components/form-field-container';
import { TextAreaField } from '../../../../components/form-fields/text-area-field';
import { RelationToSource } from '../../../../components/form-fields/relation-to-source';
import { SourceForDefinitionField } from '../../../../components/form-fields/source-for-definition';
import { PlusCircleIcon } from '@navikt/aksel-icons';
import jsonpatch from 'fast-json-patch';

const languageOptions = [
{ value: 'nb', label: 'Norsk bokmål' },
{ value: 'nn', label: 'Norsk nynorsk' },
{ value: 'en', label: 'English' },
];

export const ChangeRequestPage = ({
export const ChangeRequestForm = ({
FDK_REGISTRATION_BASE_URI,
organization,
changeRequest,
changeRequestAsConcept,
originalConcept,
showOriginal = false,
changeRequestMutateHook,
submitHandler,
}) => {
const changeRequestId = changeRequest.id;
const catalogId = organization?.organizationId;
Expand All @@ -43,16 +36,7 @@ export const ChangeRequestPage = ({

const handleSubmit = (values: Concept) => {
setIsSubmitting(true);
const changeRequestFromConcept: ChangeRequestUpdateBody = {
conceptId: changeRequest.conceptId,
operations: jsonpatch.compare(originalConcept, values) as JsonPatchOperation[],
title: '',
};

changeRequestMutateHook.mutateAsync(changeRequestFromConcept).catch((error) => {
alert('Fail');
});

submitHandler(values);
setIsSubmitting(false);
};

Expand Down Expand Up @@ -335,4 +319,4 @@ export const ChangeRequestPage = ({
);
};

export default ChangeRequestPage;
export default ChangeRequestForm;
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import { getOrganization, getConcept, getChangeRequest } from '@catalog-frontend/data-access';
import { Organization, Concept, ChangeRequest } from '@catalog-frontend/types';
import {
Organization,
Concept,
ChangeRequest,
ChangeRequestUpdateBody,
JsonPatchOperation,
} from '@catalog-frontend/types';
import { hasOrganizationReadPermission, validOrganizationNumber, validUUID } from '@catalog-frontend/utils';
import { authOptions } from '../../../api/auth/[...nextauth]';
import { Session, getServerSession } from 'next-auth';
import { ChangeRequestPage } from './_change-request-form';
import { ChangeRequestForm } from './_change-request-form';
import jsonpatch from 'fast-json-patch';
import { useUpdateChangeRequest } from '../../../../hooks/change-requests';
import { useRouter } from 'next/router';

const ChangeRequestEditPage = ({
FDK_REGISTRATION_BASE_URI,
Expand All @@ -15,19 +22,37 @@ const ChangeRequestEditPage = ({
originalConcept,
showOriginal,
}) => {
const router = useRouter();
const changeRequestMutateHook = useUpdateChangeRequest({
catalogId: organization,
catalogId: organization.organizationId,
changeRequestId: changeRequest.id,
});

const submitHandler = (values: Concept) => {
const changeRequestFromConcept: ChangeRequestUpdateBody = {
conceptId: changeRequest.conceptId,
operations: jsonpatch.compare(originalConcept, values) as JsonPatchOperation[],
title: '',
};
changeRequestMutateHook
.mutateAsync(changeRequestFromConcept)
.then(() => {
router.reload();
})
.catch((error) => {
alert('Failed to submit change request.');
});
};

return (
<ChangeRequestPage
<ChangeRequestForm
FDK_REGISTRATION_BASE_URI={FDK_REGISTRATION_BASE_URI}
organization={organization}
changeRequest={changeRequest}
changeRequestAsConcept={changeRequestAsConcept}
originalConcept={originalConcept}
showOriginal={showOriginal}
changeRequestMutateHook={changeRequestMutateHook}
submitHandler={submitHandler}
/>
);
};
Expand Down
20 changes: 16 additions & 4 deletions apps/concept-catalog/pages/[catalogId]/change-requests/new.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { getOrganization } from '@catalog-frontend/data-access';
import { Organization, Concept, ChangeRequestUpdateBody } from '@catalog-frontend/types';
import { Organization, Concept, ChangeRequestUpdateBody, JsonPatchOperation } from '@catalog-frontend/types';
import { hasOrganizationReadPermission, validOrganizationNumber } from '@catalog-frontend/utils';
import { authOptions } from '../../api/auth/[...nextauth]';
import { Session, getServerSession } from 'next-auth';
import { ChangeRequestPage } from './[changeRequestId]/_change-request-form';
import { ChangeRequestForm } from './[changeRequestId]/_change-request-form';
import jsonpatch from 'fast-json-patch';
import { useCreateChangeRequest } from '../../../hooks/change-requests';

Expand All @@ -16,15 +16,27 @@ const NewConceptSuggestion = ({
showOriginal,
}) => {
const changeRequestMutateHook = useCreateChangeRequest({ catalogId: organization.organizationId });

const submitHandler = (values: Concept) => {
const changeRequestFromConcept: ChangeRequestUpdateBody = {
conceptId: changeRequest.conceptId,
operations: jsonpatch.compare(originalConcept, values) as JsonPatchOperation[],
title: '',
};
changeRequestMutateHook.mutateAsync(changeRequestFromConcept).catch((error) => {
alert('Failed to submit change request.');
});
};

return (
<ChangeRequestPage
<ChangeRequestForm
FDK_REGISTRATION_BASE_URI={FDK_REGISTRATION_BASE_URI}
organization={organization}
changeRequest={changeRequest}
changeRequestAsConcept={changeRequestAsConcept}
originalConcept={originalConcept}
showOriginal={showOriginal}
changeRequestMutateHook={changeRequestMutateHook}
submitHandler={submitHandler}
/>
);
};
Expand Down
21 changes: 17 additions & 4 deletions apps/concept-catalog/pages/api/change-requests/[...slug].ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createChangeRequest, getChangeRequests } from '@catalog-frontend/data-access';
import { createChangeRequest, getChangeRequests, updateChangeRequest } from '@catalog-frontend/data-access';
import { NextApiRequest, NextApiResponse } from 'next';
import { getServerSession } from 'next-auth';
import { authOptions } from '../auth/[...nextauth]';
Expand All @@ -12,7 +12,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
res.status(200);

const { slug } = req.query;
const [catalogId, postType] = slug;
const [catalogId, postType, changeRequestId] = slug;

if (req.method == 'GET') {
try {
Expand All @@ -29,15 +29,28 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
try {
const response = await createChangeRequest(req.body, `${catalogId}`, `${session?.accessToken}`);
if (response.status !== 201) {
return res.status(response.status).send({ error: 'Failed to create change requests' });
return res.status(response.status).send({ error: 'Failed to create change request' });
}
const changeRequestId = response?.headers?.get('location').split('/').pop();
res.status(200).send({ changeRequestId });
} catch (error) {
res.status(500).send({ error: 'Failed to create change request' });
}
} else if (req.method == 'POST' && postType == 'updateChangeRequest') {
return res.status(404).send('Not implemented');
try {
const response = await updateChangeRequest(
req.body,
`${catalogId}`,
`${changeRequestId}`,
`${session?.accessToken}`,
);
if (response.status !== 200) {
res.status(response.status).send({ error: 'Failed to update change request' });
}
} catch (error) {
res.status(500).send({ error: 'Failed to update change request' });
}
res.send(200);
} else {
return res.status(400).send('');
}
Expand Down
18 changes: 18 additions & 0 deletions libs/data-access/src/lib/change-requests/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,21 @@ export const createChangeRequest = async (body: any, catalogId: string, accessTo
};
return await fetch(resource, options);
};

export const updateChangeRequest = async (
body: any,
catalogId: string,
changeRequestId: string,
accessToken: string,
) => {
const resource = `${path}/${catalogId}/endringsforslag/${changeRequestId}`;
const options = {
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
method: 'POST',
body: body,
};
return await fetch(resource, options);
};

0 comments on commit 92a7a5f

Please sign in to comment.