补充修改
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
const DeviceWarning = require('../models/DeviceWarning');
|
||||
const { Op, fn, col } = require('sequelize');
|
||||
const sequelize = require('../config/database');
|
||||
const { QueryTypes } = require('sequelize');
|
||||
|
||||
// 获取设备预警列表
|
||||
exports.getDeviceWarnings = async (req, res) => {
|
||||
@@ -9,25 +9,52 @@ exports.getDeviceWarnings = async (req, res) => {
|
||||
const limit = parseInt(pageSize);
|
||||
const offset = (parseInt(page) - 1) * limit;
|
||||
|
||||
const where = {};
|
||||
// 构建WHERE条件
|
||||
let whereConditions = [];
|
||||
let whereParams = {};
|
||||
|
||||
if (deviceType) {
|
||||
where.deviceType = deviceType;
|
||||
whereConditions.push('deviceType = :deviceType');
|
||||
whereParams.deviceType = deviceType;
|
||||
}
|
||||
if (alertType) {
|
||||
where.alertType = alertType;
|
||||
whereConditions.push('alertType = :alertType');
|
||||
whereParams.alertType = alertType;
|
||||
}
|
||||
if (status) {
|
||||
where.status = status;
|
||||
whereConditions.push('status = :status');
|
||||
whereParams.status = status;
|
||||
}
|
||||
if (farmerName) {
|
||||
where.farmerName = { [Op.like]: `%${farmerName}%` };
|
||||
whereConditions.push('farmerName LIKE :farmerName');
|
||||
whereParams.farmerName = `%${farmerName}%`;
|
||||
}
|
||||
|
||||
const { count, rows } = await DeviceWarning.findAndCountAll({
|
||||
where,
|
||||
limit,
|
||||
offset,
|
||||
order: [['alertTime', 'DESC']],
|
||||
const whereClause = whereConditions.length > 0 ? 'WHERE ' + whereConditions.join(' AND ') : '';
|
||||
|
||||
// 查询总数
|
||||
const countQuery = `SELECT COUNT(*) as count FROM device_warnings ${whereClause}`;
|
||||
const countResult = await DeviceWarning.sequelize.query(countQuery, {
|
||||
replacements: whereParams,
|
||||
type: QueryTypes.SELECT
|
||||
});
|
||||
const total = countResult[0].count;
|
||||
|
||||
// 查询数据
|
||||
const dataQuery = `
|
||||
SELECT id, farmName, farmerName, phone, deviceType, deviceNumber,
|
||||
alertType, alertLevel, alertTime, status, description,
|
||||
location, batteryLevel, signalStrength, temperature,
|
||||
resolvedBy, resolvedAt, remarks, createdAt, updatedAt
|
||||
FROM device_warnings
|
||||
${whereClause}
|
||||
ORDER BY alertTime DESC
|
||||
LIMIT :limit OFFSET :offset
|
||||
`;
|
||||
|
||||
const rows = await DeviceWarning.sequelize.query(dataQuery, {
|
||||
replacements: { ...whereParams, limit, offset },
|
||||
type: QueryTypes.SELECT
|
||||
});
|
||||
|
||||
res.status(200).json({
|
||||
@@ -35,7 +62,7 @@ exports.getDeviceWarnings = async (req, res) => {
|
||||
message: '获取成功',
|
||||
data: {
|
||||
list: rows,
|
||||
total: count,
|
||||
total: total,
|
||||
page: parseInt(page),
|
||||
pageSize: limit,
|
||||
},
|
||||
@@ -50,13 +77,26 @@ exports.getDeviceWarnings = async (req, res) => {
|
||||
exports.getDeviceWarningById = async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const warning = await DeviceWarning.findByPk(id);
|
||||
|
||||
const query = `
|
||||
SELECT id, farmName, farmerName, phone, deviceType, deviceNumber,
|
||||
alertType, alertLevel, alertTime, status, description,
|
||||
location, batteryLevel, signalStrength, temperature,
|
||||
resolvedBy, resolvedAt, remarks, createdAt, updatedAt
|
||||
FROM device_warnings
|
||||
WHERE id = :id
|
||||
`;
|
||||
|
||||
const results = await DeviceWarning.sequelize.query(query, {
|
||||
replacements: { id },
|
||||
type: QueryTypes.SELECT
|
||||
});
|
||||
|
||||
if (!warning) {
|
||||
if (results.length === 0) {
|
||||
return res.status(404).json({ code: 404, message: '设备预警未找到' });
|
||||
}
|
||||
|
||||
res.status(200).json({ code: 200, message: '获取成功', data: warning });
|
||||
res.status(200).json({ code: 200, message: '获取成功', data: results[0] });
|
||||
} catch (error) {
|
||||
console.error('获取设备预警详情失败:', error);
|
||||
res.status(500).json({ code: 500, message: '获取设备预警详情失败', error: error.message });
|
||||
@@ -66,8 +106,53 @@ exports.getDeviceWarningById = async (req, res) => {
|
||||
// 创建新的设备预警
|
||||
exports.createDeviceWarning = async (req, res) => {
|
||||
try {
|
||||
const newWarning = await DeviceWarning.create(req.body);
|
||||
res.status(201).json({ code: 201, message: '创建成功', data: newWarning });
|
||||
const {
|
||||
farmName, farmerName, phone, deviceType, deviceNumber,
|
||||
alertType, alertLevel = 'medium', description, location, batteryLevel,
|
||||
signalStrength, temperature, remarks
|
||||
} = req.body;
|
||||
|
||||
const insertQuery = `
|
||||
INSERT INTO device_warnings
|
||||
(farmName, farmerName, phone, deviceType, deviceNumber, alertType, alertLevel,
|
||||
description, location, batteryLevel, signalStrength, temperature, remarks,
|
||||
alertTime, status, createdAt, updatedAt)
|
||||
VALUES
|
||||
(:farmName, :farmerName, :phone, :deviceType, :deviceNumber, :alertType, :alertLevel,
|
||||
:description, :location, :batteryLevel, :signalStrength, :temperature, :remarks,
|
||||
NOW(), 'active', NOW(), NOW())
|
||||
`;
|
||||
|
||||
await DeviceWarning.sequelize.query(insertQuery, {
|
||||
replacements: {
|
||||
farmName, farmerName, phone, deviceType, deviceNumber,
|
||||
alertType, alertLevel,
|
||||
description: description || null,
|
||||
location: location || null,
|
||||
batteryLevel: batteryLevel || null,
|
||||
signalStrength: signalStrength || null,
|
||||
temperature: temperature || null,
|
||||
remarks: remarks || null
|
||||
},
|
||||
type: QueryTypes.INSERT
|
||||
});
|
||||
|
||||
// 获取刚插入的记录
|
||||
const selectQuery = `
|
||||
SELECT id, farmName, farmerName, phone, deviceType, deviceNumber,
|
||||
alertType, alertLevel, alertTime, status, description,
|
||||
location, batteryLevel, signalStrength, temperature,
|
||||
resolvedBy, resolvedAt, remarks, createdAt, updatedAt
|
||||
FROM device_warnings
|
||||
ORDER BY id DESC
|
||||
LIMIT 1
|
||||
`;
|
||||
|
||||
const results = await DeviceWarning.sequelize.query(selectQuery, {
|
||||
type: QueryTypes.SELECT
|
||||
});
|
||||
|
||||
res.status(201).json({ code: 201, message: '创建成功', data: results[0] });
|
||||
} catch (error) {
|
||||
console.error('创建设备预警失败:', error);
|
||||
res.status(500).json({ code: 500, message: '创建设备预警失败', error: error.message });
|
||||
@@ -78,16 +163,60 @@ exports.createDeviceWarning = async (req, res) => {
|
||||
exports.updateDeviceWarning = async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const [updatedRows] = await DeviceWarning.update(req.body, {
|
||||
where: { id },
|
||||
const updateFields = [];
|
||||
const replacements = { id };
|
||||
|
||||
// 动态构建更新字段
|
||||
const allowedFields = [
|
||||
'farmName', 'farmerName', 'phone', 'deviceType', 'deviceNumber',
|
||||
'alertType', 'alertLevel', 'description', 'location', 'batteryLevel',
|
||||
'signalStrength', 'temperature', 'remarks', 'status', 'resolvedBy', 'resolvedAt'
|
||||
];
|
||||
|
||||
for (const field of allowedFields) {
|
||||
if (req.body[field] !== undefined) {
|
||||
updateFields.push(`${field} = :${field}`);
|
||||
replacements[field] = req.body[field];
|
||||
}
|
||||
}
|
||||
|
||||
if (updateFields.length === 0) {
|
||||
return res.status(400).json({ code: 400, message: '没有需要更新的字段' });
|
||||
}
|
||||
|
||||
updateFields.push('updatedAt = NOW()');
|
||||
|
||||
const updateQuery = `
|
||||
UPDATE device_warnings
|
||||
SET ${updateFields.join(', ')}
|
||||
WHERE id = :id
|
||||
`;
|
||||
|
||||
const [result] = await DeviceWarning.sequelize.query(updateQuery, {
|
||||
replacements,
|
||||
type: QueryTypes.UPDATE
|
||||
});
|
||||
|
||||
if (updatedRows === 0) {
|
||||
if (result === 0) {
|
||||
return res.status(404).json({ code: 404, message: '设备预警未找到或无更新' });
|
||||
}
|
||||
|
||||
const updatedWarning = await DeviceWarning.findByPk(id);
|
||||
res.status(200).json({ code: 200, message: '更新成功', data: updatedWarning });
|
||||
// 获取更新后的记录
|
||||
const selectQuery = `
|
||||
SELECT id, farmName, farmerName, phone, deviceType, deviceNumber,
|
||||
alertType, alertLevel, alertTime, status, description,
|
||||
location, batteryLevel, signalStrength, temperature,
|
||||
resolvedBy, resolvedAt, remarks, createdAt, updatedAt
|
||||
FROM device_warnings
|
||||
WHERE id = :id
|
||||
`;
|
||||
|
||||
const results = await DeviceWarning.sequelize.query(selectQuery, {
|
||||
replacements: { id },
|
||||
type: QueryTypes.SELECT
|
||||
});
|
||||
|
||||
res.status(200).json({ code: 200, message: '更新成功', data: results[0] });
|
||||
} catch (error) {
|
||||
console.error('更新设备预警失败:', error);
|
||||
res.status(500).json({ code: 500, message: '更新设备预警失败', error: error.message });
|
||||
@@ -98,11 +227,14 @@ exports.updateDeviceWarning = async (req, res) => {
|
||||
exports.deleteDeviceWarning = async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const deletedRows = await DeviceWarning.destroy({
|
||||
where: { id },
|
||||
|
||||
const deleteQuery = 'DELETE FROM device_warnings WHERE id = :id';
|
||||
const [result] = await DeviceWarning.sequelize.query(deleteQuery, {
|
||||
replacements: { id },
|
||||
type: QueryTypes.DELETE
|
||||
});
|
||||
|
||||
if (deletedRows === 0) {
|
||||
if (result === 0) {
|
||||
return res.status(404).json({ code: 404, message: '设备预警未找到' });
|
||||
}
|
||||
|
||||
@@ -141,32 +273,27 @@ exports.updateWarningStatus = async (req, res) => {
|
||||
// 获取预警统计
|
||||
exports.getWarningStats = async (req, res) => {
|
||||
try {
|
||||
// 分别查询每种设备类型的活跃预警数量
|
||||
const earTagCount = await DeviceWarning.count({
|
||||
where: {
|
||||
deviceType: '智能耳标',
|
||||
status: 'active'
|
||||
}
|
||||
// 使用原始SQL查询每种设备类型的活跃预警数量
|
||||
const earTagQuery = 'SELECT COUNT(*) as count FROM device_warnings WHERE deviceType = :deviceType AND status = :status';
|
||||
const earTagResult = await DeviceWarning.sequelize.query(earTagQuery, {
|
||||
replacements: { deviceType: '智能耳标', status: 'active' },
|
||||
type: QueryTypes.SELECT
|
||||
});
|
||||
|
||||
const neckbandCount = await DeviceWarning.count({
|
||||
where: {
|
||||
deviceType: '智能项圈',
|
||||
status: 'active'
|
||||
}
|
||||
const neckbandResult = await DeviceWarning.sequelize.query(earTagQuery, {
|
||||
replacements: { deviceType: '智能项圈', status: 'active' },
|
||||
type: QueryTypes.SELECT
|
||||
});
|
||||
|
||||
const hostCount = await DeviceWarning.count({
|
||||
where: {
|
||||
deviceType: '智能主机',
|
||||
status: 'active'
|
||||
}
|
||||
const hostResult = await DeviceWarning.sequelize.query(earTagQuery, {
|
||||
replacements: { deviceType: '智能主机', status: 'active' },
|
||||
type: QueryTypes.SELECT
|
||||
});
|
||||
|
||||
const result = {
|
||||
earTag: earTagCount,
|
||||
neckband: neckbandCount,
|
||||
host: hostCount
|
||||
earTag: earTagResult[0].count,
|
||||
neckband: neckbandResult[0].count,
|
||||
host: hostResult[0].count
|
||||
};
|
||||
|
||||
res.status(200).json({ code: 200, message: '获取成功', data: result });
|
||||
|
||||
Reference in New Issue
Block a user