Skip to content

Commit

Permalink
Merge pull request #629 from alan-turing-institute/627-reviewer-comments
Browse files Browse the repository at this point in the history
627 reviewer comments
  • Loading branch information
RichGriff authored Oct 1, 2024
2 parents 01a8a0f + d9e4d25 commit f09b173
Show file tree
Hide file tree
Showing 8 changed files with 153 additions and 224 deletions.
125 changes: 4 additions & 121 deletions next_frontend/app/(main)/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -1,125 +1,8 @@
// 'use client'

// import CaseList from '@/components/cases/CaseList'
// import NoCasesFound from '@/components/cases/NoCasesFound'
// import { unauthorized, useLoginToken } from '@/hooks/useAuth'
// import { useEmailModal } from '@/hooks/useEmailModal'
// import { Loader2 } from 'lucide-react'
// import { useSession } from 'next-auth/react'
// import { useRouter } from 'next/navigation'
// import React, { useEffect, useState } from 'react'

// const Dashboard = () => {
// const [assuranceCases, setAssuranceCases] = useState([])
// const [loading, setLoading] = useState(true)
// const [tokenChecked, setTokenChecked] = useState(false) // New state to ensure token check is complete
// const [currentUser, setCurrentUser] = useState<any>(null)

// const [token] = useLoginToken();
// const router = useRouter()
// const { data } = useSession()
// const emailModal = useEmailModal();

// const fetchAssuranceCases = async (token: any) => {
// try {
// const myHeaders = new Headers();
// myHeaders.append("Content-Type", "application/json");
// myHeaders.append("Authorization", `Token ${token}`);

// const requestOptions: RequestInit = {
// method: 'GET',
// headers: myHeaders,
// redirect: 'follow'
// };

// const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL ?? process.env.NEXT_PUBLIC_API_URL_STAGING}/api/cases?owner=true&view=false&edit=false&review=false`, requestOptions)

// if(response.status === 401) {
// console.log('Invalid Token')
// localStorage.removeItem('token')
// router.push('login')
// return;
// }

// const result = await response.json();
// return result;
// } catch (error) {
// console.error("Failed to fetch assurance cases:", error);
// router.push('login');
// }
// }

// const fetchCurrentUser = async () => {
// const requestOptions: RequestInit = {
// headers: {
// Authorization: `Token ${token}`,
// },
// };

// const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL ?? process.env.NEXT_PUBLIC_API_URL_STAGING}/api/user/`, requestOptions);

// if(response.status === 404 || response.status === 403 ) {
// // TODO: 404 NOT FOUND PAGE
// console.log('Render Not Found Page')
// return
// }

// if(response.status === 401) return unauthorized()

// const result = await response.json()
// return result
// }

// useEffect(() => {
// const storedToken = token || localStorage.getItem('token');

// if(storedToken) {
// fetchAssuranceCases(storedToken).then(result => {
// setAssuranceCases(result)
// setLoading(false)
// })
// } else {
// if (tokenChecked) {
// router.push('login');
// }
// }

// // Set token check to complete
// setTokenChecked(true);
// }, [token, router, tokenChecked])

// useEffect(() => {
// fetchCurrentUser().then(result => {
// setCurrentUser(result)
// if(!result.email) emailModal.onOpen()
// })
// },[])

// return (
// <>
// {loading ? (
// <div className='flex justify-center items-center min-h-screen'>
// <div className='flex flex-col justify-center items-center gap-2'>
// <Loader2 className='w-10 h-10 mt-8 animate-spin' />
// <p className='text-muted-foreground'>Fetching cases...</p>
// </div>
// </div>
// ) : (
// <>
// {assuranceCases.length === 0 ? <NoCasesFound message={'Get started by creating your own assurance case.'} /> : <CaseList assuranceCases={assuranceCases} showCreate />}
// </>
// )}
// </>
// )
// }

// export default Dashboard


'use client'

import CaseList from '@/components/cases/CaseList'
import NoCasesFound from '@/components/cases/NoCasesFound'
import useStore from '@/data/store'
import { unauthorized, useLoginToken } from '@/hooks/useAuth'
import { useEmailModal } from '@/hooks/useEmailModal'
import { Loader2 } from 'lucide-react'
Expand Down Expand Up @@ -178,7 +61,7 @@ const Dashboard = () => {
},
}

const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL ?? process.env.NEXT_PUBLIC_API_URL_STAGING}/api/user/`, requestOptions)
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/user/`, requestOptions)

if (response.status === 404 || response.status === 403) {
console.log('Render Not Found Page')
Expand Down Expand Up @@ -221,12 +104,12 @@ const Dashboard = () => {
}, [token, status, router, tokenChecked])

useEffect(() => {
if (status === 'authenticated' && tokenLoaded) {
// if (status === 'authenticated' && tokenLoaded) {
fetchCurrentUser().then((result) => {
setCurrentUser(result)
if (!result?.email) emailModal.onOpen()
})
}
// }
}, [status, tokenLoaded])

