You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.4 KiB
JavaScript

import React, {useState} from 'react'
import router from 'next/router'
import Link from 'next/link'
import {DateTime} from 'luxon'
import {Icon} from '@rmwc/icon'
import axios from 'axios'
import useUser, {useSetUser} from '~/hooks/useUser'
import AdminToolbar from '~/components/admin/actionBar'
import Table from '~/components/table'
UsersTable.getInitialProps = async ({ctx: {axios}}) => {
const {data: users} = await axios.get(`/api/users`)
return {users}
}
export default function UsersTable({users: _users}) {
const currentUser = useUser()
const setCurrentUser = useSetUser()
const [users, setUsers] = useState(_users)
const promoteAdmin = uuid => async ev => {
if(ev) ev.preventDefault()
if(!window.confirm(`Are you sure you want to make this user an admin?`))
return
const {data: user} = await axios.put(`/api/users/${uuid}/admin`)
if(user.uuid === currentUser.uuid)
setCurrentUser(user)
setUsers(users.map(u => u.uuid === uuid ? user : u))
}
const demoteAdmin = uuid => async ev => {
if(ev) ev.preventDefault()
if(!window.confirm(`Are you sure you want to demote this user?`))
return
const {data: user} = await axios.delete(`/api/users/${uuid}/admin`)
if(user.uuid === currentUser.uuid){
setCurrentUser(user)
router.push('/')
}
setUsers(users.map(u => u.uuid === uuid ? user : u))
}
return (
<>
<AdminToolbar title="Users"/>
<Table
columns={[
{name: 'Email', extractor: user => user.email},
{name: 'Orders', extractor: user => user.num_orders},
{name: 'Registered', extractor: user => DateTime.fromISO(user.time_registered).setZone('local').toFormat('LLL dd')},
{name: 'Email Confirmed', extractor: user => user.email_confirmed ? <Icon icon="check"/> : <Icon icon="cancel"/>},
{name: 'Admin', extractor: user => user.is_admin ? <Icon icon="check"/> : <Icon icon="cancel"/>},
{name: 'Actions', extractor: user => (
<span>
<Link href={`/admin/users/${user.uuid}`}><a>Details</a></Link>
{user.is_admin
? <button onClick={demoteAdmin(user.uuid)} type="button" className="buttonLink">Remove Admin</button>
: <button onClick={promoteAdmin(user.uuid)} type="button" className="buttonLink">Make Admin</button>
}
</span>
)}
]}
rows={users}
/>
</>
)
}