feat: 完成查看色谱柱的功能

This commit is contained in:
2025-08-30 23:15:06 +08:00
parent 0223dff65e
commit 694ac5ce46
30 changed files with 2328 additions and 471 deletions

19
server/example.env Normal file
View File

@@ -0,0 +1,19 @@
# 将文件更名为 .env 即可
# 程序运行的端口号
PORT=3000
# MongoDB 数据库连接字符串
MONGODB_URI=mongodb://localhost:27017/qctool_plus
# 用于加密数据的秘钥
SECRET_KEY=YOUR_SECRET_KEY
# Web 管理界面的用户名和密码
WEB_ADMIN_USERNAME=admin
WEB_ADMIN_PASSWORD=admin
# NODE 运行环境(production生产/development开发)
NODE_ENV=production
# NODE_ENV=development

1215
server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -11,6 +11,14 @@
"type": "module",
"main": "index.js",
"scripts": {
"test": "nodemon ./src/index.js"
"dev": "nodemon ./src/index.js"
},
"dependencies": {
"bcrypt": "^6.0.0",
"cors": "^2.8.5",
"dotenv": "^17.2.1",
"express": "^5.1.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.17.0"
}
}

81
server/src/column.js Normal file
View File

@@ -0,0 +1,81 @@
import mongoose from "mongoose"
import express from 'express'
import { Laboratory } from "./laboratory.js"
const Column = mongoose.model('Column', new mongoose.Schema({
num: { type: Number }, // 色谱柱编号 235
type: { type: String }, // 色谱柱类型 LC 或 GC
name: { type: String }, // 色谱柱全名 LC235
model: { type: String }, // 色谱柱型号 Zorbax Eclipse Plus C18
madeby: { type: String }, // 生产厂家 Agilent
length: { type: String }, // 色谱柱长度 250mm
innerDiameter: { type: String }, // 色谱柱内径 4.6mm
particleSize: { type: String }, // 色谱柱粒径 5um
reverse: { type: Boolean }, // 是否反接色谱柱
status: { type: mongoose.SchemaTypes.ObjectId, ref: 'ColumnStatus' }, // 色谱柱状态
laboratory: { type: mongoose.SchemaTypes.ObjectId, ref: 'Laboratory' }, // 所属实验室
group: { type: mongoose.SchemaTypes.ObjectId, ref: 'Group' }, // 所属分组
borrow: { type: mongoose.SchemaTypes.ObjectId, ref: 'ColumnBorrowRecord' }, // 色谱柱借用记录
description: { type: String }, // 备注
}))
const ColumnStatus = mongoose.model('ColumnStatus', new mongoose.Schema({
name: { type: String }, // 色谱柱全名 LC235 或 GC065
// 色谱柱状态 purchased、activated、inuse、effpoor、discarded
status: { type: String },
// 状态描述 新购入、已活化(老化)、使用中、柱效差、已报废
description: { type: String },
// 最后状态日期 2025.07.30
date: { type: String },
purchased_date: { type: String }, // 新购入日期
activated_date: { type: String }, // 已活化(老化)日期
inuse_date: { type: String }, // 开始使用日期
effpoor_date: { type: String }, // 柱效变差日期
discarded_date: { type: String }, // 报废日期
}))
const router = express.Router()
// 获取所有色谱柱
// TODO maybe need paging
router.get('/', async (req, res) => {
const columns = await Column.find().populate(['status', 'laboratory', 'borrow', 'group'])
res.json(columns)
})
// 新增色谱柱
router.post('/', async (req, res) => {
const data = req.body
const date = formatDate(new Date())
// 创建色谱柱状态
data.status = await ColumnStatus.create({
name: req.body.name,
status: 'purchased',
description: '新购入',
date: date,
purchased_date: date
})
// 确定色谱柱所属实验室
data.laboratory = await Laboratory.findOne({ name: data.laboratory.name })
|| await Laboratory.findOne({ name: '未知' })
const column = await Column.create(data)
res.json(column)
})
// TODO CRUD
/**
* 格式化日期
* @param {Date} date 日期对象
* @returns 格式化后的日期字符串,比如'2025.03.09'
*/
function formatDate(date) {
const year = date.getFullYear()
const month = date.getMonth() < 9 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
const day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
return `${year}.${month}.${day}`
}
export { router as columnRouter, Column, ColumnStatus }

View File

