Skip to content

Commit

Permalink
refactor(project_details): Remove linting errors in projects details
Browse files Browse the repository at this point in the history
  • Loading branch information
deo002 authored and heliocastro committed Nov 25, 2024
1 parent 0ed3817 commit 9ba5a14
Show file tree
Hide file tree
Showing 29 changed files with 971 additions and 926 deletions.
156 changes: 77 additions & 79 deletions src/app/[locale]/projects/components/DeleteProjectDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,14 @@
'use client'

import { HttpStatus, Project } from '@/object-types'
import { ApiUtils } from '@/utils'
import { signOut, useSession } from 'next-auth/react'
import { ApiUtils, CommonUtils } from '@/utils'
import { signOut, getSession } from 'next-auth/react'
import { useTranslations } from 'next-intl'
import { useRouter } from 'next/navigation'
import { useCallback, useEffect, useState } from 'react'
import { Alert, Button, Form, Modal } from 'react-bootstrap'
import { ChangeEvent, useCallback, useEffect, useState } from 'react'
import { Alert, Button, Form, Modal, Spinner } from 'react-bootstrap'
import { AiOutlineQuestionCircle } from 'react-icons/ai'

const DEFAULT_PROJECT_DATA: Project = {
name: '',
_embedded: {
'sw360:releases': [],
'sw360:projects': [],
'sw360:attachments': [],
'sw360:packages': [],
},
}

