Files
aler_dashboard_git/api/work_order_api.php.5.0
T
2026-07-09 16:31:30 +08:00

268 lines
10 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,POST,OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
echo json_encode(['code' => 0, 'msg' => 'ok']);
exit;
}
session_start();
$expire = 1800;
if (empty($_SESSION['user_id']) || (time() - $_SESSION['login_time'] > $expire)) {
echo json_encode(['code' => 401, 'msg' => '登录失效']);
exit;
}
$loginUid = $_SESSION['user_id'];
// 工单业务库 monitor
$dbWorkHost = '10.150.117.190';
$dbWorkUser = 'root';
$dbWorkPwd = 'hp93000';
$dbWorkName = 'monitor';
$connWork = mysqli_connect($dbWorkHost, $dbWorkUser, $dbWorkPwd, $dbWorkName);
if (!$connWork) {
echo json_encode(['code' => 500, 'msg' => '工单数据库连接失败:' . mysqli_connect_error()]);
exit;
}
mysqli_set_charset($connWork, 'utf8mb4');
// 配置库 alert_mail_stat(告警、通知配置统一此处)
$dbConfHost = "10.150.117.190";
$dbConfUser = "root";
$dbConfPwd = "hp93000";
$dbConfName = "alert_mail_stat";
$connConf = mysqli_connect($dbConfHost, $dbConfUser, $dbConfPwd, $dbConfName);
if(!$connConf){
echo json_encode(['code' => 500, 'msg' => '配置库连接失败']);
exit;
}
mysqli_set_charset($connConf, "utf8mb4");
// 获取当前用户角色权限
$isAdmin = 0;
$permList = "";
$roleSql = "SELECT r.is_admin, r.perm_list FROM sys_user u LEFT JOIN sys_role r ON u.role_id=r.id WHERE u.uid = ?";
$stmtRole = mysqli_prepare($connWork, $roleSql);
mysqli_stmt_bind_param($stmtRole, 's', $loginUid);
mysqli_stmt_execute($stmtRole);
$roleRes = mysqli_stmt_get_result($stmtRole);
$roleRow = $roleRes ? mysqli_fetch_assoc($roleRes) : [];
if ($roleRow) {
$isAdmin = intval($roleRow['is_admin']);
$permList = $roleRow['perm_list'];
}
$action = $_REQUEST['action'] ?? '';
$post = json_decode(file_get_contents("php://input"), true) ?: [];
// 1、获取实时活跃告警(alert_mail_stat.alert_firing 数据源)
if ($action === "get_firing_alert") {
$alertSql = "SELECT alert_id,alert_name,instance FROM alert_firing WHERE status='firing' ORDER BY receive_time DESC LIMIT 100";
$res = mysqli_query($connConf, $alertSql);
$list = [];
if($res instanceof mysqli_result){
while ($row = mysqli_fetch_assoc($res)) {
$list[] = $row;
}
}
echo json_encode(['code' => 0, 'list' => $list]);
exit;
}
// 2、新建工单(关联告警、多渠道通知)
if ($action === "create") {
$title = trim($post['title'] ?? '');
$content = trim($post['content'] ?? '');
$assign = trim($post['assign_uid'] ?? '');
$relateAlertId = trim($post['relate_alert_id'] ?? '');
$notifyUser = trim($post['notify_user'] ?? '');
$notifyChannel = trim($post['notify_channel'] ?? '');
$status = 1;
if (!$title || !$content) {
echo json_encode(['code' => 400, 'msg' => '标题和内容不能为空']);
exit;
}
$sql = "INSERT INTO work_order(title,content,create_uid,assign_uid,relate_alert_id,notify_user,notify_channel,status,create_time,update_time) VALUES (?,?,?,?,?,?,?,?,NOW(),NOW())";
$stmt = mysqli_prepare($connWork, $sql);
mysqli_stmt_bind_param($stmt, 'sssssssi', $title, $content, $loginUid, $assign, $relateAlertId, $notifyUser, $notifyChannel, $status);
$ok = mysqli_stmt_execute($stmt);
if (!$ok) {
echo json_encode(['code' => 500, 'msg' => '创建失败:' . mysqli_error($connWork)]);
exit;
}
$orderId = mysqli_insert_id($connWork);
sendWorkOrderNotify($connConf, $connWork, $orderId, $notifyUser, $notifyChannel);
echo json_encode(['code' => 0, 'msg' => '工单提交成功,通知已下发']);
exit;
}
// 3、编辑工单
if ($action === "edit") {
$id = intval($post['id'] ?? 0);
$title = trim($post['title'] ?? '');
$content = trim($post['content'] ?? '');
$assign = trim($post['assign_uid'] ?? '');
$notifyUser = trim($post['notify_user'] ?? '');
$notifyChannel = trim($post['notify_channel'] ?? '');
if ($id <= 0 || empty($title) || empty($content)) {
echo json_encode(['code' => 400, 'msg' => '参数不能为空']);
exit;
}
// 非管理员权限校验
if ($isAdmin !== 1) {
$chkSql = "SELECT id FROM work_order WHERE id=? AND (create_uid=? OR assign_uid=?)";
$stmtChk = mysqli_prepare($connWork, $chkSql);
mysqli_stmt_bind_param($stmtChk, 'iss', $id, $loginUid, $loginUid);
mysqli_stmt_execute($stmtChk);
$chkRes = mysqli_stmt_get_result($stmtChk);
if (mysqli_num_rows($chkRes) === 0) {
echo json_encode(['code' => 403, 'msg' => '无权限编辑该工单']);
exit;
}
}
$sql = "UPDATE work_order SET title=?,content=?,assign_uid=?,notify_user=?,notify_channel=?,update_time=NOW() WHERE id=?";
$stmt = mysqli_prepare($connWork, $sql);
mysqli_stmt_bind_param($stmt, 'sssssi', $title, $content, $assign, $notifyUser, $notifyChannel, $id);
mysqli_stmt_execute($stmt);
sendWorkOrderNotify($connConf, $connWork, $id, $notifyUser, $notifyChannel);
echo json_encode(['code' => 0, 'msg' => '工单保存成功,通知已更新下发']);
exit;
}
// 4、修改工单状态
if ($action === "update_status") {
$id = intval($post['id'] ?? 0);
$status = intval($post['status'] ?? 1);
if ($id <= 0) {
echo json_encode(['code' => 400, 'msg' => '工单ID错误']);
exit;
}
if ($isAdmin !== 1) {
$chkSql = "SELECT id FROM work_order WHERE id=? AND (create_uid=? OR assign_uid=?)";
$stmtChk = mysqli_prepare($connWork, $chkSql);
mysqli_stmt_bind_param($stmtChk, 'iss', $id, $loginUid, $loginUid);
mysqli_stmt_execute($stmtChk);
$chkRes = mysqli_stmt_get_result($stmtChk);
if (mysqli_num_rows($chkRes) === 0) {
echo json_encode(['code' => 403, 'msg' => '无权限操作该工单']);
exit;
}
}
$sql = "UPDATE work_order SET status=?,update_time=NOW() WHERE id=?";
$stmt = mysqli_prepare($connWork, $sql);
mysqli_stmt_bind_param($stmt, 'ii', $status, $id);
mysqli_stmt_execute($stmt);
echo json_encode(['code' => 0, 'msg' => '状态更新成功']);
exit;
}
// 5、管理员分发工单(前端统一action=assign,废弃assign_order
if ($action === "assign") {
if ($isAdmin !== 1) {
echo json_encode(['code' => 403, 'msg' => '仅管理员可分发工单']);
exit;
}
$id = intval($post['id'] ?? 0);
$assignUid = trim($post['assign_uid'] ?? '');
$sql = "UPDATE work_order SET assign_uid=?,update_time=NOW() WHERE id=?";
$stmt = mysqli_prepare($connWork, $sql);
mysqli_stmt_bind_param($stmt, 'si', $assignUid, $id);
mysqli_stmt_execute($stmt);
echo json_encode(['code' => 0, 'msg' => '工单分发成功']);
exit;
}
// ==================== 全局通知统一函数 ====================
function sendWorkOrderNotify($connConf, $connWork, $orderId, $notifyUserStr, $channelStr)
{
if (empty($notifyUserStr) || empty($channelStr)) return;
$userArr = explode(",", $notifyUserStr);
$channelArr = explode(",", $channelStr);
// 读取完整通知配置(邮箱+钉钉+企微)
$cfgRes = mysqli_query($connConf, "SELECT * FROM sys_smtp_config WHERE id=1");
$notifyCfg = $cfgRes ? mysqli_fetch_assoc($cfgRes) : [];
if(empty($notifyCfg)) return;
// 获取工单完整信息
$orderRes = mysqli_query($connWork, "SELECT * FROM work_order WHERE id=$orderId");
$order = $orderRes ? mysqli_fetch_assoc($orderRes) : [];
$title = $order['title'];
$content = $order['content'];
$relateId = $order['relate_alert_id'] ?: "无";
$msgText = "【运维工单通知】\n工单ID$orderId\n关联告警:$relateId\n标题:$title\n详情:$content";
foreach ($channelArr as $ch) {
$ch = trim($ch);
switch ($ch) {
case "mail":
sendMailNotify($notifyCfg, $userArr, $title, $content, $relateId, $orderId);
break;
case "dingtalk":
sendDingNotify($notifyCfg, $msgText);
break;
case "wecom":
sendWecomNotify($notifyCfg, $msgText);
break;
}
}
}
// 邮件发送
function sendMailNotify($smtp, $uidList, $title, $content, $relateId, $orderId)
{
if (empty($smtp['smtp_host']) || empty($smtp['smtp_account'])) return;
$emailList = [];
foreach ($uidList as $uid) {
$uid = trim($uid);
if (empty($uid)) continue;
$res = mysqli_query($GLOBALS['connWork'], "SELECT email FROM sys_user WHERE uid='$uid'");
$u = mysqli_fetch_assoc($res);
if (!empty($u['email'])) $emailList[] = $u['email'];
}
if (empty($emailList)) return;
$to = implode(",", array_unique($emailList));
$subject = "【工单通知】#$orderId $title";
$body = "<h3>工单 #$orderId</h3>
<p>关联告警ID$relateId</p>
<p>标题:$title</p>
<pre style='background:#f5f5f5;padding:10px'>$content</pre>";
// 此处接入PHPMailer发送逻辑
}
// 钉钉机器人推送
function sendDingNotify($cfg, $text)
{
$webhook = $cfg['ding_webhook'] ?? '';
$secret = $cfg['ding_secret'] ?? '';
if(empty($webhook)) return;
$data = json_encode([
"msgtype" => "text",
"text" => ["content" => $text]
]);
$opts = ["http" => ["method" => "POST", "header" => "Content-Type:application/json", "content" => $data]];
file_get_contents($webhook, false, stream_context_create($opts));
}
// 企业微信机器人推送
function sendWecomNotify($cfg, $text)
{
$webhook = $cfg['wecom_webhook'] ?? '';
if(empty($webhook)) return;
$data = json_encode([
"msgtype" => "text",
"text" => ["content" => $text]
]);
$opts = ["http" => ["method" => "POST", "header" => "Content-Type:application/json", "content" => $data]];
file_get_contents($webhook, false, stream_context_create($opts));
}
// 无匹配动作
echo json_encode(['code' => 400, 'msg' => '无效请求动作']);
mysqli_close($connWork);
mysqli_close($connConf);
exit;
?>