@@ -0,0 +1,25 @@
import mongoose from "mongoose"
import express from 'express'
const ColumnBorrowRecord = mongoose.model('ColumnBorrowRecord', new mongoose.Schema({
name: { type: String}, // 色谱柱编号
borrower: { type: mongoose.SchemaTypes.ObjectId, ref: 'User' }, // 借用人
borrowTo: { type: mongoose.SchemaTypes.ObjectId, ref: 'Laboratory' }, // 借用到实验室
borrowDate: { type: String }, // 借用日期 2025.07.30
returnStatus: { type: Boolean, }, // 是否已归还
returner: { type: mongoose.SchemaTypes.ObjectId, ref: 'User' }, // 归还人
returnDate: { type: String }, // 归还日期 2025.08.30
description: { type: String }, // 备注
}))
const router = express.Router()
// TODO CURD
router.get('/:columnName', async (req, res) => {
const record = await ColumnBorrowRecord.find({ name: req.params.columnName }).populate(['User', 'Laboratory'])
res.json(record)
})
export { router as columnBorrowRecordRouter, ColumnBorrowRecord }

45
server/src/group.js Normal file
View File

@@ -0,0 +1,45 @@
import mongoose from "mongoose"
import express from 'express'
const Group = mongoose.model('Group', new mongoose.Schema({
name: { type: String }, // 分组名称
description: { type: String }, // 分组描述
laboratory: { type: mongoose.SchemaTypes.ObjectId, ref: 'Laboratory' }, // 所属实验室
}))
const router = express.Router()
// 获取所有分组
router.get('/', async (req, res) => {
const groups = await Group.find().populate('Laboratory')
res.json(groups)
})
// 获取指定分组
router.get('/:id', async (req, res) => {
const group = await Group.findById(req.params.id).populate('Laboratory')
if (!group) {
return res.status(404).json({ message: `Can not found the group ${req.params.id}` })
}
res.json(group)
})
// 创建分组
router.post('/', async (req, res) => {
const group = await Group.create(req.body)
res.json(group)
})
// 更新分组
router.patch('/:id', async (req, res) => {
const group = await Group.findByIdAndUpdate(req.params.id, req.body, { new: true })
res.json(group)
})
// 删除分组
router.delete('/:id', async (req, res) => {
const group = await Group.findByIdAndDelete(req.params.id)
res.json(group)
})
export { router as groupRouter, Group }

45
server/src/index.js Normal file
View File

@@ -0,0 +1,45 @@
import express from 'express'
import mongoose from 'mongoose'
import cors from 'cors'
import dotenv from "dotenv"
dotenv.config({ path: '.env', quiet: true })
// import routers
import { uacRouter } from './uac.js'
import { columnRouter } from './column.js'
import { columnBorrowRecordRouter } from './column_borrow_record.js'
import { laboratoryRouter } from './laboratory.js'
import { groupRouter } from './group.js'
const log = (...args) => {
console.log(`[${new Date().toISOString()}] Main`, ...args)
}
mongoose.connect(process.env.MONGODB_URI).then(() => {
log('连接 MongoDB 数据库成功')
}).catch(err => {
log('连接 MongoDB 数据库失败', err)
})
const app = express()
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use('/api/uac', uacRouter)
app.use('/api/columns', columnRouter)
app.use('/api/column_borrow_records', columnBorrowRecordRouter)
app.use('/api/laboratories', laboratoryRouter)
app.use('/api/groups', groupRouter)
uacRouter.initialize()
laboratoryRouter.initialize()
app.get('/', async (req, res) => {
res.send('success')
})
const port = process.env.PORT || 3000
app.listen(port, () => {
log('系统已启动, 服务地址', `http://localhost:${port}`)
})

56
server/src/laboratory.js Normal file
View File

@@ -0,0 +1,56 @@
import mongoose from "mongoose"
import express from 'express'
const Laboratory = mongoose.model('Laboratory', new mongoose.Schema({
name: { type: String }, // 实验室名称
description: { type: String }, // 实验室描述
}))
async function initialize() {
await Laboratory.insertMany([
{ name: "一楼", description: "质量部一楼东面" },
{ name: "三楼", description: "质量部一楼东面液相室二" },
{ name: "七楼", description: "宿舍北七楼" },
{ name: "研发分析", description: "质量部三楼西面" },
{ name: "API 实验室", description: "质量部三四楼东面" },
{ name: "未知", description: "未知" },
])
}
const router = express.Router()
router.initialize = initialize
// 获取所有的实验室
router.get('/', async (req, res) => {
const lab = await Laboratory.find()
res.json(lab)
})
// 获取指定实验室
router.get('/:id', async (req, res) => {
const lab = await Laboratory.findById(req.params.id)
if (!lab) {
return res.status(404).json({ message: `Can not found the laboratory ${req.params.id}` })
}
res.json(lab)
})
// 创建实验室
router.post('/', async (req, res) => {
const lab = await Laboratory.create(req.body)
res.json(lab)
})
// 更新实验室
router.patch('/:id', async (req, res) => {
const lab = await Laboratory.findByIdAndUpdate(req.params.id, req.body, { new: true })
res.json(lab)
})
// 删除实验室
router.delete('/:id', async (req, res) => {
const lab = await Laboratory.findByIdAndDelete(req.params.id)
res.json(lab)
})
export { router as laboratoryRouter, Laboratory }

