update package
This commit is contained in:
@@ -0,0 +1,269 @@
|
||||
'use client'
|
||||
|
||||
import type { CellContext, ColumnDef } from '@tanstack/react-table'
|
||||
import { useToggle } from 'ahooks'
|
||||
import {
|
||||
EllipsisVerticalIcon,
|
||||
FileBadgeIcon,
|
||||
HelpCircleIcon
|
||||
} from 'lucide-react'
|
||||
import type { ComponentProps } from 'react'
|
||||
|
||||
import { Abbr } from '@repo/ui/components/abbr'
|
||||
import { DataTableColumnHeader } from '@repo/ui/components/data-table'
|
||||
import { Avatar, AvatarFallback } from '@repo/ui/components/ui/avatar'
|
||||
import { Badge } from '@repo/ui/components/ui/badge'
|
||||
import { Button } from '@repo/ui/components/ui/button'
|
||||
import { Checkbox } from '@repo/ui/components/ui/checkbox'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger
|
||||
} from '@repo/ui/components/ui/dropdown-menu'
|
||||
import { Progress } from '@repo/ui/components/ui/progress'
|
||||
import { Spinner } from '@repo/ui/components/ui/spinner'
|
||||
import { cn, initials } from '@repo/ui/lib/utils'
|
||||
|
||||
import { labels, statuses } from './data'
|
||||
|
||||
// This type is used to define the shape of our data.
|
||||
// You can use a Zod schema here if you want.
|
||||
type Course = {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export type Enrollment = {
|
||||
id: string
|
||||
name: string
|
||||
course: Course
|
||||
status: string
|
||||
progress: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
const formatted = new Intl.DateTimeFormat('pt-BR', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})
|
||||
|
||||
export const columns: ColumnDef<Enrollment>[] = [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => (
|
||||
<Checkbox
|
||||
checked={
|
||||
table.getIsAllPageRowsSelected() ||
|
||||
(table.getIsSomePageRowsSelected() && 'indeterminate')
|
||||
}
|
||||
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
|
||||
className="cursor-pointer"
|
||||
aria-label="Selecionar tudo"
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
checked={row.getIsSelected()}
|
||||
disabled={!row.getCanSelect()}
|
||||
onCheckedChange={(value) => row.toggleSelected(!!value)}
|
||||
className="cursor-pointer"
|
||||
aria-label="Selecionar linha"
|
||||
/>
|
||||
)
|
||||
},
|
||||
{
|
||||
accessorKey: 'user',
|
||||
header: 'Colaborador',
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => {
|
||||
const user = row.getValue('user') as { name: string; email: string }
|
||||
|
||||
return (
|
||||
<div className="flex gap-2.5 items-center">
|
||||
<Avatar className="size-10 hidden lg:block">
|
||||
<AvatarFallback>{initials(user.name)}</AvatarFallback>
|
||||
</Avatar>
|
||||
|
||||
<ul>
|
||||
<li className="font-bold">
|
||||
<Abbr>{user.name}</Abbr>
|
||||
</li>
|
||||
<li className="text-muted-foreground text-sm">
|
||||
<Abbr>{user.email}</Abbr>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'course',
|
||||
header: 'Curso',
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => {
|
||||
const { name } = row.getValue('course') as { name: string }
|
||||
|
||||
return <Abbr>{name}</Abbr>
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: 'Status',
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => {
|
||||
const s = row.getValue('status') as string
|
||||
const status = labels[s] ?? s
|
||||
const { icon: Icon, color } = statuses?.[s] ?? { icon: HelpCircleIcon }
|
||||
|
||||
return (
|
||||
<Badge variant="outline" className={cn(color, ' px-1.5')}>
|
||||
<Icon className={cn('stroke-2', color)} />
|
||||
{status}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'progress',
|
||||
header: 'Progresso',
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => {
|
||||
const progress = row.getValue('progress')
|
||||
|
||||
return (
|
||||
<div className="flex gap-2.5 items-center ">
|
||||
<Progress value={Number(progress)} className="w-32" />
|
||||
<span className="text-xs">{String(progress)}%</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: 'created_at',
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} />,
|
||||
meta: { title: 'Cadastrado em' },
|
||||
enableSorting: true,
|
||||
enableHiding: true,
|
||||
cell: cellDate
|
||||
},
|
||||
{
|
||||
accessorKey: 'started_at',
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} />,
|
||||
meta: { title: 'Iniciado em' },
|
||||
enableSorting: true,
|
||||
enableHiding: true,
|
||||
cell: cellDate
|
||||
},
|
||||
{
|
||||
accessorKey: 'completed_at',
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} />,
|
||||
meta: { title: 'Concluído em' },
|
||||
enableSorting: true,
|
||||
enableHiding: true,
|
||||
cell: cellDate
|
||||
},
|
||||
{
|
||||
accessorKey: 'failed_at',
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} />,
|
||||
meta: { title: 'Reprovado em' },
|
||||
enableSorting: true,
|
||||
enableHiding: true,
|
||||
cell: cellDate
|
||||
},
|
||||
{
|
||||
accessorKey: 'canceled_at',
|
||||
header: ({ column }) => <DataTableColumnHeader column={column} />,
|
||||
meta: { title: 'Cancelado em' },
|
||||
enableSorting: true,
|
||||
enableHiding: true,
|
||||
cell: cellDate
|
||||
},
|
||||
{
|
||||
id: 'actions',
|
||||
cell: ({ row }) => <ActionMenu row={row} />
|
||||
}
|
||||
]
|
||||
|
||||
function cellDate<TData>({
|
||||
row: { original },
|
||||
cell: { column }
|
||||
}: CellContext<TData, unknown>) {
|
||||
const accessorKey = column.columnDef.accessorKey as keyof TData
|
||||
const value = original?.[accessorKey]
|
||||
|
||||
if (value) {
|
||||
return formatted.format(new Date(value as string))
|
||||
}
|
||||
|
||||
return <></>
|
||||
}
|
||||
|
||||
function ActionMenu({ row }: { row: any }) {
|
||||
const [open, { set: setOpen }] = useToggle(false)
|
||||
const cert = row.original?.cert
|
||||
|
||||
return (
|
||||
<div className="flex justify-end items-center">
|
||||
<DropdownMenu
|
||||
modal={false}
|
||||
open={open}
|
||||
onOpenChange={(open) => {
|
||||
setOpen(open)
|
||||
}}
|
||||
>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="data-[state=open]:bg-muted text-muted-foreground cursor-pointer"
|
||||
size="icon-sm"
|
||||
>
|
||||
<EllipsisVerticalIcon />
|
||||
<span className="sr-only">Abrir menu</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-46 *:cursor-pointer">
|
||||
<DownloadItem
|
||||
id={row.id}
|
||||
disabled={!cert}
|
||||
onSuccess={() => setOpen(false)}
|
||||
/>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type ItemProps = ComponentProps<typeof DropdownMenuItem> & {
|
||||
id: string
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
function DownloadItem({ id, onSuccess, ...props }: ItemProps) {
|
||||
const [loading, { set }] = useToggle(false)
|
||||
|
||||
const download = async (e: Event) => {
|
||||
e.preventDefault()
|
||||
set(true)
|
||||
const r = await fetch(`/~/api/enrollments/${id}/download`, {
|
||||
method: 'GET'
|
||||
})
|
||||
|
||||
if (r.ok) {
|
||||
const { presigned_url } = (await r.json()) as { presigned_url: string }
|
||||
window.open(presigned_url, '_blank')
|
||||
|
||||
set(false)
|
||||
onSuccess?.()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenuItem onSelect={download} {...props}>
|
||||
{loading ? <Spinner /> : <FileBadgeIcon />} Baixar certificado
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import {
|
||||
CircleCheckIcon,
|
||||
CircleIcon,
|
||||
CircleOffIcon,
|
||||
CircleXIcon,
|
||||
TimerIcon,
|
||||
type LucideIcon
|
||||
} from 'lucide-react'
|
||||
|
||||
export const statuses: Record<
|
||||
string,
|
||||
{ icon: LucideIcon; color?: string; label: string }
|
||||
> = {
|
||||
PENDING: {
|
||||
icon: CircleIcon,
|
||||
label: 'Não iniciado'
|
||||
},
|
||||
IN_PROGRESS: {
|
||||
icon: TimerIcon,
|
||||
color: 'text-blue-400 [&_svg]:text-blue-500',
|
||||
label: 'Em andamento'
|
||||
},
|
||||
COMPLETED: {
|
||||
icon: CircleCheckIcon,
|
||||
color: 'text-green-400 [&_svg]:text-background [&_svg]:fill-green-500',
|
||||
label: 'Concluído'
|
||||
},
|
||||
FAILED: {
|
||||
icon: CircleXIcon,
|
||||
color: 'text-red-400 [&_svg]:text-red-500',
|
||||
label: 'Reprovado'
|
||||
},
|
||||
CANCELED: {
|
||||
icon: CircleOffIcon,
|
||||
color: 'text-orange-400 [&_svg]:text-orange-500',
|
||||
label: 'Cancelado'
|
||||
}
|
||||
}
|
||||
|
||||
export const labels: Record<string, string> = {
|
||||
PENDING: 'Não iniciado',
|
||||
IN_PROGRESS: 'Em andamento',
|
||||
COMPLETED: 'Concluído',
|
||||
FAILED: 'Reprovado',
|
||||
CANCELED: 'Cancelado'
|
||||
}
|
||||
|
||||
export const sortings: Record<string, string> = {
|
||||
created_at: 'Cadastrado em',
|
||||
started_at: 'Iniciado em',
|
||||
completed_at: 'Concluído em',
|
||||
failed_at: 'Reprovado em',
|
||||
canceled_at: 'Cancelado em'
|
||||
}
|
||||
|
||||
export const headers = {
|
||||
id: 'ID',
|
||||
'user.name': 'Nome',
|
||||
'user.email': 'Email',
|
||||
'user.cpf': 'CPF',
|
||||
'course.name': 'Curso',
|
||||
status: 'Status',
|
||||
progress: 'Progresso',
|
||||
created_at: 'Cadastrado em',
|
||||
started_at: 'Iniciado em',
|
||||
completed_at: 'Concluído em',
|
||||
failed_at: 'Reprovado em',
|
||||
canceled_at: 'Cancelado em'
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
import type { Route } from './+types'
|
||||
|
||||
import { flatten } from 'flat'
|
||||
import {
|
||||
CalendarIcon,
|
||||
ChevronDownIcon,
|
||||
DownloadIcon,
|
||||
FileSpreadsheetIcon,
|
||||
FileTextIcon,
|
||||
PlusCircleIcon,
|
||||
PlusIcon
|
||||
} from 'lucide-react'
|
||||
import { MeiliSearchFilterBuilder } from 'meilisearch-helper'
|
||||
import { Suspense, useState } from 'react'
|
||||
import { Await, Link, Outlet, useParams, useSearchParams } from 'react-router'
|
||||
import type { BookType } from 'xlsx'
|
||||
import * as XLSX from 'xlsx'
|
||||
|
||||
import { DataTable, DataTableViewOptions } from '@repo/ui/components/data-table'
|
||||
import { FacetedFilter } from '@repo/ui/components/faceted-filter'
|
||||
import { RangeCalendarFilter } from '@repo/ui/components/range-calendar-filter'
|
||||
import { SearchForm } from '@repo/ui/components/search-form'
|
||||
import { Skeleton } from '@repo/ui/components/skeleton'
|
||||
import { Button } from '@repo/ui/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger
|
||||
} from '@repo/ui/components/ui/dropdown-menu'
|
||||
import { Kbd } from '@repo/ui/components/ui/kbd'
|
||||
import { createSearch } from '@repo/util/meili'
|
||||
|
||||
import { columns, type Enrollment } from './columns'
|
||||
import { headers, sortings, statuses } from './data'
|
||||
|
||||
export function meta({}: Route.MetaArgs) {
|
||||
return [{ title: 'Matrículas' }]
|
||||
}
|
||||
|
||||
export async function loader({ params, context, request }: Route.LoaderArgs) {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const { orgid } = params
|
||||
const query = searchParams.get('q') || ''
|
||||
const from = searchParams.get('from')
|
||||
const to = searchParams.get('to')
|
||||
const sort = searchParams.get('sort') || 'created_at:desc'
|
||||
const status = searchParams.get('status')
|
||||
const page = Number(searchParams.get('p')) + 1
|
||||
const hitsPerPage = Number(searchParams.get('perPage')) || 25
|
||||
|
||||
let builder = new MeiliSearchFilterBuilder()
|
||||
|
||||
if (status) {
|
||||
builder = builder.where('status', 'in', status.split(','))
|
||||
}
|
||||
|
||||
if (from && to) {
|
||||
const [field, from_] = from.split(':')
|
||||
builder = builder.where(field, 'between', [from_, to])
|
||||
}
|
||||
|
||||
return {
|
||||
data: createSearch({
|
||||
index: 'betaeducacao-prod-enrollments',
|
||||
filter: builder.build(),
|
||||
sort: [sort],
|
||||
query,
|
||||
page,
|
||||
hitsPerPage,
|
||||
env: context.cloudflare.env
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const formatted = new Intl.DateTimeFormat('en-CA', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit'
|
||||
})
|
||||
|
||||
export default function Route({ loaderData: { data } }) {
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const [selectedRows, setSelectedRows] = useState<Enrollment[]>([])
|
||||
const status = searchParams.get('status')
|
||||
const rangeParams = useRangeParams()
|
||||
|
||||
return (
|
||||
<Suspense fallback={<Skeleton />}>
|
||||
<div className="space-y-0.5 mb-8">
|
||||
<h1 className="text-2xl font-bold tracking-tight">
|
||||
Gerenciar matrículas
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Matricule colaboradores de forma rápida e acompanhe seu progresso.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Await resolve={data}>
|
||||
{({ hits, page, hitsPerPage, totalHits }) => (
|
||||
<DataTable
|
||||
sort={[{ id: 'created_at', desc: true }]}
|
||||
columns={columns}
|
||||
data={hits as Enrollment[]}
|
||||
pageIndex={page - 1}
|
||||
pageSize={hitsPerPage}
|
||||
setSelectedRows={setSelectedRows}
|
||||
rowCount={totalHits}
|
||||
columnVisibilityInit={{
|
||||
created_at: true,
|
||||
completed_at: false,
|
||||
started_at: false,
|
||||
failed_at: false,
|
||||
canceled_at: false
|
||||
}}
|
||||
>
|
||||
<div className="flex gap-2.5 mb-2.5">
|
||||
{selectedRows.length ? (
|
||||
<>
|
||||
<div className="flex gap-2.5 items-center">
|
||||
<ExportMenu headers={headers} selectedRows={selectedRows} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="w-full 2xl:w-1/3">
|
||||
<SearchForm
|
||||
defaultValue={searchParams.get('q') || ''}
|
||||
placeholder={
|
||||
<>
|
||||
Digite <Kbd className="border font-mono">/</Kbd> para
|
||||
pesquisar
|
||||
</>
|
||||
}
|
||||
onChange={(value) =>
|
||||
setSearchParams((searchParams) => {
|
||||
searchParams.set('q', String(value))
|
||||
searchParams.delete('p')
|
||||
return searchParams
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2.5 max-lg:flex-col w-full">
|
||||
<div className="flex gap-2.5 max-lg:flex-col">
|
||||
<FacetedFilter
|
||||
title="Status"
|
||||
icon={PlusCircleIcon}
|
||||
className="lg:flex-1"
|
||||
value={status ? status.split(',') : []}
|
||||
onChange={(statuses) => {
|
||||
setSearchParams((searchParams) => {
|
||||
searchParams.delete('status')
|
||||
searchParams.delete('p')
|
||||
|
||||
if (statuses.length) {
|
||||
searchParams.set('status', statuses.join(','))
|
||||
}
|
||||
|
||||
return searchParams
|
||||
})
|
||||
}}
|
||||
options={Object.entries(statuses).map(
|
||||
([key, value]) => ({
|
||||
value: key,
|
||||
...value
|
||||
})
|
||||
)}
|
||||
/>
|
||||
|
||||
<RangeCalendarFilter
|
||||
title="Período"
|
||||
icon={CalendarIcon}
|
||||
value={rangeParams}
|
||||
className="lg:flex-1"
|
||||
options={Object.entries(sortings).map(
|
||||
([value, label]) => ({
|
||||
value,
|
||||
label
|
||||
})
|
||||
)}
|
||||
onChange={(props) => {
|
||||
setSearchParams((searchParams) => {
|
||||
if (!props) {
|
||||
searchParams.delete('from')
|
||||
searchParams.delete('to')
|
||||
return searchParams
|
||||
}
|
||||
|
||||
const { rangeField, dateRange } = props
|
||||
|
||||
searchParams.set(
|
||||
'from',
|
||||
`${rangeField}:${formatted.format(dateRange?.from)}`
|
||||
)
|
||||
searchParams.set(
|
||||
'to',
|
||||
formatted.format(dateRange?.to)
|
||||
)
|
||||
|
||||
return searchParams
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="lg:ml-auto flex gap-2.5">
|
||||
<DataTableViewOptions className="flex-1" />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DataTable>
|
||||
)}
|
||||
</Await>
|
||||
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
||||
function useRangeParams() {
|
||||
const [searchParams] = useSearchParams()
|
||||
const [from, to] = [searchParams.get('from'), searchParams.get('to')]
|
||||
|
||||
if (!from || !to) {
|
||||
return {}
|
||||
}
|
||||
|
||||
const [rangeField, from_] = from.split(':')
|
||||
|
||||
return {
|
||||
rangeField,
|
||||
dateRange: {
|
||||
from: new Date(from_),
|
||||
to: new Date(to)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function ExportMenu({
|
||||
headers,
|
||||
selectedRows = []
|
||||
}: {
|
||||
headers: Record<string, string>
|
||||
selectedRows: object[]
|
||||
}) {
|
||||
const { orgid } = useParams()
|
||||
|
||||
const exportFile = (bookType: BookType) => () => {
|
||||
if (!selectedRows.length) {
|
||||
return
|
||||
}
|
||||
const now = new Date()
|
||||
const header = Object.keys(headers)
|
||||
const data = selectedRows.map((data) => {
|
||||
const obj: Record<string, string> = flatten(data)
|
||||
return Object.fromEntries(header.map((k) => [k, obj?.[k]]))
|
||||
})
|
||||
const workbook = XLSX.utils.book_new()
|
||||
const worksheet = XLSX.utils.json_to_sheet(data, { header })
|
||||
|
||||
XLSX.utils.sheet_add_aoa(worksheet, [Object.values(headers)], {
|
||||
origin: 'A1'
|
||||
})
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
|
||||
XLSX.writeFile(workbook, `${orgid}_users_${+now}.${bookType}`, {
|
||||
bookType,
|
||||
compression: true
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="cursor-pointer">
|
||||
<DownloadIcon /> Baixar <ChevronDownIcon />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-52" align="start">
|
||||
<DropdownMenuGroup className="*:cursor-pointer">
|
||||
<DropdownMenuItem onClick={exportFile('xlsx')}>
|
||||
<FileSpreadsheetIcon /> Microsoft Excel (.xlsx)
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={exportFile('csv')}>
|
||||
<FileTextIcon /> CSV (.csv)
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user