125 lines
2.7 KiB
JavaScript
125 lines
2.7 KiB
JavaScript
import { query } from '../db/client.js'
|
|
|
|
export async function getAdminUserById(userId) {
|
|
const result = await query(
|
|
'SELECT * FROM admin_users WHERE id = $1 LIMIT 1',
|
|
[Number(userId)],
|
|
)
|
|
return result.rows[0] || null
|
|
}
|
|
|
|
export async function getAdminUserByUsername(username) {
|
|
const result = await query(
|
|
'SELECT * FROM admin_users WHERE username = $1 LIMIT 1',
|
|
[String(username || '').trim().toLowerCase()],
|
|
)
|
|
return result.rows[0] || null
|
|
}
|
|
|
|
export async function createAdminUser(input) {
|
|
const result = await query(
|
|
`
|
|
INSERT INTO admin_users (
|
|
username,
|
|
password_hash,
|
|
role,
|
|
status,
|
|
created_at,
|
|
updated_at
|
|
) VALUES ($1, $2, $3, $4, $5, $6)
|
|
RETURNING *
|
|
`,
|
|
[
|
|
input.username,
|
|
input.passwordHash,
|
|
input.role,
|
|
input.status,
|
|
input.createdAt,
|
|
input.updatedAt,
|
|
],
|
|
)
|
|
|
|
return result.rows[0] || null
|
|
}
|
|
|
|
export async function updateAdminUser(userId, patch) {
|
|
const current = await getAdminUserById(userId)
|
|
if (!current) {
|
|
return null
|
|
}
|
|
|
|
const next = { ...current, ...patch }
|
|
const result = await query(
|
|
`
|
|
UPDATE admin_users
|
|
SET
|
|
username = $1,
|
|
password_hash = $2,
|
|
role = $3,
|
|
status = $4,
|
|
updated_at = $5
|
|
WHERE id = $6
|
|
RETURNING *
|
|
`,
|
|
[
|
|
next.username,
|
|
next.password_hash,
|
|
next.role,
|
|
next.status,
|
|
next.updated_at,
|
|
Number(userId),
|
|
],
|
|
)
|
|
|
|
return result.rows[0] || null
|
|
}
|
|
|
|
export async function listAdminUsers({ page = 1, pageSize = 20, username = '', role = '', status = '' } = {}) {
|
|
const offset = (page - 1) * pageSize
|
|
const filters = []
|
|
const params = []
|
|
|
|
if (username) {
|
|
params.push(`%${username}%`)
|
|
filters.push(`username ILIKE $${params.length}`)
|
|
}
|
|
|
|
if (role) {
|
|
params.push(role)
|
|
filters.push(`role = $${params.length}`)
|
|
}
|
|
|
|
if (status) {
|
|
params.push(status)
|
|
filters.push(`status = $${params.length}`)
|
|
}
|
|
|
|
const whereClause = filters.length > 0 ? `WHERE ${filters.join(' AND ')}` : ''
|
|
const totalResult = await query(`SELECT COUNT(*)::int AS total FROM admin_users ${whereClause}`, params)
|
|
|
|
params.push(pageSize)
|
|
params.push(offset)
|
|
const itemsResult = await query(
|
|
`
|
|
SELECT *
|
|
FROM admin_users
|
|
${whereClause}
|
|
ORDER BY id DESC
|
|
LIMIT $${params.length - 1} OFFSET $${params.length}
|
|
`,
|
|
params,
|
|
)
|
|
|
|
return {
|
|
items: itemsResult.rows,
|
|
total: Number(totalResult.rows[0]?.total || 0),
|
|
}
|
|
}
|
|
|
|
export async function countActiveAdminUsers() {
|
|
const result = await query(
|
|
`SELECT COUNT(*)::int AS total FROM admin_users WHERE role = 'admin' AND status = 'active'`,
|
|
)
|
|
return Number(result.rows[0]?.total || 0)
|
|
}
|