Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: users management #56

Draft
wants to merge 3 commits into
base: staging
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions app/components/ui/data-table.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import * as reactTable from "@tanstack/react-table"

import { useState } from "react"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "~/components/ui/table"
import { Iconify } from "./iconify"

export type TDataTable<T extends Record<string, unknown>> = {
data: T[]
columns: reactTable.ColumnDef<T>[]
isLoading?: boolean
}

export function DataTable<T extends Record<string, unknown>>(
props: TDataTable<T>,
) {
const [sorting, setSorting] = useState<reactTable.SortingState>([])

const table = reactTable.useReactTable({
data: props.data,
columns: props.columns,
getCoreRowModel: reactTable.getCoreRowModel(),
getSortedRowModel: reactTable.getSortedRowModel(),
state: {
sorting,
},
onSortingChange: setSorting,
})
return (
<Table>
<TableHeader>
{table.getHeaderGroups().map(headerGroup => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map(header => {
return (
<TableHead key={header.id}>
<div
{...{
className: "flex items-start",
onClick: header.column.getToggleSortingHandler(),
}}
>
{header.isPlaceholder
? null
: reactTable.flexRender(
header.column.columnDef.header,
header.getContext(),
)}
{{
asc: (
<Iconify
icon="ph:caret-up"
style={{ marginLeft: "4px" }}
/>
),
desc: (
<Iconify
icon="ph:caret-down"
style={{ marginLeft: "4px" }}
/>
),
}[header.column.getIsSorted() as string] ?? null}
</div>
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map(row => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map(cell => (
<TableCell key={cell.id}>
{reactTable.flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={props.columns.length}
className="h-24 text-center"
>
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
)
}
4 changes: 2 additions & 2 deletions app/components/ui/table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ const TableHead = React.forwardRef<
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
"h-12 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className,
)}
{...props}
Expand All @@ -84,7 +84,7 @@ const TableCell = React.forwardRef<
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
className={cn("p-2 align-middle [&:has([role=checkbox])]:pr-0", className)}
{...props}
/>
))
Expand Down
184 changes: 184 additions & 0 deletions app/routes/admin.users._index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import { parse } from "@conform-to/zod"
import {
json,
type ActionFunctionArgs,
type LoaderFunctionArgs,
type MetaFunction,
} from "@remix-run/node"
import { Link, useLoaderData } from "@remix-run/react"
import type * as reactTable from "@tanstack/react-table"
import { match } from "ts-pattern"
import { FormDelete } from "~/components/shared/form-delete"
import {
PaginationNavigation,
PaginationSearch,
getPaginationConfigs,
getPaginationOptions,
} from "~/components/shared/pagination"
import { AvatarAuto } from "~/components/ui/avatar-auto"
import { ButtonLink } from "~/components/ui/button-link"
import { DataTable } from "~/components/ui/data-table"
import { Iconify } from "~/components/ui/iconify"

import { requireUser } from "~/helpers/auth"
import { prisma } from "~/libs/db.server"
import { schemaGeneralId } from "~/schemas/general"
import { createMeta } from "~/utils/meta"
import { createSitemap } from "~/utils/sitemap"

export const handle = createSitemap()

export const meta: MetaFunction = () =>
createMeta({ title: `Users`, description: `Manage users` })

export const loader = async ({ request }: LoaderFunctionArgs) => {
const config = getPaginationConfigs({ request })
const { userId } = await requireUser(request)

const where = !config.queryParam
? {}
: { fullname: { contains: config.queryParam } }

const [totalItems, users] = await prisma.$transaction([
prisma.post.count(),
prisma.user.findMany({
where,
skip: config.skip,
take: config.limitParam,
orderBy: { updatedAt: "desc" },
include: {
images: { select: { url: true, id: true, altText: true } },
},
}),
])

return json({
userId,
users,
...getPaginationOptions({ request, totalItems }),
})
}

export default function AdminUsersRoute() {
const { users, ...loaderData } = useLoaderData<typeof loader>()

const columns: reactTable.ColumnDef<(typeof users)[0]>[] = [
{
header: "Avatar",
accessorKey: "images",
cell: ({ row }) => {
const images = row.original?.images
return match(images)
.with([], () => (
<Link to={`/${row.original.username}`}>
<AvatarAuto size="sm" user={row.original} />
</Link>
))
.otherwise(() => (
<Link to={`/${row.original.username}`}>
<img
className="rounded-full"
width={30}
alt={images?.at(-1)?.altText as string}
src={images?.at(-1)?.url}
/>
</Link>
))
},
},
{
header: "Username",
accessorKey: "username",
cell: ({ row }) => {
const username = row.original.username
return (
<Link to={`/${username}`}>
<span>{username}</span>
</Link>
)
},
},
{
header: "Fullname",
accessorKey: "fullname",
},

{
header: "Nickname",
accessorKey: "nickname",
},
{
header: "Email",
accessorKey: "email",
},
{
header: "Phone",
accessorKey: "phone",
},

{
header: "Actions",
cell: ({ row }) => {
const id = row.original.id
const name = row.original.fullname
return (
// TODO Make it re-usable
<section className="flex items-center gap-x-2">
<ButtonLink
variant="outline"
size="xs"
to={`/admin/users/edit/${id}`}
>
<Iconify icon="ph:pencil" />
<span>Edit</span>
</ButtonLink>
<FormDelete
action="/admin/users/delete"
intentValue="admin-delete-user-by-id"
itemText={`user ${name}`}
defaultValue={id}
requireUser
/>
<ButtonLink variant="outline" size="xs" to={`/admin/users/${id}`}>
<Iconify icon="ph:arrow-square-out-duotone" />
<span>View</span>
</ButtonLink>
</section>
)
},
},
]

return (
<div className="app-container">
<header className="app-header">
<div>
<h2>Users</h2>
</div>
</header>

<section className="app-section">
<PaginationSearch
itemName="user"
searchPlaceholder="Search users with keyword..."
count={users.length}
{...loaderData}
/>
</section>

<section className="app-section">
<DataTable data={users} columns={columns} />
<PaginationNavigation {...loaderData} />
</section>
</div>
)
}

export const action = async ({ request }: ActionFunctionArgs) => {
const formData = await request.formData()
const submission = parse(formData, { schema: schemaGeneralId })
if (!submission.value || submission.intent !== "submit") {
return json(submission, { status: 400 })
}
return json(submission)
}
44 changes: 0 additions & 44 deletions app/routes/admin.users.tsx

This file was deleted.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
"@remix-run/server-runtime": "^2.4.1",
"@remixicon/react": "4.0.1",
"@tanem/react-nprogress": "^5.0.51",
"@tanstack/react-table": "^8.11.6",
"@tiptap/core": "^2.1.16",
"@tiptap/extension-highlight": "^2.1.16",
"@tiptap/extension-link": "2.1.13",
Expand Down
20 changes: 20 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.