routes_alert_notify_configs.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import { Hono } from "hono";
  2. import debug from "debug";
  3. import type {
  4. AlertNotifyConfig,
  5. } from "../client/share/monitorTypes.ts";
  6. import {
  7. EnableStatus,
  8. DeleteStatus,
  9. } from "../client/share/types.ts";
  10. import type { Variables, WithAuth } from "./middlewares.ts";
  11. const log = {
  12. api: debug("api:monitor"),
  13. };
  14. // 告警通知配置路由
  15. export function createAlertNotifyConfigsRoutes(withAuth: WithAuth) {
  16. const alertNotifyConfigsRoutes = new Hono<{ Variables: Variables }>();
  17. // 获取告警通知配置列表
  18. alertNotifyConfigsRoutes.get("/", withAuth, async (c) => {
  19. try {
  20. const apiClient = c.get('apiClient');
  21. // 获取分页参数
  22. const page = Number(c.req.query("page")) || 1;
  23. const pageSize = Number(c.req.query("pageSize")) || 10;
  24. const offset = (page - 1) * pageSize;
  25. // 获取筛选参数
  26. const deviceId = c.req.query("device_id")
  27. ? Number(c.req.query("device_id"))
  28. : null;
  29. const alertLevel = c.req.query("alert_level")
  30. ? Number(c.req.query("alert_level"))
  31. : null;
  32. const notifyType = c.req.query("notify_type");
  33. const isEnabled = c.req.query("is_enabled")
  34. ? Number(c.req.query("is_enabled"))
  35. : null;
  36. // 构建查询
  37. let query = apiClient.database
  38. .table("alert_notify_configs")
  39. .where("is_deleted", DeleteStatus.NOT_DELETED)
  40. .orderBy("id", "desc");
  41. // 应用筛选条件
  42. if (deviceId) {
  43. query = query.where("device_id", deviceId);
  44. }
  45. if (alertLevel !== null) {
  46. query = query.where("alert_level", alertLevel);
  47. }
  48. if (notifyType) {
  49. query = query.where("notify_type", notifyType);
  50. }
  51. if (isEnabled !== null) {
  52. query = query.where("is_enabled", isEnabled);
  53. }
  54. // 获取总记录数
  55. const total = await query.clone().count();
  56. // 获取分页数据
  57. const data = await query.limit(pageSize).offset(offset);
  58. return c.json({
  59. data,
  60. total: Number(total),
  61. page,
  62. pageSize,
  63. });
  64. } catch (error) {
  65. log.api("获取告警通知配置失败:", error);
  66. return c.json({ error: "获取告警通知配置失败" }, 500);
  67. }
  68. });
  69. // 获取单个告警通知配置
  70. alertNotifyConfigsRoutes.get("/:id", withAuth, async (c) => {
  71. try {
  72. const id = Number(c.req.param("id"));
  73. if (!id || isNaN(id)) {
  74. return c.json({ error: "无效的通知配置ID" }, 400);
  75. }
  76. const apiClient = c.get('apiClient');
  77. const config = await apiClient.database
  78. .table("alert_notify_configs")
  79. .where("id", id)
  80. .where("is_deleted", DeleteStatus.NOT_DELETED)
  81. .first();
  82. if (!config) {
  83. return c.json({ error: "通知配置不存在" }, 404);
  84. }
  85. // 处理JSON字段
  86. try {
  87. config.notify_users = config.notify_users
  88. ? JSON.parse(config.notify_users)
  89. : [];
  90. } catch (parseError) {
  91. log.api(`解析通知用户JSON失败 (配置ID: ${config.id}):`, parseError);
  92. config.notify_users = [];
  93. }
  94. return c.json(config);
  95. } catch (error) {
  96. log.api("获取告警通知配置详情失败:", error);
  97. return c.json({ error: "获取告警通知配置详情失败" }, 500);
  98. }
  99. });
  100. // 创建告警通知配置
  101. alertNotifyConfigsRoutes.post("/", withAuth, async (c) => {
  102. try {
  103. const data = (await c.req.json()) as Partial<AlertNotifyConfig>;
  104. // 验证必填字段
  105. if (!data.device_id) {
  106. return c.json({ error: "设备ID不能为空" }, 400);
  107. }
  108. if (data.alert_level === undefined || data.alert_level === null) {
  109. return c.json({ error: "告警等级不能为空" }, 400);
  110. }
  111. if (!data.notify_type) {
  112. return c.json({ error: "通知类型不能为空" }, 400);
  113. }
  114. if (!data.notify_users || data.notify_users.length === 0) {
  115. return c.json({ error: "通知用户不能为空" }, 400);
  116. }
  117. const apiClient = c.get('apiClient');
  118. // 检查设备是否存在
  119. const device = await apiClient.database
  120. .table("zichan_info")
  121. .where("id", data.device_id)
  122. .where("is_deleted", DeleteStatus.NOT_DELETED)
  123. .first();
  124. if (!device) {
  125. return c.json({ error: "设备不存在" }, 404);
  126. }
  127. // 序列化JSON字段
  128. const insertData = {
  129. ...data,
  130. notify_users: JSON.stringify(data.notify_users),
  131. is_enabled:
  132. data.is_enabled !== undefined ? data.is_enabled : EnableStatus.ENABLED,
  133. created_at: apiClient.database.fn.now(),
  134. updated_at: apiClient.database.fn.now(),
  135. };
  136. // 插入通知配置
  137. const [id] = await apiClient.database
  138. .table("alert_notify_configs")
  139. .insert(insertData);
  140. // 获取插入的数据
  141. const [insertedConfig] = await apiClient.database
  142. .table("alert_notify_configs")
  143. .where("id", id);
  144. // 处理返回的JSON字段
  145. try {
  146. const parsedConfig = {
  147. ...insertedConfig,
  148. notify_users: insertedConfig.notify_users
  149. ? JSON.parse(insertedConfig.notify_users)
  150. : [],
  151. };
  152. return c.json({
  153. message: "告警通知配置创建成功",
  154. data: parsedConfig,
  155. });
  156. } catch (parseError) {
  157. log.api(
  158. `解析通知用户JSON失败 (配置ID: ${insertedConfig.id}):`,
  159. parseError
  160. );
  161. return c.json({
  162. message: "告警通知配置创建成功,但解析通知用户数据失败",
  163. data: {
  164. ...insertedConfig,
  165. notify_users: [],
  166. },
  167. });
  168. }
  169. } catch (error) {
  170. log.api("创建告警通知配置失败:", error);
  171. return c.json({ error: "创建告警通知配置失败" }, 500);
  172. }
  173. });
  174. // 更新告警通知配置
  175. alertNotifyConfigsRoutes.put("/:id", withAuth, async (c) => {
  176. try {
  177. const id = Number(c.req.param("id"));
  178. if (!id || isNaN(id)) {
  179. return c.json({ error: "无效的通知配置ID" }, 400);
  180. }
  181. const data = (await c.req.json()) as Partial<AlertNotifyConfig>;
  182. const apiClient = c.get('apiClient');
  183. // 检查通知配置是否存在
  184. const config = await apiClient.database
  185. .table("alert_notify_configs")
  186. .where("id", id)
  187. .where("is_deleted", DeleteStatus.NOT_DELETED)
  188. .first();
  189. if (!config) {
  190. return c.json({ error: "通知配置不存在" }, 404);
  191. }
  192. // 如果更改了设备ID,检查设备是否存在
  193. if (data.device_id && data.device_id !== config.device_id) {
  194. const device = await apiClient.database
  195. .table("zichan_info")
  196. .where("id", data.device_id)
  197. .where("is_deleted", DeleteStatus.NOT_DELETED)
  198. .first();
  199. if (!device) {
  200. return c.json({ error: "设备不存在" }, 404);
  201. }
  202. }
  203. // 处理JSON字段
  204. const updateData = { ...data };
  205. if (data.notify_users) {
  206. updateData.notify_users = JSON.stringify(data.notify_users) as any;
  207. }
  208. // 更新通知配置
  209. await apiClient.database
  210. .table("alert_notify_configs")
  211. .where("id", id)
  212. .update({
  213. ...updateData,
  214. updated_at: apiClient.database.fn.now(),
  215. });
  216. // 获取更新后的数据
  217. const [updatedConfig] = await apiClient.database
  218. .table("alert_notify_configs")
  219. .where("id", id);
  220. // 处理返回的JSON字段
  221. try {
  222. const parsedConfig = {
  223. ...updatedConfig,
  224. notify_users: updatedConfig.notify_users
  225. ? JSON.parse(updatedConfig.notify_users)
  226. : [],
  227. };
  228. return c.json({
  229. message: "告警通知配置更新成功",
  230. data: parsedConfig,
  231. });
  232. } catch (parseError) {
  233. log.api(
  234. `解析通知用户JSON失败 (配置ID: ${updatedConfig.id}):`,
  235. parseError
  236. );
  237. return c.json({
  238. message: "告警通知配置更新成功,但解析通知用户数据失败",
  239. data: {
  240. ...updatedConfig,
  241. notify_users: [],
  242. },
  243. });
  244. }
  245. } catch (error) {
  246. log.api("更新告警通知配置失败:", error);
  247. return c.json({ error: "更新告警通知配置失败" }, 500);
  248. }
  249. });
  250. // 删除告警通知配置
  251. alertNotifyConfigsRoutes.delete("/:id", withAuth, async (c) => {
  252. try {
  253. const id = Number(c.req.param("id"));
  254. if (!id || isNaN(id)) {
  255. return c.json({ error: "无效的通知配置ID" }, 400);
  256. }
  257. const apiClient = c.get('apiClient');
  258. // 检查通知配置是否存在
  259. const config = await apiClient.database
  260. .table("alert_notify_configs")
  261. .where("id", id)
  262. .where("is_deleted", DeleteStatus.NOT_DELETED)
  263. .first();
  264. if (!config) {
  265. return c.json({ error: "通知配置不存在" }, 404);
  266. }
  267. // 软删除通知配置
  268. await apiClient.database
  269. .table("alert_notify_configs")
  270. .where("id", id)
  271. .update({
  272. is_deleted: DeleteStatus.DELETED,
  273. updated_at: apiClient.database.fn.now(),
  274. });
  275. return c.json({
  276. message: "告警通知配置删除成功",
  277. id,
  278. });
  279. } catch (error) {
  280. log.api("删除告警通知配置失败:", error);
  281. return c.json({ error: "删除告警通知配置失败" }, 500);
  282. }
  283. });
  284. return alertNotifyConfigsRoutes;
  285. }