279
server/src/uac.js Normal file
View File

@@ -0,0 +1,279 @@
import mongoose from "mongoose"
import express from "express"
import bcrypt from "bcrypt"
import jwt from "jsonwebtoken"
const log = (...args) => {
console.log(`[${new Date().toISOString()}] UAC`, ...args)
}
// 权限模型
const Permission = mongoose.model('Permission', new mongoose.Schema({
name: { type: String, required: true, unique: true }, // 权限名称
description: { type: String } // 权限描述
}))
// 角色模型
const Role = mongoose.model('Role', new mongoose.Schema({
name: { type: String, required: true, unique: true }, // 角色
permissions: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'Permission' }], // 角色权限
description: { type: String } // 角色描述
}))
// 用户模型
const User = mongoose.model('User', new mongoose.Schema({
username: { type: String, required: true, unique: true }, // 用户名(用于登录)
truename: { type: String }, // 用户名(用于显示)
password: {
type: String,
required: true,
set(val) {
return bcrypt.hashSync(val, 10)
}
}, // 密码(加密存储)
role: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'Role' }], // 角色
}))
// 初始化模型数据库
async function initialize() {
log('初始化权限模型...')
await Permission.deleteMany({})
await Permission.insertMany([
// 用户相关权限
{ name: 'access_user_get', description: '查看用户信息' },
{ name: 'access_user_post', description: '新增用户信息' },
{ name: 'access_user_patch', description: '修改用户信息' },
{ name: 'access_user_delete', description: '删除用户信息' },
// 角色相关权限
{ name: 'access_role_get', description: '查看角色信息' },
{ name: 'access_role_post', description: '新增角色信息' },
{ name: 'access_role_patch', description: '修改角色信息' },
{ name: 'access_role_delete', description: '删除角色信息' },
// 色谱柱相关权限
{ name: 'access_columns_get', description: '查看色谱柱信息' },
{ name: 'access_columns_post', description: '新增色谱柱信息' },
{ name: 'access_columns_patch', description: '修改色谱柱信息' },
{ name: 'access_columns_delete', description: '删除色谱柱信息' },
])
log('初始化角色模型...')
await Role.deleteMany({})
const p = await Permission.find({})
await Role.insertMany([
{ name: 'admin', description: '系统管理员', permissions: p },
])
// 创建一个默认的管理员用户, 并为其分配系统管理员权限
log('创建系统管理员账户...')
let username = process.env.WEB_ADMIN_USERNAME || 'admin'
let password = process.env.WEB_ADMIN_PASSWORD || 'admin'
await User.deleteOne({ username})
const admin = await User.create({
username, password,
truename: '系统管理员',
role: [await Role.findOne({ name: 'admin' })]
})
log(`初始化完成,系统管理员账号:${username},密码:${password}`)
if (process.env.NODE_ENV !== 'production') {
log(`请在生产环境中修改管理员账号和密码,以确保系统安全。`)
}
}
const router = express.Router()
router.initialize = initialize
/**
* 使用 jwt 验证用户是否登录
* @param {*} req request 请求
* @param {*} res response 响应
* @param {*} next 下一个中间件
* @returns
*/
function auth(req, res, next) {
const authorization = req.headers['authorization']
if (!authorization) {
return res.status(401).json({ error: 'unauth, please login' })
}
const token = authorization.split(' ')[1] // Bearer <token>
if (!token) {
return res.status(401).json({ error: 'unauth, please login' })
}
jwt.verify(token, 'your_jwt_secret', (err, decoded) => {
if (err) {
return res.status(403).json({ error: 'invalid or expired token, please login again' })
}
req.userId = decoded.userId
next()
})
}
function access(req, res, next) {
const userId = req.userId
User.findById(userId).populate({
path: "role",
populate: { path: "permissions" }
}).then(user => {
if (!user) {
return res.status(403).json({ error: 'user not found' })
}
// 该用户拥有的权限
const permissions = []
user.role.forEach((role) => {
role.permissions.map(p => permissions.push(p.name))
})
const requestRouter = req.route.path.split('/')[1]
const requestMethod = req.method.toLowerCase()
const require = `access_${requestRouter}_${requestMethod}`
if (permissions.includes(require)) {
next()
} else {
return res.status(403).json({
error: 'permission denied',
require,
userHas: permissions
})
}
}
)
}
// 获取用户列表
router.get('/user', auth, access, async (req, res) => {
log('GET /user 获取用户列表')
const users = await User.find({}, { password: 0 }).populate({
path: 'role',
populate: { path: 'permissions' }
})
res.json(users)
})
// 创建用户
router.post('/user', auth, access, async (req, res) => {
log('POST /user 创建用户')
let data = req.body
console.log(data.role)
try {
data.role = await Role.find({ name: { $in: data.role } })
const user = await User.create(data)
res.status(201).json(user)
} catch (err) {
res.status(500).json({ error: '创建用户失败', details: err.message })
}
})
// 更新用户信息
router.patch('/user/:id', auth, access, async (req, res) => {
log(`PATCH /user/${req.params.id} 更新用户信息`)
const userId = req.params.id
const data = req.body
try {
data.role = await Role.find({ name: { $in: data.role } })
const user = await User.findByIdAndUpdate(userId, data, { new: true }).populate('role')
if (!user) {
return res.status(404).json({ error: '用户未找到' })
}
res.json(user)
} catch (err) {
res.status(500).json({ error: '更新用户失败', details: err.message })
}
})
// 删除用户
router.delete('/user/:id', auth, access, async (req, res) => {
log(`DELETE /user/${req.params.id} 删除用户`)
const userId = req.params.id
try {
const user = await User.findByIdAndDelete(userId)
if (!user) {
return res.status(404).json({ error: '用户未找到' })
}
res.json({ message: '用户已删除', user })
} catch (err) {
res.status(500).json({ error: '删除用户失败', details: err.message })
}
})
// 获取角色列表
router.get('/role', auth, access, async (req, res) => {
log('GET /role 获取角色列表')
const roles = await Role.find({}).populate('permissions')
res.json(roles)
})
// 创建角色
router.post('/role', auth, access, async (req, res) => {
log('POST /role 创建角色')
const data = req.body
try {
data.permissions = await Permission.find({ name: { $in: data.permissions } })
const role = await Role.create(data)
res.status(201).json(role)
} catch (err) {
res.status(500).json({ error: '创建角色失败', details: err.message })
}
})
// 删除角色
router.delete('/role/:id', auth, access, async (req, res) => {
log(`DELETE /role/${req.params.id} 删除角色`)
const roleId = req.params.id
try {
const role = await Role.findByIdAndDelete(roleId)
if (!role) {
return res.status(404).json({ error: '角色未找到' })
}
res.json({ message: '角色已删除', role })
} catch (err) {
res.status(500).json({ error: '删除角色失败', details: err.message })
}
})
// 更新角色信息
router.patch('/role/:id', auth, access, async (req, res) => {
log(`PATCH /role/${req.params.id} 更新角色信息`)
const roleId = req.params.id
const data = req.body
try {
data.permissions = await Permission.find({ name: { $in: data.permissions } })
const role = await Role.findByIdAndUpdate(roleId, data, { new: true })
if (!role) {
return res.status(404).json({ error: '角色未找到' })
}
res.json(role.populate('permissions'))
} catch (err) {
res.status(500).json({ error: '更新角色失败', details: err.message })
}
})
// 用户登录
router.post('/sign', async (req, res) => {
const { username, password } = req.body
log('POST /sign 用户登录 ', username)
if (!username || !password) {
return res.status(400).json({ error: '用户名和密码不能为空' })
}
try {
// 查询用户
const user = await User.findOne({ username })
if (!user) {
return res.status(401).json({ error: '用户名或密码错误' })
}
// 验证密码
const isMatch = bcrypt.compareSync(password, user.password)
if (!isMatch) {
return res.status(401).json({ error: '用户名或密码错误' })
}
const token = jwt.sign({ userId: user._id }, 'your_jwt_secret', { expiresIn: '30d' })
res.json({ token })
} catch (err) {
return res.status(500).json({ error: '查询用户失败', details: err.message })
}
})
export { router as uacRouter, User, Role, Permission, auth, access }