-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathSchemaList.tsx
More file actions
551 lines (498 loc) · 16.3 KB
/
SchemaList.tsx
File metadata and controls
551 lines (498 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
'use client'
import { DidMethod, SchemaTypes } from '@/common/enums'
import { IAttributesDetails, IW3cSchemaDetails, SchemaListItem } from '../type/schemas-interface'
import {
Pagination,
PaginationContent,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from '@/components/ui/pagination'
import React, { ChangeEvent, useEffect, useState } from 'react'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { apiStatusCodes, itemPerPage } from '../../../config/CommonConstant'
import { getAllSchemas, getAllSchemasByOrgId } from '@/app/api/schema'
import { useAppDispatch, useAppSelector } from '@/lib/hooks'
import { AxiosResponse } from 'axios'
import { Button } from '@/components/ui/button'
import { EmptyMessage } from '@/components/EmptyMessage'
import { GetAllSchemaListParameter } from '@/features/dashboard/type/schema'
import { IconSearch } from '@tabler/icons-react'
import { Input } from '@/components/ui/input'
import PageContainer from '@/components/layout/page-container'
import { Plus } from 'lucide-react'
import SchemaCard from './SchemaCard'
import { Skeleton } from '@/components/ui/skeleton'
import { getOrganizationById } from '@/app/api/organization'
import { getUserProfile } from '@/app/api/Auth'
import { useRouter } from 'next/navigation'
export interface ISchemaData {
createDateTime: string
name: string
version: string
attributes: IAttributesDetails[]
schemaLedgerId: string
createdBy: string
publisherDid: string
orgId: string
issuerId: string
organizationName: string
userName: string
}
interface UserOrgRole {
orgId: string
orgRole: {
name: string
}
}
interface GetUserProfileResponse {
data: {
userOrgRoles: UserOrgRole[]
}
}
const SchemaList = (props: {
schemaSelectionCallback?: (
schemaId: string,
schemaDetails: SchemaListItem,
) => void
W3CSchemaSelectionCallback?: (
schemaId: string,
w3cSchemaDetails: IW3cSchemaDetails,
) => void
verificationFlag?: boolean
}): React.ReactElement => {
const verificationFlag = props.verificationFlag ?? false
const organizationId = useAppSelector((state) => state.organization.orgId)
const token = useAppSelector((state) => state.auth.token)
const [schemaList, setSchemaList] = useState<ISchemaData[]>([])
const [, setSchemaListErr] = useState<string | null>('')
const [loading, setLoading] = useState<boolean>(true)
const [allSchemaFlag, setAllSchemaFlag] = useState<boolean>(false)
const [ledger, setLedger] = useState<string>('')
const [schemaType, setSchemaType] = useState('')
const [, setWalletStatus] = useState(false)
const [totalItem, setTotalItem] = useState(0)
const [lastPage, setLastPage] = useState(0)
const [searchValue, setSearchValue] = useState('')
const [, setSelectedValue] = useState<string>('Organizations schema')
const [w3cSchema, setW3CSchema] = useState<boolean>(false)
const [isNoLedger, setIsNoLedger] = useState<boolean>(false)
const [orgRole, setOrgRole] = useState<string | null>(null)
const route = useRouter()
const dispatch = useAppDispatch()
const [schemaListAPIParameter, setSchemaListAPIParameter] = useState({
itemPerPage,
page: 1,
search: '',
sortBy: 'id',
sortingOrder: 'desc',
allSearch: '',
})
const options = ['All schemas']
const optionsWithDefault = ["Organization's schema", ...options]
useEffect(() => {
async function fetchProfile(): Promise<void> {
if (!token || !organizationId) {
return
}
try {
const response = await getUserProfile(token)
// Type narrowing: check if response is a string
if (typeof response === 'string') {
console.error('API error:', response)
setOrgRole(null)
return
}
// Type-cast to expected shape after narrowing
const typedResponse = response as AxiosResponse<GetUserProfileResponse>
const roles = typedResponse?.data?.data?.userOrgRoles ?? []
const matchedRole = roles.find(
(role: UserOrgRole) => role.orgId === organizationId,
)
if (matchedRole?.orgRole?.name) {
setOrgRole(matchedRole.orgRole.name)
} else {
setOrgRole(null)
}
} catch (error) {
console.error('Unexpected fetch error:', error)
setOrgRole(null)
}
}
fetchProfile()
}, [token, organizationId, dispatch])
const getSchemaList = async (
schemaListAPIParameter: GetAllSchemaListParameter,
flag: boolean,
): Promise<void> => {
try {
setLoading(true)
let schemaResponse = undefined
if (flag) {
schemaResponse = await getAllSchemas(
schemaListAPIParameter,
schemaType,
ledger,
)
} else {
schemaResponse = await getAllSchemasByOrgId(
schemaListAPIParameter,
organizationId,
)
}
const { data } = schemaResponse as AxiosResponse
if (data === 'Schema records not found') {
setSchemaList([])
setLoading(false)
return
}
if (data?.statusCode === apiStatusCodes.API_STATUS_SUCCESS) {
const schemaData = data?.data?.data
if (data?.data?.data) {
setLastPage(data?.data?.lastPage - 1)
setTotalItem(data?.data?.totalItems)
setSchemaList([...schemaData])
} else {
setSchemaListErr(schemaResponse as string)
}
} else {
setSchemaListErr(schemaResponse as string)
}
} catch (error) {
console.error('Error while fetching schema list:', error)
} finally {
setLoading(false)
setTimeout(() => setSchemaListErr(''), 3000)
}
}
const fetchOrganizationDetails = async (
organizationId: string,
): Promise<void> => {
setLoading(true)
const response = await getOrganizationById(organizationId)
const { data } = response as AxiosResponse
if (data?.statusCode === apiStatusCodes.API_STATUS_SUCCESS) {
const did = data?.data?.org_agents?.[0]?.orgDid
const ledgerId = data?.data?.org_agents?.[0]?.ledgers?.id ?? ''
setLedger(ledgerId)
if (data?.data?.org_agents && data?.data?.org_agents.length > 0) {
setWalletStatus(true)
}
if (did) {
if (
did.includes(DidMethod.POLYGON) ||
did.includes(DidMethod.KEY) ||
did.includes(DidMethod.WEB)
) {
setW3CSchema(true)
setSchemaType(SchemaTypes.schema_W3C)
}
if (did.includes(DidMethod.INDY)) {
setW3CSchema(false)
setSchemaType(SchemaTypes.schema_INDY)
}
if (did.includes(DidMethod.KEY) || did.includes(DidMethod.WEB)) {
setIsNoLedger(true)
}
}
}
setLoading(false)
}
useEffect(() => {
if (organizationId) {
setLoading(true)
fetchOrganizationDetails(organizationId)
.then(() => {
getSchemaList(schemaListAPIParameter, allSchemaFlag)
})
.finally(() => {
setLoading(false)
})
}
}, [organizationId])
useEffect(() => {
if (organizationId) {
getSchemaList(schemaListAPIParameter, allSchemaFlag)
}
}, [
schemaListAPIParameter.page,
schemaListAPIParameter.allSearch,
schemaListAPIParameter.search,
])
const onSearch = (event: ChangeEvent<HTMLInputElement>): void => {
const inputValue = event.target.value
setSearchValue(inputValue)
const updatedParams = {
...schemaListAPIParameter,
search: allSchemaFlag ? '' : inputValue,
allSearch: allSchemaFlag ? inputValue : '',
}
setSchemaListAPIParameter(updatedParams)
}
const handleFilterChange = async (value: string): Promise<void> => {
const isAllSchemas = value === 'All schemas'
setSelectedValue(value)
setAllSchemaFlag(isAllSchemas)
// Reset pagination and search parameters
setSchemaListAPIParameter({
itemPerPage,
page: 1,
search: '',
sortBy: 'id',
sortingOrder: 'desc',
allSearch: '',
})
setSearchValue('')
if (organizationId) {
setLoading(true)
try {
await getSchemaList(
{
itemPerPage,
page: 1,
search: '',
sortBy: 'id',
allSearch: '',
},
isAllSchemas,
)
} finally {
setLoading(false)
}
}
}
const schemaSelectionCallback = ({
schemaId,
attributes,
issuerDid,
created,
}: {
schemaId: string
attributes: string[]
issuerDid: string
created: string
}): void => {
const schemaDetails = {
attribute: attributes,
issuerDid,
createdDate: created,
}
props.schemaSelectionCallback?.(schemaId, schemaDetails)
}
const W3CSchemaSelectionCallback = ({
schemaId,
schemaName,
version,
issuerDid,
attributes,
created,
}: {
schemaId: string
schemaName: string
version: string
issuerDid: string
attributes: []
created: string
}): void => {
const w3cSchemaDetails = {
schemaId,
schemaName,
version,
issuerDid,
attributes,
created,
}
props.W3CSchemaSelectionCallback?.(schemaId, w3cSchemaDetails)
}
const paginationRange = 2
const currentPage = schemaListAPIParameter.page
const startPage = Math.max(1, currentPage - paginationRange)
const endPage = Math.min(lastPage, currentPage + paginationRange)
const paginationNumbers = []
if (startPage > 1) {
paginationNumbers.push(1)
if (startPage > 2) {
paginationNumbers.push('...')
}
}
for (let i = startPage; i <= endPage; i++) {
paginationNumbers.push(i)
}
if (endPage < lastPage) {
if (endPage < lastPage - 1) {
paginationNumbers.push('...')
}
paginationNumbers.push(lastPage)
}
return (
<PageContainer>
<div className="px-4 pt-2">
<div className="mb-4 grid gap-4 sm:flex sm:flex-wrap sm:items-center sm:justify-between">
<h1 className="mr-auto ml-1 text-xl font-semibold sm:text-2xl">
Schemas
</h1>
<div className="relative w-full sm:max-w-sm">
<Input
type="text"
placeholder="Search..."
value={searchValue}
onChange={onSearch}
className="h-10 rounded-lg pr-4 pl-10"
/>
<IconSearch className="text-muted-foreground absolute top-1/2 left-3 h-5 w-5 -translate-y-1/2" />
</div>
<Select
defaultValue="Organization's schema"
onValueChange={handleFilterChange}
>
<SelectTrigger className="min-h-[42px] w-[230px] rounded-lg border p-2.5 text-sm">
<SelectValue placeholder="Select schema type" />
</SelectTrigger>
<SelectContent>
{optionsWithDefault.map((opt) => (
<SelectItem key={opt} value={opt}>
{opt}
</SelectItem>
))}
</SelectContent>
</Select>
<Button
onClick={() => {
if (orgRole === 'admin' || orgRole === 'owner') {
route.push('/organizations/schemas/create')
}
}}
disabled={orgRole !== 'admin' && orgRole !== 'owner'}
className="w-full sm:w-auto"
>
<Plus /> Create
</Button>
</div>
{loading && (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-2">
{[...Array(4)].map((_, idx) => (
<div key={idx} className="space-y-3 rounded-lg p-4 shadow-sm">
<Skeleton className="h-5 w-1/2 rounded-md" />
<Skeleton className="h-4 w-1/3 rounded" />
<Skeleton className="h-4 w-3/4 rounded" />
<Skeleton className="h-4 w-2/4 rounded" />
<Skeleton className="h-3 w-1/4 rounded" />
</div>
))}
</div>
)}
{!loading && (schemaList.length ? (
<>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-2">
{schemaList.map((element) => (
<div
className="px-0 sm:px-2"
key={`SchemaList-${element?.schemaLedgerId}`}
>
<SchemaCard
schemaName={element?.name}
version={element['version']}
schemaId={element['schemaLedgerId']}
issuerDid={element['issuerId']}
attributes={element['attributes']}
created={element['createDateTime']}
showCheckbox={false}
selectedSchemas={[]}
onClickCallback={schemaSelectionCallback}
onClickW3CCallback={W3CSchemaSelectionCallback}
w3cSchema={w3cSchema}
noLedger={isNoLedger}
isVerification={verificationFlag}
/>
</div>
))}
</div>
{totalItem > itemPerPage &&
(schemaList.length === itemPerPage ||
schemaListAPIParameter.page === lastPage) && (
<div className="mt-6 flex justify-end">
<Pagination className="m-0 w-fit">
<PaginationContent>
{schemaListAPIParameter.page > 1 && (
<PaginationItem>
<PaginationPrevious
href="#"
onClick={() =>
setSchemaListAPIParameter((prev) => ({
...prev,
page: prev.page - 1,
}))
}
/>
</PaginationItem>
)}
{paginationNumbers.map((page, idx) => (
<PaginationItem key={idx}>
{page === '...' ? (
<span className="text-muted-foreground px-3 py-2">
…
</span>
) : (
<PaginationLink
className={`${
page === schemaListAPIParameter.page
? 'bg-primary text-white'
: 'bg-background text-muted-foreground'
} rounded-lg px-4 py-2`}
href="#"
onClick={() =>
setSchemaListAPIParameter((prev) => ({
...prev,
page: page as number,
}))
}
>
{page}
</PaginationLink>
)}
</PaginationItem>
))}
{schemaListAPIParameter.page < lastPage && (
<PaginationItem>
<PaginationNext
href="#"
onClick={() =>
setSchemaListAPIParameter((prev) => ({
...prev,
page: prev.page + 1,
}))
}
/>
</PaginationItem>
)}
</PaginationContent>
</Pagination>
</div>
)}
</>
) : (
<EmptyMessage
title="No Schemas"
description="Get started by creating a new Schema"
buttonContent="Create"
buttonIcon={<Plus className="h-4 w-4" />}
onClick={() => {
if (orgRole === 'admin' || orgRole === 'owner') {
route.push('/organizations/schemas/create')
}
}}
disabled={orgRole !== 'admin' && orgRole !== 'owner'}
/>
))}
</div>
</PageContainer>
)
}
export default SchemaList