Skip to content

Commit

Permalink
fix(Code): linter for package
Browse files Browse the repository at this point in the history
  • Loading branch information
duonglq-tsdv committed Oct 15, 2024
1 parent ed9bba0 commit d14af03
Show file tree
Hide file tree
Showing 12 changed files with 254 additions and 155 deletions.
39 changes: 26 additions & 13 deletions src/app/[locale]/packages/add/components/CreatePackage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,17 @@

'use client'

import { useState } from 'react'
import { useState, ReactNode } from 'react'
import { Package, HttpStatus } from "@/object-types"
import CreateOrEditPackage from '../../components/CreateOrEditPackage'
import { Tab, ListGroup } from 'react-bootstrap'
import { useTranslations } from 'next-intl'
import { getSession, signOut } from 'next-auth/react'
import { ApiUtils } from '@/utils'
import { ApiUtils, CommonUtils } from '@/utils'
import MessageService from '@/services/message.service'
import { useRouter } from 'next/navigation'

export default function CreatePackage() {
export default function CreatePackage() : ReactNode {

const t = useTranslations('default')
const router = useRouter()
Expand All @@ -33,18 +33,19 @@ export default function CreatePackage() {
try {
setCreatingPackage(true)
const session = await getSession()
if (CommonUtils.isNullOrUndefined(session)) return
const response = await ApiUtils.POST('packages', {
...packagePayload,
createdBy: session.user.email,
packageManager: packagePayload.purl.substring(4, packagePayload.purl.indexOf('/')).toUpperCase()
packageManager: packagePayload.purl?.substring(4, packagePayload.purl.indexOf('/')).toUpperCase()
}, session.user.access_token)
if (response.status == HttpStatus.CREATED) {
MessageService.success(t('Package created successfully'))
router.push('/packages')
} else if (response.status === HttpStatus.UNAUTHORIZED) {
signOut()
await signOut()
} else {
const res = await response.json()
const res = await response.json() as Record<string, string>
MessageService.error(`${t('Something went wrong')}: ${res.message}`)
}
} catch (e) {
Expand All @@ -56,20 +57,32 @@ export default function CreatePackage() {

return (
<>
<Tab.Container defaultActiveKey='summary' mountOnEnter={true} unmountOnExit={true}>
<div className="row mx-2 mt-3">
<div className="col-lg-2">
<Tab.Container
defaultActiveKey='summary'
mountOnEnter={true}
unmountOnExit={true}
>
<div className='row mx-2 mt-3'>
<div className='col-lg-2'>
<ListGroup>
<ListGroup.Item action eventKey='summary'>
<ListGroup.Item
action
eventKey='summary'
>
<div className='my-2'>{t('Summary')}</div>
</ListGroup.Item>
</ListGroup>
</div>
<div className="col ms-2 me-4 mt-2">
<div className='col ms-2 me-4 mt-2'>
<Tab.Content>
<Tab.Pane eventKey='summary'>
<CreateOrEditPackage packagePayload={packagePayload} setPackagePayload={setPackagePayload}
handleSubmit={handleCreatePackage} isPending={creatingPackage} isEditPage={false} />
<CreateOrEditPackage
packagePayload={packagePayload}
setPackagePayload={setPackagePayload}
handleSubmit={() => {handleCreatePackage().catch((e) => console.error(e))}}
isPending={creatingPackage}
isEditPage={false}
/>
</Tab.Pane>
</Tab.Content>
</div>
Expand Down
3 changes: 2 additions & 1 deletion src/app/[locale]/packages/add/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@
import { Metadata } from 'next'

import CreatePackage from './components/CreatePackage'
import { ReactNode } from 'react'

export const metadata: Metadata = {
title: 'Packages',
}

async function PackagesList() {
function PackagesList() : ReactNode {
return <CreatePackage />
}

Expand Down
172 changes: 122 additions & 50 deletions src/app/[locale]/packages/components/CreateOrEditPackage.tsx

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions src/app/[locale]/packages/components/DeletePackageModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

'use client'

import { useState } from 'react'
import { ReactNode, useState } from 'react'
import { Dispatch, SetStateAction } from 'react'
import { HttpStatus } from '@/object-types'
import { getSession, signOut } from 'next-auth/react'
Expand All @@ -34,7 +34,7 @@ interface AlertData {
}

export default function DeletePackageModal({ modalMetaData, setModalMetaData, isEditPage }:
{ modalMetaData: DeletePackageModalMetData, setModalMetaData: Dispatch<SetStateAction<DeletePackageModalMetData>>, isEditPage: boolean }) {
{ modalMetaData: DeletePackageModalMetData, setModalMetaData: Dispatch<SetStateAction<DeletePackageModalMetData>>, isEditPage: boolean }) : ReactNode {
const t = useTranslations('default')
const [alert, setAlert] = useState<AlertData | null>(null)
const [deleting, setDeleting] = useState<boolean | null>(null)
Expand Down Expand Up @@ -66,7 +66,7 @@ export default function DeletePackageModal({ modalMetaData, setModalMetaData, is
})
}
} else if (response.status == HttpStatus.UNAUTHORIZED) {
signOut()
await signOut()
} else {
if(isEditPage) {
MessageService.error(t('Package cannot be deleted'))
Expand Down Expand Up @@ -99,7 +99,7 @@ export default function DeletePackageModal({ modalMetaData, setModalMetaData, is
centered
show={modalMetaData.show}
onHide={() => {
if (!deleting) {
if (deleting !== null) {
setModalMetaData({ show: false, packageId: modalMetaData.packageId, packageName: '', packageVersion: '' })
}
}}
Expand All @@ -126,19 +126,19 @@ export default function DeletePackageModal({ modalMetaData, setModalMetaData, is
<button
className='btn btn-dark'
onClick={() => setModalMetaData({ show: false, packageId: '', packageName: '', packageVersion: '' })}
disabled={deleting}
disabled={deleting ?? undefined}
>
{t('Cancel')}
</button>
<button
className='btn btn-danger'
onClick={async () => {
await deletePackage()
onClick={() => {
deletePackage().catch((e) => console.error(e))
}}
disabled={deleting}
disabled={deleting ?? undefined}
>
{t('Delete Package')}
{deleting && <Spinner size='sm' className='ms-1 spinner' />}
{deleting === true && <Spinner size='sm' className='ms-1 spinner' />}
</button>
</>:
<button
Expand Down
74 changes: 40 additions & 34 deletions src/app/[locale]/packages/components/Packages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@

'use client'

import { useEffect, useState } from 'react'
import { Embedded, Package, Session } from '@/object-types'
import { useEffect, useState, ReactNode } from 'react'
import { Embedded, Package } from '@/object-types'
import { CommonUtils } from '@/utils'
import { SW360_API_URL } from '@/utils/env'
import { useSession } from 'next-auth/react'
import { useSession, signOut } from 'next-auth/react'
import { useTranslations } from 'next-intl'
import { AdvancedSearch, Table, _ } from 'next-sw360'
import Link from 'next/link'
Expand All @@ -22,6 +22,7 @@ import { OverlayTrigger, Spinner, Tooltip } from 'react-bootstrap'
import { FaPencilAlt, FaTrashAlt } from 'react-icons/fa'
import DeletePackageModal from './DeletePackageModal'
import { packageManagers } from "./PackageManagers"
import { ServerStorageOptions } from 'gridjs/dist/src/storage/server'

type EmbeddedPackages = Embedded<Package, 'sw360:packages'>

Expand All @@ -32,7 +33,7 @@ interface DeletePackageModalMetData {
packageVersion: string
}

export default function Packages() {
export default function Packages() : ReactNode {
const { data: session, status } = useSession()
const t = useTranslations('default')
const params = useSearchParams()
Expand Down Expand Up @@ -111,13 +112,14 @@ export default function Packages() {
},
]

const initServerPaginationConfig = (session: Session) => {
const initServerPaginationConfig = () => {
if (CommonUtils.isNullOrUndefined(session)) return
return {
url: CommonUtils.createUrlWithParams(`${SW360_API_URL}/resource/api/packages`, Object.fromEntries(params)),
then: (data: EmbeddedPackages) => {
return data._embedded['sw360:packages'].map((elem: Package) => [
{
id: elem['_links']['self']['href'].split('/').at(-1),
id: elem._links?.self.href.split('/').at(-1) ?? '',
name: elem.name ?? '',
version: elem.version ?? ''
},
Expand All @@ -126,13 +128,13 @@ export default function Packages() {
'',
elem.packageManager ?? '',
{
id: elem['_links']['self']['href'].split('/').at(-1),
id: elem._links?.self.href.split('/').at(-1) ?? '',
name: elem.name ?? '',
version: elem.version ?? ''
},
])
},
total: (data: EmbeddedPackages) => data.page.totalElements,
total: (data: EmbeddedPackages) => data.page?.totalElements,
headers: { Authorization: `${session.user.access_token}` },
}
}
Expand Down Expand Up @@ -165,33 +167,37 @@ export default function Packages() {
}
]

return (
<>
<DeletePackageModal modalMetaData={deletePackageModalMetaData} setModalMetaData={setDeletePackageModalMetaData} isEditPage={false}/>
<div className='container page-content'>
<div className='row'>
<div className='col-2'>
<AdvancedSearch title='Advanced Search' fields={advancedSearch} />
</div>
<div className='col-10'>
<div className='row'>
<div className='col d-flex justify-content-between'>
<button className='btn btn-primary col-auto' onClick={handleCreatePackage}>
{t('Add Package')}
</button>
<div className='col-auto buttonheader-title'>{t('PACKAGES')}</div>
</div>
if (status === 'unauthenticated') {
return signOut()
} else {
return (
<>
<DeletePackageModal modalMetaData={deletePackageModalMetaData} setModalMetaData={setDeletePackageModalMetaData} isEditPage={false}/>
<div className='container page-content'>
<div className='row'>
<div className='col-2'>
<AdvancedSearch title='Advanced Search' fields={advancedSearch} />
</div>
{
status === 'authenticated' ?
<Table columns={columns} server={initServerPaginationConfig(session)} selector={true} sort={false} /> :
<div className='col-12 d-flex justify-content-center align-items-center'>
<Spinner className='spinner' />
<div className='col-10'>
<div className='row'>
<div className='col d-flex justify-content-between'>
<button className='btn btn-primary col-auto' onClick={handleCreatePackage}>
{t('Add Package')}
</button>
<div className='col-auto buttonheader-title'>{t('PACKAGES')}</div>
</div>
</div>
}
{
status === 'authenticated' ?
<Table columns={columns} server={initServerPaginationConfig() as ServerStorageOptions} selector={true} sort={false} /> :
<div className='col-12 d-flex justify-content-center align-items-center'>
<Spinner className='spinner' />
</div>
}
</div>
</div>
</div>
</div>
</>
)
}
</>
)
}
}
26 changes: 15 additions & 11 deletions src/app/[locale]/packages/detail/[id]/components/Changelog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,20 @@
import { signOut, useSession } from 'next-auth/react'
import { useTranslations } from 'next-intl'
import { notFound } from 'next/navigation'
import { useEffect, useState } from 'react'
import { ReactNode, useEffect, useState } from 'react'
import { Nav, Tab } from 'react-bootstrap'
import { HttpStatus, Changelogs } from '@/object-types'
import ChangeLogDetail from '@/components/ChangeLog/ChangeLogDetail/ChangeLogDetail'
import ChangeLogList from '@/components/ChangeLog/ChangeLogList/ChangeLogList'
import { ApiUtils, CommonUtils } from '@/utils'
import { ApiUtils } from '@/utils'

function ChangeLog({ packageId }: { packageId: string }) {
interface PackageChangelogs {
_embedded: {
"sw360:changeLogs": Array<Changelogs>
}
}

function ChangeLog({ packageId }: { packageId: string }) : ReactNode {
const t = useTranslations('default')
const { data: session, status } = useSession()
const [key, setKey] = useState('list-change')
Expand All @@ -32,7 +38,7 @@ function ChangeLog({ packageId }: { packageId: string }) {
const controller = new AbortController()
const signal = controller.signal

;(async () => {
void (async () => {
try {
const response = await ApiUtils.GET(
`changelog/document/${packageId}`,
Expand All @@ -44,13 +50,11 @@ function ChangeLog({ packageId }: { packageId: string }) {
} else if (response.status !== HttpStatus.OK) {
return notFound()
}

const data = await response.json()

const data = await response.json() as PackageChangelogs
setChangeLogList(
CommonUtils.isNullOrUndefined(data['_embedded']['sw360:changeLogs'])
? []
: data['_embedded']['sw360:changeLogs']
data['_embedded']['sw360:changeLogs']
)
} catch (e) {
console.error(e)
Expand All @@ -62,7 +66,7 @@ function ChangeLog({ packageId }: { packageId: string }) {

return (
<>
<Tab.Container id='views-tab' activeKey={key} onSelect={(k) => setKey(k)}>
<Tab.Container id='views-tab' activeKey={key} onSelect={(k) => setKey(k ?? '')}>
<div className='row'>
<div className='col ps-0'>
<Nav variant='pills' className='d-inline-flex'>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,17 @@
'use client'

import { HttpStatus, Package } from '@/object-types'
import { ApiUtils } from '@/utils'
import { ApiUtils, CommonUtils } from '@/utils'
import { signOut, useSession } from 'next-auth/react'
import { useTranslations } from 'next-intl'
import { notFound, useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import { useEffect, useState, ReactNode } from 'react'
import { ListGroup, Spinner, Tab } from 'react-bootstrap'
import MessageService from '@/services/message.service'
import Summary from './Summary'
import ChangeLog from './Changelog'

export default function PackageDetailTab({ packageId }: { packageId: string }) {
export default function PackageDetailTab({ packageId }: { packageId: string }) : ReactNode {
const t = useTranslations('default')
const { data: session, status } = useSession()
const [summaryData, setSummaryData] = useState<Package | undefined>(undefined)
Expand All @@ -32,7 +32,7 @@ export default function PackageDetailTab({ packageId }: { packageId: string }) {
const controller = new AbortController()
const signal = controller.signal

;(async () => {
void (async () => {
try {
const response = await ApiUtils.GET(
`packages/${packageId}`,
Expand All @@ -45,7 +45,7 @@ export default function PackageDetailTab({ packageId }: { packageId: string }) {
return notFound()
}

const data = await response.json()
const data = await response.json() as Package

setSummaryData({ id: packageId, ...data })
} catch (e) {
Expand All @@ -57,7 +57,8 @@ export default function PackageDetailTab({ packageId }: { packageId: string }) {
}, [packageId, session, status])

const handleEditPackage = () => {
if (session.user.email === summaryData['_embedded']['createdBy']['email']){
if (CommonUtils.isNullOrUndefined(session)) return
if (session.user.email === summaryData?._embedded?.createdBy?.email){
MessageService.success(t('You are editing the original document'))
router.push(`/packages/edit/${packageId}`)
}
Expand Down
Loading

0 comments on commit d14af03

Please sign in to comment.