feat: add user list sorting and pagination enhancements (#1178)

* feat: add user list sorting and pagination enhancements

* feat: add user list sorting for THEME=air

* feat: add token list sorting and pagination enhancements

* feat: add token list sorting for THEME=air
This commit is contained in:
Benny 2024-03-17 19:25:36 +08:00 committed by GitHub
parent 08831881f1
commit 9821bc7281
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 184 additions and 42 deletions

View File

@ -16,7 +16,10 @@ func GetAllTokens(c *gin.Context) {
if p < 0 { if p < 0 {
p = 0 p = 0
} }
tokens, err := model.GetAllUserTokens(userId, p*config.ItemsPerPage, config.ItemsPerPage)
order := c.Query("order")
tokens, err := model.GetAllUserTokens(userId, p*config.ItemsPerPage, config.ItemsPerPage, order)
if err != nil { if err != nil {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"success": false, "success": false,

View File

@ -180,24 +180,27 @@ func Register(c *gin.Context) {
} }
func GetAllUsers(c *gin.Context) { func GetAllUsers(c *gin.Context) {
p, _ := strconv.Atoi(c.Query("p")) p, _ := strconv.Atoi(c.Query("p"))
if p < 0 { if p < 0 {
p = 0 p = 0
} }
users, err := model.GetAllUsers(p*config.ItemsPerPage, config.ItemsPerPage)
if err != nil { order := c.DefaultQuery("order", "")
c.JSON(http.StatusOK, gin.H{ users, err := model.GetAllUsers(p*config.ItemsPerPage, config.ItemsPerPage, order)
"success": false,
"message": err.Error(), if err != nil {
}) c.JSON(http.StatusOK, gin.H{
return "success": false,
} "message": err.Error(),
c.JSON(http.StatusOK, gin.H{ })
"success": true, return
"message": "", }
"data": users,
}) c.JSON(http.StatusOK, gin.H{
return "success": true,
"message": "",
"data": users,
})
} }
func SearchUsers(c *gin.Context) { func SearchUsers(c *gin.Context) {

View File

@ -25,10 +25,21 @@ type Token struct {
UsedQuota int64 `json:"used_quota" gorm:"bigint;default:0"` // used quota UsedQuota int64 `json:"used_quota" gorm:"bigint;default:0"` // used quota
} }
func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error) { func GetAllUserTokens(userId int, startIdx int, num int, order string) ([]*Token, error) {
var tokens []*Token var tokens []*Token
var err error var err error
err = DB.Where("user_id = ?", userId).Order("id desc").Limit(num).Offset(startIdx).Find(&tokens).Error query := DB.Where("user_id = ?", userId)
switch order {
case "remain_quota":
query = query.Order("unlimited_quota desc, remain_quota desc")
case "used_quota":
query = query.Order("used_quota desc")
default:
query = query.Order("id desc")
}
err = query.Limit(num).Offset(startIdx).Find(&tokens).Error
return tokens, err return tokens, err
} }

View File

@ -40,9 +40,22 @@ func GetMaxUserId() int {
return user.Id return user.Id
} }
func GetAllUsers(startIdx int, num int) (users []*User, err error) { func GetAllUsers(startIdx int, num int, order string) (users []*User, err error) {
err = DB.Order("id desc").Limit(num).Offset(startIdx).Omit("password").Where("status != ?", common.UserStatusDeleted).Find(&users).Error query := DB.Limit(num).Offset(startIdx).Omit("password").Where("status != ?", common.UserStatusDeleted)
return users, err
switch order {
case "quota":
query = query.Order("quota desc")
case "used_quota":
query = query.Order("used_quota desc")
case "request_count":
query = query.Order("request_count desc")
default:
query = query.Order("id desc")
}
err = query.Find(&users).Error
return users, err
} }
func SearchUsers(keyword string) (users []*User, err error) { func SearchUsers(keyword string) (users []*User, err error) {

View File

@ -247,6 +247,8 @@ const TokensTable = () => {
const [editingToken, setEditingToken] = useState({ const [editingToken, setEditingToken] = useState({
id: undefined id: undefined
}); });
const [orderBy, setOrderBy] = useState('');
const [dropdownVisible, setDropdownVisible] = useState(false);
const closeEdit = () => { const closeEdit = () => {
setShowEdit(false); setShowEdit(false);
@ -269,7 +271,7 @@ const TokensTable = () => {
let pageData = tokens.slice((activePage - 1) * pageSize, activePage * pageSize); let pageData = tokens.slice((activePage - 1) * pageSize, activePage * pageSize);
const loadTokens = async (startIdx) => { const loadTokens = async (startIdx) => {
setLoading(true); setLoading(true);
const res = await API.get(`/api/token/?p=${startIdx}&size=${pageSize}`); const res = await API.get(`/api/token/?p=${startIdx}&size=${pageSize}&order=${orderBy}`);
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
if (startIdx === 0) { if (startIdx === 0) {
@ -289,7 +291,7 @@ const TokensTable = () => {
(async () => { (async () => {
if (activePage === Math.ceil(tokens.length / pageSize) + 1) { if (activePage === Math.ceil(tokens.length / pageSize) + 1) {
// In this case we have to load more data and then append them. // In this case we have to load more data and then append them.
await loadTokens(activePage - 1); await loadTokens(activePage - 1, orderBy);
} }
setActivePage(activePage); setActivePage(activePage);
})(); })();
@ -392,12 +394,12 @@ const TokensTable = () => {
}; };
useEffect(() => { useEffect(() => {
loadTokens(0) loadTokens(0, orderBy)
.then() .then()
.catch((reason) => { .catch((reason) => {
showError(reason); showError(reason);
}); });
}, [pageSize]); }, [pageSize, orderBy]);
const removeRecord = key => { const removeRecord = key => {
let newDataSource = [...tokens]; let newDataSource = [...tokens];
@ -452,6 +454,7 @@ const TokensTable = () => {
// if keyword is blank, load files instead. // if keyword is blank, load files instead.
await loadTokens(0); await loadTokens(0);
setActivePage(1); setActivePage(1);
setOrderBy('');
return; return;
} }
setSearching(true); setSearching(true);
@ -520,6 +523,23 @@ const TokensTable = () => {
} }
}; };
const handleOrderByChange = (e, { value }) => {
setOrderBy(value);
setActivePage(1);
setDropdownVisible(false);
};
const renderSelectedOption = (orderBy) => {
switch (orderBy) {
case 'remain_quota':
return '按剩余额度排序';
case 'used_quota':
return '按已用额度排序';
default:
return '默认排序';
}
};
return ( return (
<> <>
<EditToken refresh={refresh} editingToken={editingToken} visiable={showEdit} handleClose={closeEdit}></EditToken> <EditToken refresh={refresh} editingToken={editingToken} visiable={showEdit} handleClose={closeEdit}></EditToken>
@ -579,6 +599,21 @@ const TokensTable = () => {
await copyText(keys); await copyText(keys);
} }
}>复制所选令牌到剪贴板</Button> }>复制所选令牌到剪贴板</Button>
<Dropdown
trigger="click"
position="bottomLeft"
visible={dropdownVisible}
onVisibleChange={(visible) => setDropdownVisible(visible)}
render={
<Dropdown.Menu>
<Dropdown.Item onClick={() => handleOrderByChange('', { value: '' })}>默认排序</Dropdown.Item>
<Dropdown.Item onClick={() => handleOrderByChange('', { value: 'remain_quota' })}>按剩余额度排序</Dropdown.Item>
<Dropdown.Item onClick={() => handleOrderByChange('', { value: 'used_quota' })}>按已用额度排序</Dropdown.Item>
</Dropdown.Menu>
}
>
<Button style={{ marginLeft: '10px' }}>{renderSelectedOption(orderBy)}</Button>
</Dropdown>
</> </>
); );
}; };

View File

@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { API, showError, showSuccess } from '../helpers'; import { API, showError, showSuccess } from '../helpers';
import { Button, Form, Popconfirm, Space, Table, Tag, Tooltip } from '@douyinfe/semi-ui'; import { Button, Form, Popconfirm, Space, Table, Tag, Tooltip, Dropdown } from '@douyinfe/semi-ui';
import { ITEMS_PER_PAGE } from '../constants'; import { ITEMS_PER_PAGE } from '../constants';
import { renderGroup, renderNumber, renderQuota } from '../helpers/render'; import { renderGroup, renderNumber, renderQuota } from '../helpers/render';
import AddUser from '../pages/User/AddUser'; import AddUser from '../pages/User/AddUser';
@ -139,6 +139,8 @@ const UsersTable = () => {
const [editingUser, setEditingUser] = useState({ const [editingUser, setEditingUser] = useState({
id: undefined id: undefined
}); });
const [orderBy, setOrderBy] = useState('');
const [dropdownVisible, setDropdownVisible] = useState(false);
const setCount = (data) => { const setCount = (data) => {
if (data.length >= (activePage) * ITEMS_PER_PAGE) { if (data.length >= (activePage) * ITEMS_PER_PAGE) {
@ -162,7 +164,7 @@ const UsersTable = () => {
}; };
const loadUsers = async (startIdx) => { const loadUsers = async (startIdx) => {
const res = await API.get(`/api/user/?p=${startIdx}`); const res = await API.get(`/api/user/?p=${startIdx}&order=${orderBy}`);
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
if (startIdx === 0) { if (startIdx === 0) {
@ -184,19 +186,19 @@ const UsersTable = () => {
(async () => { (async () => {
if (activePage === Math.ceil(users.length / ITEMS_PER_PAGE) + 1) { if (activePage === Math.ceil(users.length / ITEMS_PER_PAGE) + 1) {
// In this case we have to load more data and then append them. // In this case we have to load more data and then append them.
await loadUsers(activePage - 1); await loadUsers(activePage - 1, orderBy);
} }
setActivePage(activePage); setActivePage(activePage);
})(); })();
}; };
useEffect(() => { useEffect(() => {
loadUsers(0) loadUsers(0, orderBy)
.then() .then()
.catch((reason) => { .catch((reason) => {
showError(reason); showError(reason);
}); });
}, []); }, [orderBy]);
const manageUser = async (username, action, record) => { const manageUser = async (username, action, record) => {
const res = await API.post('/api/user/manage', { const res = await API.post('/api/user/manage', {
@ -239,6 +241,7 @@ const UsersTable = () => {
// if keyword is blank, load files instead. // if keyword is blank, load files instead.
await loadUsers(0); await loadUsers(0);
setActivePage(1); setActivePage(1);
setOrderBy('');
return; return;
} }
setSearching(true); setSearching(true);
@ -301,6 +304,25 @@ const UsersTable = () => {
} }
}; };
const handleOrderByChange = (e, { value }) => {
setOrderBy(value);
setActivePage(1);
setDropdownVisible(false);
};
const renderSelectedOption = (orderBy) => {
switch (orderBy) {
case 'quota':
return '按剩余额度排序';
case 'used_quota':
return '按已用额度排序';
case 'request_count':
return '按请求次数排序';
default:
return '默认排序';
}
};
return ( return (
<> <>
<AddUser refresh={refresh} visible={showAddUser} handleClose={closeAddUser}></AddUser> <AddUser refresh={refresh} visible={showAddUser} handleClose={closeAddUser}></AddUser>
@ -331,6 +353,22 @@ const UsersTable = () => {
setShowAddUser(true); setShowAddUser(true);
} }
}>添加用户</Button> }>添加用户</Button>
<Dropdown
trigger="click"
position="bottomLeft"
visible={dropdownVisible}
onVisibleChange={(visible) => setDropdownVisible(visible)}
render={
<Dropdown.Menu>
<Dropdown.Item onClick={() => handleOrderByChange('', { value: '' })}>默认排序</Dropdown.Item>
<Dropdown.Item onClick={() => handleOrderByChange('', { value: 'quota' })}>按剩余额度排序</Dropdown.Item>
<Dropdown.Item onClick={() => handleOrderByChange('', { value: 'used_quota' })}>按已用额度排序</Dropdown.Item>
<Dropdown.Item onClick={() => handleOrderByChange('', { value: 'request_count' })}>按请求次数排序</Dropdown.Item>
</Dropdown.Menu>
}
>
<Button style={{ marginLeft: '10px' }}>{renderSelectedOption(orderBy)}</Button>
</Dropdown>
</> </>
); );
}; };

View File

@ -48,9 +48,10 @@ const TokensTable = () => {
const [searching, setSearching] = useState(false); const [searching, setSearching] = useState(false);
const [showTopUpModal, setShowTopUpModal] = useState(false); const [showTopUpModal, setShowTopUpModal] = useState(false);
const [targetTokenIdx, setTargetTokenIdx] = useState(0); const [targetTokenIdx, setTargetTokenIdx] = useState(0);
const [orderBy, setOrderBy] = useState('');
const loadTokens = async (startIdx) => { const loadTokens = async (startIdx) => {
const res = await API.get(`/api/token/?p=${startIdx}`); const res = await API.get(`/api/token/?p=${startIdx}&order=${orderBy}`);
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
if (startIdx === 0) { if (startIdx === 0) {
@ -70,7 +71,7 @@ const TokensTable = () => {
(async () => { (async () => {
if (activePage === Math.ceil(tokens.length / ITEMS_PER_PAGE) + 1) { if (activePage === Math.ceil(tokens.length / ITEMS_PER_PAGE) + 1) {
// In this case we have to load more data and then append them. // In this case we have to load more data and then append them.
await loadTokens(activePage - 1); await loadTokens(activePage - 1, orderBy);
} }
setActivePage(activePage); setActivePage(activePage);
})(); })();
@ -160,12 +161,12 @@ const TokensTable = () => {
} }
useEffect(() => { useEffect(() => {
loadTokens(0) loadTokens(0, orderBy)
.then() .then()
.catch((reason) => { .catch((reason) => {
showError(reason); showError(reason);
}); });
}, []); }, [orderBy]);
const manageToken = async (id, action, idx) => { const manageToken = async (id, action, idx) => {
let data = { id }; let data = { id };
@ -205,6 +206,7 @@ const TokensTable = () => {
// if keyword is blank, load files instead. // if keyword is blank, load files instead.
await loadTokens(0); await loadTokens(0);
setActivePage(1); setActivePage(1);
setOrderBy('');
return; return;
} }
setSearching(true); setSearching(true);
@ -243,6 +245,11 @@ const TokensTable = () => {
setLoading(false); setLoading(false);
}; };
const handleOrderByChange = (e, { value }) => {
setOrderBy(value);
setActivePage(1);
};
return ( return (
<> <>
<Form onSubmit={searchTokens}> <Form onSubmit={searchTokens}>
@ -427,6 +434,18 @@ const TokensTable = () => {
添加新的令牌 添加新的令牌
</Button> </Button>
<Button size='small' onClick={refresh} loading={loading}>刷新</Button> <Button size='small' onClick={refresh} loading={loading}>刷新</Button>
<Dropdown
placeholder='排序方式'
selection
options={[
{ key: '', text: '默认排序', value: '' },
{ key: 'remain_quota', text: '按剩余额度排序', value: 'remain_quota' },
{ key: 'used_quota', text: '按已用额度排序', value: 'used_quota' },
]}
value={orderBy}
onChange={handleOrderByChange}
style={{ marginLeft: '10px' }}
/>
<Pagination <Pagination
floated='right' floated='right'
activePage={activePage} activePage={activePage}

View File

@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Button, Form, Label, Pagination, Popup, Table } from 'semantic-ui-react'; import { Button, Form, Label, Pagination, Popup, Table, Dropdown } from 'semantic-ui-react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { API, showError, showSuccess } from '../helpers'; import { API, showError, showSuccess } from '../helpers';
@ -25,9 +25,10 @@ const UsersTable = () => {
const [activePage, setActivePage] = useState(1); const [activePage, setActivePage] = useState(1);
const [searchKeyword, setSearchKeyword] = useState(''); const [searchKeyword, setSearchKeyword] = useState('');
const [searching, setSearching] = useState(false); const [searching, setSearching] = useState(false);
const [orderBy, setOrderBy] = useState('');
const loadUsers = async (startIdx) => { const loadUsers = async (startIdx) => {
const res = await API.get(`/api/user/?p=${startIdx}`); const res = await API.get(`/api/user/?p=${startIdx}&order=${orderBy}`);
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
if (startIdx === 0) { if (startIdx === 0) {
@ -47,19 +48,19 @@ const UsersTable = () => {
(async () => { (async () => {
if (activePage === Math.ceil(users.length / ITEMS_PER_PAGE) + 1) { if (activePage === Math.ceil(users.length / ITEMS_PER_PAGE) + 1) {
// In this case we have to load more data and then append them. // In this case we have to load more data and then append them.
await loadUsers(activePage - 1); await loadUsers(activePage - 1, orderBy);
} }
setActivePage(activePage); setActivePage(activePage);
})(); })();
}; };
useEffect(() => { useEffect(() => {
loadUsers(0) loadUsers(0, orderBy)
.then() .then()
.catch((reason) => { .catch((reason) => {
showError(reason); showError(reason);
}); });
}, []); }, [orderBy]);
const manageUser = (username, action, idx) => { const manageUser = (username, action, idx) => {
(async () => { (async () => {
@ -110,6 +111,7 @@ const UsersTable = () => {
// if keyword is blank, load files instead. // if keyword is blank, load files instead.
await loadUsers(0); await loadUsers(0);
setActivePage(1); setActivePage(1);
setOrderBy('');
return; return;
} }
setSearching(true); setSearching(true);
@ -148,6 +150,11 @@ const UsersTable = () => {
setLoading(false); setLoading(false);
}; };
const handleOrderByChange = (e, { value }) => {
setOrderBy(value);
setActivePage(1);
};
return ( return (
<> <>
<Form onSubmit={searchUsers}> <Form onSubmit={searchUsers}>
@ -322,6 +329,19 @@ const UsersTable = () => {
<Button size='small' as={Link} to='/user/add' loading={loading}> <Button size='small' as={Link} to='/user/add' loading={loading}>
添加新的用户 添加新的用户
</Button> </Button>
<Dropdown
placeholder='排序方式'
selection
options={[
{ key: '', text: '默认排序', value: '' },
{ key: 'quota', text: '按剩余额度排序', value: 'quota' },
{ key: 'used_quota', text: '按已用额度排序', value: 'used_quota' },
{ key: 'request_count', text: '按请求次数排序', value: 'request_count' },
]}
value={orderBy}
onChange={handleOrderByChange}
style={{ marginLeft: '10px' }}
/>
<Pagination <Pagination
floated='right' floated='right'
activePage={activePage} activePage={activePage}