interface Data {
attachment?: number
project?: number
Expand All @@ -36,16 +26,15 @@ interface Data {
}

interface Props {
projectId?: string
show?: boolean
setShow?: React.Dispatch<React.SetStateAction<boolean>>
projectId: string
show: boolean
setShow: React.Dispatch<React.SetStateAction<boolean>>
}

function DeleteProjectDialog ({ projectId, show, setShow }: Props) {
const { data: session } = useSession()
function DeleteProjectDialog ({ projectId, show, setShow }: Props): JSX.Element {
const t = useTranslations('default')
const router = useRouter()
const [project, setProject] = useState<Project>(DEFAULT_PROJECT_DATA)
const [project, setProject] = useState<Project>()
const [internalData, setInternalData] = useState<Data>({ attachment: 0, project: 0, release: 0, package: 0 })
const [variant, setVariant] = useState('success')
const [message, setMessage] = useState('')
Expand All @@ -66,11 +55,12 @@ function DeleteProjectDialog ({ projectId, show, setShow }: Props) {
}, [t])

const deleteProject = async () => {
if (CommonUtils.isNullEmptyOrUndefinedString(projectId))
return
const response = await ApiUtils.DELETE(`projects/${projectId}`, session.user.access_token)
try {
if (response.status == HttpStatus.OK) {
const session = await getSession()
if (CommonUtils.isNullOrUndefined(session))
return
const response = await ApiUtils.DELETE(`projects/${projectId}`, session.user.access_token)
if (response.status === HttpStatus.OK) {
displayMessage('success', t('Delete project successful!'))
router.push('/projects')
setReloadPage(true)
Expand All @@ -90,27 +80,25 @@ function DeleteProjectDialog ({ projectId, show, setShow }: Props) {

useEffect(() => {
const fetchData = async (projectId: string) => {
if (CommonUtils.isNullEmptyOrUndefinedString(projectId))
const session = await getSession()
if (CommonUtils.isNullOrUndefined(session))
return
if (session) {
const projectsResponse = await ApiUtils.GET(`projects/${projectId}`, session.user.access_token)
if (projectsResponse.status == HttpStatus.OK) {
const projectData = (await projectsResponse.json()) as Project
setProject(projectData)
handleInternalDataCount(projectData)
} else if (projectsResponse.status == HttpStatus.UNAUTHORIZED) {
await signOut()
} else {
setProject(DEFAULT_PROJECT_DATA)
handleError()
}
const projectsResponse = await ApiUtils.GET(`projects/${projectId}`, session.user.access_token)
if (projectsResponse.status == HttpStatus.OK) {
const projectData = (await projectsResponse.json()) as Project
setProject(projectData)
handleInternalDataCount(projectData)
} else if (projectsResponse.status == HttpStatus.UNAUTHORIZED) {
await signOut()
} else {
handleError()
}
}

fetchData(projectId).catch((err) => {
console.error(err)
})
}, [show, projectId, handleError, session])
}, [show, projectId, handleError])

const handleSubmit = () => {
deleteProject().catch((err) => {
Expand All @@ -130,26 +118,26 @@ function DeleteProjectDialog ({ projectId, show, setShow }: Props) {

const handleInternalDataCount = (projectData: Project) => {
const dataCount: Data = {}
if (projectData._embedded['sw360:attachments']) {
if (projectData._embedded?.['sw360:attachments']) {
dataCount.attachment = projectData._embedded['sw360:attachments'].length
setVisuallyHideLinkedData(false)
}
if (projectData._embedded['sw360:projects']) {
if (projectData._embedded?.['sw360:projects']) {
dataCount.project = projectData._embedded['sw360:projects'].length
setVisuallyHideLinkedData(false)
}
if (projectData._embedded['sw360:releases']) {
if (projectData._embedded?.['sw360:releases']) {
dataCount.release = projectData._embedded['sw360:releases'].length
setVisuallyHideLinkedData(false)
}
if (projectData._embedded['sw360:packages']) {
if (projectData._embedded?.['sw360:packages']) {
dataCount.package = projectData._embedded['sw360:packages'].length
setVisuallyHideLinkedData(false)
}
setInternalData(dataCount)
}

const handleUserComment = (e: any) => {
const handleUserComment = (e: ChangeEvent<HTMLInputElement>) => {
setComment(e.target.value)
}

Expand All @@ -162,42 +150,52 @@ function DeleteProjectDialog ({ projectId, show, setShow }: Props) {
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Alert variant={variant} onClose={() => setShowMessage(false)} dismissible show={showMessage}>
{message}
</Alert>
<Form>
<Form.Group>
<Form.Label className='mb-3'>
{t.rich('Do you really want to delete the project?', {
name: project.name,
strong: (data) => <b>{data}</b>,
})}
</Form.Label>
<br />
<Form.Label className='mb-1' visuallyHidden={visuallyHideLinkedData}>
{t.rich('This project contains', {
name: project.name,
strong: (data) => <b>{data}</b>,
visuallyHideLinkedData,
})}
<ul>
{Object.entries(internalData).map(([key, value]) => (
<li key={key}>{`${value} linked ${key}`}</li>
))}
</ul>
</Form.Label>
</Form.Group>
<hr />
<Form.Group className='mb-3'>
<Form.Label style={{ fontWeight: 'bold' }}>{t('Please comment your changes')}</Form.Label>
<Form.Control
as='textarea'
aria-label='With textarea'
placeholder='Comment your message...'
onChange={handleUserComment}
/>
</Form.Group>
</Form>
<>
{
project === undefined ?
<div className='col-12 mt-1 text-center'>
<Spinner className='spinner' />
</div>:
<>
<Alert variant={variant} onClose={() => setShowMessage(false)} dismissible show={showMessage}>
{message}
</Alert>
<Form>
<Form.Group>
<Form.Label className='mb-3'>
{t.rich('Do you really want to delete the project?', {
name: project.name,
strong: (data) => <b>{data}</b>,
})}
</Form.Label>
<br />
<Form.Label className='mb-1' visuallyHidden={visuallyHideLinkedData}>
{t.rich('This project contains', {
name: project.name,
strong: (data) => <b>{data}</b>,
visuallyHideLinkedData,
})}
<ul>
{Object.entries(internalData).map(([key, value]) => (
<li key={key}>{`${value} linked ${key}`}</li>
))}
</ul>
</Form.Label>
</Form.Group>
<hr />
<Form.Group className='mb-3'>
<Form.Label style={{ fontWeight: 'bold' }}>{t('Please comment your changes')}</Form.Label>
<Form.Control
as='textarea'
aria-label='With textarea'
placeholder='Comment your message...'
onChange={handleUserComment}
/>
</Form.Group>
</Form>
</>
}
</>
</Modal.Body>
<Modal.Footer className='justify-content-end'>
<Button className='delete-btn' variant='light' onClick={handleCloseDialog}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

'use client'

import { signOut, useSession } from 'next-auth/react'
import { getSession, signOut } from 'next-auth/react'
import { useTranslations } from 'next-intl'

import { notFound } from 'next/navigation'
Expand All @@ -18,10 +18,9 @@ import { Alert, Button, Col, Form, Modal, OverlayTrigger, Row, Tooltip } from 'r
import { FaInfoCircle } from 'react-icons/fa'

import { Table, _ } from '@/components/sw360'
import { Embedded, HttpStatus, Project } from '@/object-types'
import { HttpStatus, Project } from '@/object-types'
import { ApiUtils, CommonUtils } from '@/utils'

type EmbeddedProject = Embedded<Project, 'sw360:projects'>
const Capitalize = (text: string) =>
text.split('_').reduce((s, c) => s + ' ' + (c.charAt(0) + c.substring(1).toLocaleLowerCase()), '')

Expand All @@ -38,18 +37,17 @@ export default function CompareObligation({
show: boolean
setShow: (show: boolean) => void
setSelectedProjectId: (id: string | null) => void
}) {
}): JSX.Element {
const t = useTranslations('default')
const { data: session } = useSession()
const [projectData, setProjectData] = useState<any[] | null>(null)
const [compareProject, setCompareProject] = useState<Map<string, any>>(new Map())
const [projectData, setProjectData] = useState<(object | string)[][] | null>(null)
const [compareProject, setCompareProject] = useState<Map<string, object>>(new Map())
const [alert, setAlert] = useState<AlertData | null>(null)
const searchValueRef = useRef<HTMLInputElement>(null)
const topRef = useRef(null)
const [pid, setPid] = useState('')

const scrollToTop = () => {
topRef.current.scrollTo({ top: 0, left: 0 })
(topRef.current as HTMLDivElement | null)?.scrollTo({ top: 0, left: 0 })
}

const columns = [
Expand Down Expand Up @@ -137,8 +135,11 @@ export default function CompareObligation({
},
]

const handleSearch = async ({ searchValue }: { searchValue: string }): Promise<EmbeddedProject> => {
const handleSearch = async ({ searchValue }: { searchValue: string }) => {
try {
const session = await getSession()
if(CommonUtils.isNullOrUndefined(session))
return
const response = await ApiUtils.GET(
`projects?name=${searchValue}&luceneSearch=false`,
session.user.access_token
Expand All @@ -148,21 +149,20 @@ export default function CompareObligation({
} else if (response.status !== HttpStatus.OK) {
return notFound()
}
const data = await response.json()
const dataTableFormat =
CommonUtils.isNullOrUndefined(data['_embedded']) &&
CommonUtils.isNullOrUndefined(data['_embedded']['sw360:projects'])
? []
: data['_embedded']['sw360:projects'].map((elem: Project) => {
return [
elem['_links']['self']['href'].substring(elem['_links']['self']['href'].lastIndexOf('/') + 1),
elem.name,
elem.version,
{ state: elem.state, clearingState: elem.clearingState },
elem.projectResponsible,
elem.description,
];
});
const data = await response.json() as Project
const dataTableFormat: (object | string)[][] =
CommonUtils.isNullOrUndefined(data['_embedded']?.['sw360:projects'])
? []
: data['_embedded']['sw360:projects'].map((elem: Project) => {
return [
elem['_links']['self']['href'].substring(elem['_links']['self']['href'].lastIndexOf('/') + 1),
elem.name,
elem.version ?? '',
{ state: elem.state ?? '', clearingState: elem.clearingState ?? '' },
elem.projectResponsible ?? '',
elem.description ?? '',
];
})
setProjectData(dataTableFormat)
} catch (e) {
console.error(e)
Expand Down Expand Up @@ -230,8 +230,8 @@ export default function CompareObligation({
<Col xs='auto'>
<Button
variant='secondary'
onClick={async () => {
await handleSearch({ searchValue: searchValueRef.current.value })
onClick={() => {
void handleSearch({ searchValue: searchValueRef.current?.value ?? '' })
}}
>
{t('Search')}
Expand All @@ -256,7 +256,7 @@ export default function CompareObligation({
</Button>
<Button
variant='primary'
onClick={async () => {
onClick={() => {
scrollToTop()
setAlert({ variant: 'success', message: <>{t('comparing')}</> })
setSelectedProjectId(pid)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { ActionType, ProjectObligation } from '@/object-types'
import CompareObligation from './CompareObligation'

export default function Obligations({ projectId, actionType, payload, setPayload }:
{ projectId: string, actionType: ActionType, payload?: ProjectObligation, setPayload?: Dispatch<SetStateAction<ProjectObligation>> }) {
{ projectId: string, actionType: ActionType, payload?: ProjectObligation, setPayload?: Dispatch<SetStateAction<ProjectObligation>> }): JSX.Element {
const t = useTranslations('default')
const [key, setKey] = useState('obligations-view')
const [show, setShow] = useState(false)
Expand All @@ -27,7 +27,7 @@ export default function Obligations({ projectId, actionType, payload, setPayload
return (
<>
<CompareObligation show={show} setShow={setShow} setSelectedProjectId={setSelectedProjectId} />
<Tab.Container id='views-tab' activeKey={key} onSelect={(k) => setKey(k)}>
<Tab.Container id='views-tab' activeKey={key} onSelect={(k) => setKey(k as string)}>
<div className='row'>
<div className='col ps-0'>
<Nav variant='pills' className='d-inline-flex'>
Expand Down
Loading

0 comments on commit 9ba5a14

Please sign in to comment.