return (
Expand Down
1 change: 1 addition & 0 deletions next_frontend/components/cases/CaseList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { useCreateCaseModal } from '@/hooks/useCreateCaseModal'
import { useImportModal } from '@/hooks/useImportModal'
import { useShareModal } from '@/hooks/useShareModal'
import { Input } from '../ui/input'
import useStore from '@/data/store'

interface CaseListProps {
assuranceCases: any[]
Expand Down
42 changes: 28 additions & 14 deletions next_frontend/components/cases/CommentsFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { PencilLine,Trash2, User2Icon } from 'lucide-react'
import moment from 'moment'
import useStore from '@/data/store'
import { Button } from '../ui/button'
import { useLoginToken } from '@/hooks/useAuth'
import { unauthorized, useLoginToken } from '@/hooks/useAuth'
import CommentsEditForm from './CommentsEditForm'
import { useToast } from '../ui/use-toast'

Expand All @@ -18,10 +18,9 @@ export default function CommentsFeed({ node }: CommentsFeedProps) {
const [token] = useLoginToken();
const [edit, setEdit] = useState<boolean>(false)
const [editId, setEditId] = useState<number>()
const [user, setUser] = useState<any>()
const { toast } = useToast();

console.log(nodeComments.map(item => item.id))

const handleNoteDelete = async (id: number) => {
try {
let url = `${process.env.NEXT_PUBLIC_API_URL}/api/comments/${id}/`
Expand Down Expand Up @@ -55,18 +54,33 @@ export default function CommentsFeed({ node }: CommentsFeedProps) {
}
}

// const comments = [
// { id: 1, comment: 'Lorem ipsum odor amet, consectetuer adipiscing elit. Tellus neque venenatis; maximus ultricies augue potenti. Est eu posuere metus diam purus facilisi.', user: { name: 'Rich' }, createdOn: new Date() },
// { id: 2, comment: 'Lorem ipsum odor amet, consectetuer adipiscing elit. Tellus neque venenatis; maximus ultricies augue potenti. Est eu posuere metus diam purus facilisi. Lorem ipsum odor amet, consectetuer adipiscing elit. Tellus neque venenatis; maximus ultricies augue potenti. Est eu posuere metus diam purus facilisi.', user: { name: 'Rich' }, createdOn: new Date() },
// { id: 3, comment: 'Testing comment', user: { name: 'Rich' }, createdOn: new Date() },
// { id: 4, comment: 'Lorem ipsum odor amet, consectetuer adipiscing elit. Tellus neque venenatis; maximus ultricies augue potenti. Est eu posuere metus diam purus facilisi.', user: { name: 'Rich' }, createdOn: new Date() },
// { id: 5, comment: 'Testing comment', user: { name: 'Rich' }, createdOn: new Date() },
// { id: 6, comment: 'Lorem ipsum odor amet, consectetuer adipiscing elit. Tellus neque venenatis; maximus ultricies augue potenti. Est eu posuere metus diam purus facilisi.', user: { name: 'Rich' }, createdOn: new Date() },
// { id: 7, comment: 'Testing comment', user: { name: 'Rich' }, createdOn: new Date() },
// ]

useEffect(() => {},[nodeComments])

const fetchCurrentUser = async () => {
const requestOptions: RequestInit = {
headers: {
Authorization: `Token ${token}`,
},
}

const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/user/`, requestOptions)

if (response.status === 404 || response.status === 403) {
console.log('Render Not Found Page')
return
}

if (response.status === 401) return unauthorized()

const result = await response.json()
return result
}

// Fetch current user
useEffect(() => {
fetchCurrentUser().then(result => setUser(result))
},[user])

return (
<div className="mt-4 py-2 w-full">
{/* <p className='mb-6'>Exisitng comments</p> */}
Expand Down Expand Up @@ -98,7 +112,7 @@ export default function CommentsFeed({ node }: CommentsFeedProps) {
</div>
)}
{!edit && (
assuranceCase.permissions !== 'view' && (
assuranceCase.permissions !== 'view' && user?.username === comment.author && (
<div className='hidden group-hover:block absolute bottom-2 right-2'>
<div className='flex justify-start items-center gap-2'>
<Button
Expand Down
32 changes: 19 additions & 13 deletions next_frontend/components/cases/NotesEditForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
import { Textarea } from '../ui/textarea'
import { useLoginToken } from '@/hooks/useAuth'
import useStore from '@/data/store'
import { useToast } from '../ui/use-toast'

type NotesEditFormProps = {
note: any,
Expand All @@ -29,8 +30,9 @@ const formSchema = z.object({

const NotesEditForm = ({ note, setEdit } : NotesEditFormProps ) => {
const [token] = useLoginToken();
const { assuranceCase, setAssuranceCase } = useStore()
const { assuranceCase, setAssuranceCase, caseNotes, setCaseNotes } = useStore()
const [loading, setLoading] = useState<boolean>(false)
const { toast } = useToast()

const { id, content } = note

Expand All @@ -49,7 +51,7 @@ const NotesEditForm = ({ note, setEdit } : NotesEditFormProps ) => {
}

try {
let url = `${process.env.NEXT_PUBLIC_API_URL ?? process.env.NEXT_PUBLIC_API_URL_STAGING}/api/comments/${id}/`
let url = `${process.env.NEXT_PUBLIC_API_URL}/api/comments/${id}/`

const requestOptions: RequestInit = {
method: "PUT",
Expand All @@ -62,27 +64,31 @@ const NotesEditForm = ({ note, setEdit } : NotesEditFormProps ) => {
const response = await fetch(url, requestOptions);

if(!response.ok) {
console.log('error')
toast({
variant: 'destructive',
title: 'Failed to update comment',
description: 'Something went wrong trying to update the comment.',
});
return
}

const updatedComment = await response.json();

// Find the index of the updated comment in the existing comments array
const updatedComments = assuranceCase.comments.map((comment:any) =>
const updatedComments = caseNotes.map((comment:any) =>
comment.id === updatedComment.id ? updatedComment : comment
);

const updatedAssuranceCase = {
...assuranceCase,
comments: updatedComments,
};

setAssuranceCase(updatedAssuranceCase);
setCaseNotes(updatedComments);
setEdit(false);
setLoading(false)
} catch (error) {
console.log('Error', error)
setLoading(false)
toast({
variant: 'destructive',
title: 'Failed to update comment',
description: 'Something went wrong trying to update the comment.',
});
} finally {
setLoading(false)
}
}

Expand Down
Loading

0 comments on commit f09b173

Please sign in to comment.