alarm.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package model
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "smart-government-management/consts"
  8. "smart-government-management/errors"
  9. "time"
  10. "github.com/jaryhe/gopkgs/logger"
  11. "github.com/jinzhu/gorm"
  12. "go.uber.org/zap"
  13. )
  14. type TAlarm struct {
  15. Id int64 `gorm:"primary_key"`
  16. ProjectId int64 `gorm:"column:project_id"`
  17. Sn string `gorm:"column:sn"`
  18. AlarmCode string `gorm:"column:alarm_code"`
  19. AlarmReason string `gorm:"column:alarm_reason"`
  20. IsHandle bool `gorm:"column:is_handle"`
  21. Time time.Time `gorm:"column:time"`
  22. CreatedAt string `gorm:"column:created_at"`
  23. UpdatedAt string `json:"updated_at"`
  24. DeviceCode int
  25. }
  26. func (TAlarm) TableName() string {
  27. return "t_alarm"
  28. }
  29. func (p *TAlarm) Insert(db *gorm.DB) error {
  30. timeNow := time.Now().Format(consts.TimeSecondLayOut)
  31. p.CreatedAt = timeNow
  32. p.UpdatedAt = timeNow
  33. err := db.Create(p).Error
  34. if err != nil {
  35. fields, _ := json.Marshal(*p)
  36. logger.Error("mysql",
  37. zap.String("sql", "insert into t_alarm"),
  38. zap.String("fields", string(fields)),
  39. zap.String("error", err.Error()))
  40. return errors.DataBaseError
  41. }
  42. return nil
  43. }
  44. func (p *TAlarm) Delete(db *gorm.DB, filter map[string]interface{}) error {
  45. err := db.Where(filter).Delete(p).Error
  46. if err != nil {
  47. fields, _ := json.Marshal(filter)
  48. logger.Error("mysql",
  49. zap.String("sql", "delete from t_alarm"),
  50. zap.String("fields", string(fields)),
  51. zap.String("error", err.Error()))
  52. return errors.DataBaseError
  53. }
  54. return nil
  55. }
  56. func (p *TAlarm) Update(db *gorm.DB, where map[string]interface{}, values map[string]interface{}) error {
  57. cond, val, err := whereBuild(where)
  58. if err != nil {
  59. return err
  60. }
  61. return db.Table(p.TableName()).Where(cond, val...).Updates(values).Error
  62. }
  63. // 通过结构体变量更新字段值, gorm库会忽略零值字段。就是字段值等于0, nil, "", false这些值会被忽略掉,不会更新。如果想更新零值,可以使用map类型替代结构体。
  64. func (p *TAlarm) UpdateSome(db *gorm.DB, filed map[string]interface{}) error {
  65. if filed == nil {
  66. return errors.ParamsError
  67. }
  68. timeNow := time.Now().Format(consts.TimeSecondLayOut)
  69. filed["updated_at"] = timeNow
  70. err := db.Model(p).Updates(filed).Error
  71. if err != nil {
  72. fields, _ := json.Marshal(filed)
  73. logger.Error("mysql",
  74. zap.String("sql", "update t_alarm"),
  75. zap.String("fields", string(fields)),
  76. zap.String("error", err.Error()))
  77. return errors.DataBaseError
  78. }
  79. return nil
  80. }
  81. func (p *TAlarm) Query(db *gorm.DB, filter map[string]interface{}) error {
  82. err := db.Where(filter).Find(p).Error
  83. if err != nil {
  84. fields, _ := json.Marshal(filter)
  85. logger.Error("mysql",
  86. zap.String("sql", "select from t_alarm"),
  87. zap.String("fields", string(fields)),
  88. zap.String("error", err.Error()))
  89. return err
  90. }
  91. return nil
  92. }
  93. func (p *TAlarm) Count(db *gorm.DB, where map[string]interface{}) (int64, error) {
  94. if len(where) > 0 {
  95. cond, val, err := whereBuild(where)
  96. if err != nil {
  97. return 0, err
  98. }
  99. ret := int64(0)
  100. err = db.Table(p.TableName()).Where(cond, val...).Count(&ret).Error
  101. if err != nil {
  102. fields, _ := json.Marshal(where)
  103. logger.Error("mysql",
  104. zap.String("sql", "select count from t_alarm"),
  105. zap.String("fields", string(fields)),
  106. zap.String("error", err.Error()))
  107. return ret, errors.DataBaseError
  108. }
  109. return ret, err
  110. }
  111. ret := int64(0)
  112. err := db.Table(p.TableName()).Count(&ret).Error
  113. if err != nil {
  114. fields, _ := json.Marshal(where)
  115. logger.Error("mysql",
  116. zap.String("sql", "select count from t_alarm"),
  117. zap.String("fields", string(fields)),
  118. zap.String("error", err.Error()))
  119. return ret, errors.DataBaseError
  120. }
  121. return ret, err
  122. }
  123. type AlarmListRequest struct {
  124. Page int32
  125. PageSize int32
  126. IsHandle int32
  127. Start int64
  128. End int64
  129. Filter string
  130. ProjectId int64
  131. DeviceCode int32
  132. }
  133. type AlarmListItem struct {
  134. TAlarm
  135. DeviceCode int32
  136. Name string
  137. ProjectName string
  138. SafetyRecordNo string
  139. }
  140. func AlarmListMoreSql(req *AlarmListRequest)(string, string) {
  141. sql := fmt.Sprintf("select t1.*, t2.device_code, t2.name, t3.name as project_name, t3.safety_record_no from t_alarm as t1 left join t_device as t2 on t1.sn=t2.sn and t1.device_code=t2.device_code and t1.project_id=t2.project_id left join t_project as t3 on t3.id=t1.project_id")
  142. countSql := fmt.Sprintf("select count(1) as count from t_alarm as t1 left join t_device as t2 on t1.sn=t2.sn and t1.device_code=t2.device_code and t1.project_id=t2.project_id left join t_project as t3 on t3.id=t1.project_id")
  143. whereArray := []string{}
  144. where := ""
  145. whereArray = append(whereArray, fmt.Sprintf("t2.sn is not null"))
  146. whereArray = append(whereArray, fmt.Sprintf("t1.first = 1"))
  147. if req.Filter != "" {
  148. whereArray = append(whereArray, fmt.Sprintf("(t1.sn like '%%%s%%' or t2.name like '%%%s%%')", req.Filter, req.Filter))
  149. }
  150. if req.ProjectId > 0 {
  151. whereArray = append(whereArray, fmt.Sprintf("(t1.project_id=%d)", req.ProjectId))
  152. }
  153. if req.DeviceCode > 0 {
  154. whereArray = append(whereArray, fmt.Sprintf("(t1.device_code=%d)", req.DeviceCode))
  155. }
  156. if req.IsHandle == 1 {
  157. whereArray = append(whereArray, fmt.Sprintf("t1.is_handle=1"))
  158. } else if req.IsHandle == 2 {
  159. whereArray = append(whereArray, fmt.Sprintf("t1.is_handle=0"))
  160. }
  161. if req.Start > 0 {
  162. whereArray = append(whereArray, fmt.Sprintf("t1.time >= '%s'", time.Unix(req.Start, 0).Format("2006-01-02 15:04:05")))
  163. }
  164. if req.End > 0 {
  165. whereArray = append(whereArray, fmt.Sprintf("t1.time < '%s'", time.Unix(req.End, 0).Format("2006-01-02 15:04:05")))
  166. }
  167. for _, v := range whereArray {
  168. if where == "" {
  169. where = fmt.Sprintf(" where %s", v)
  170. continue
  171. }
  172. where = fmt.Sprintf("%s and %s", where, v)
  173. }
  174. offset := (req.Page - 1) *req.PageSize
  175. limit := req.PageSize
  176. sql = fmt.Sprintf("%s %s order by t1.time desc limit %d offset %d", sql, where, limit, offset)
  177. countSql = fmt.Sprintf("%s %s", countSql, where)
  178. return sql, countSql
  179. }
  180. func (p *TAlarm) ListMore(db *gorm.DB, req *AlarmListRequest) (list []AlarmListItem, total int64, err error) {
  181. type ResultCount struct {
  182. Count int64
  183. }
  184. array := []ResultCount{}
  185. ret := []AlarmListItem{}
  186. sql, countSql := AlarmListMoreSql(req)
  187. err = db.Raw(countSql).Scan(&array).Error
  188. if err != nil {
  189. logger.Error("mysql",
  190. zap.String("sql", countSql),
  191. zap.String("error", err.Error()))
  192. return nil, 0, errors.DataBaseError
  193. }
  194. if len(array) == 0 {
  195. return nil, 0, nil
  196. }
  197. if array[0].Count == 0 {
  198. return nil, 0, nil
  199. }
  200. err = db.Raw(sql).Scan(&ret).Error
  201. if err != nil {
  202. logger.Error("mysql",
  203. zap.String("sql", sql),
  204. zap.String("error", err.Error()))
  205. return nil, array[0].Count, errors.DataBaseError
  206. }
  207. return ret, array[0].Count, nil
  208. }
  209. func (p *TAlarm) List(db *gorm.DB, where map[string]interface{}, page int32, pagesize int32) (list []TAlarm, err error) {
  210. offset := (page - 1) * pagesize
  211. if len(where) > 0 {
  212. cond, val, err := whereBuild(where)
  213. if err != nil {
  214. return list, err
  215. }
  216. err = db.Table(p.TableName()).Where(cond, val...).Limit(PageSize).Offset(offset).Find(&list).Error
  217. if err != nil {
  218. fields, _ := json.Marshal(where)
  219. logger.Error("mysql",
  220. zap.String("sql", "select * from t_alarm"),
  221. zap.String("fields", string(fields)),
  222. zap.String("error", err.Error()))
  223. return list, errors.DataBaseError
  224. }
  225. return list, err
  226. }
  227. err = db.Table(p.TableName()).Limit(10).Offset(page).Find(&list).Error
  228. if err != nil {
  229. fields, _ := json.Marshal(where)
  230. logger.Error("mysql",
  231. zap.String("sql", "select * from t_alarm"),
  232. zap.String("fields", string(fields)),
  233. zap.String("error", err.Error()))
  234. return list, errors.DataBaseError
  235. }
  236. return list, err
  237. }
  238. type AlarmProjectItem struct {
  239. ProjectId int64
  240. Total int64
  241. Handled int64
  242. ProjectName string
  243. }
  244. func AlarmProjectStatistic(db *gorm.DB) ([]AlarmProjectItem, error) {
  245. ret := []AlarmProjectItem{}
  246. sql := fmt.Sprintf("select sum(1) as total, sum(is_handle=1) as handled, t1.project_id, t2.name as project_name from t_alarm as t1 left join t_project as t2 on t1.project_id=t2.id where t1.first=1 group by t1.project_id")
  247. err := db.Raw(sql).Scan(&ret).Error
  248. if err != nil {
  249. logger.Error("mysql",
  250. zap.String("sql", sql),
  251. zap.String("error", err.Error()))
  252. return nil, errors.DataBaseError
  253. }
  254. return ret, nil
  255. }
  256. type AlarmReasonItem struct {
  257. Total int64
  258. Reason string
  259. Handled int64
  260. }
  261. func AlarmReasonStatistic(db *gorm.DB)([]AlarmReasonItem, error) {
  262. sql := fmt.Sprintf("select sum(1) as total, sum(is_handle) as handled, alarm_reason as reason from t_alarm where first=1 group by alarm_code")
  263. ret := []AlarmReasonItem{}
  264. err := db.Raw(sql).Scan(&ret).Error
  265. if err != nil {
  266. logger.Error("mysql",
  267. zap.String("sql", sql),
  268. zap.String("error", err.Error()))
  269. return nil, errors.DataBaseError
  270. }
  271. return ret, nil
  272. }
  273. type AlarmDeviceStatisticItem struct {
  274. Count int64
  275. DeviceCode uint32
  276. }
  277. func AlarmDeviceStatistic(db *gorm.DB)([]AlarmDeviceStatisticItem, error) {
  278. sql := fmt.Sprintf("select sum(1) as count, device_code from t_alarm where first=1 and is_handle<>1 group by device_code")
  279. ret := []AlarmDeviceStatisticItem{}
  280. err := db.Raw(sql).Scan(&ret).Error
  281. if err != nil {
  282. logger.Error("mysql",
  283. zap.String("sql", sql),
  284. zap.String("error", err.Error()))
  285. return nil, errors.DataBaseError
  286. }
  287. return ret, nil
  288. }
  289. var timeLayOut = "2006-01-02 15:04:05"
  290. func getDayTime(now time.Time)(start, end string) {
  291. nowStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
  292. nowEnd := nowStart.Add(24*time.Hour)
  293. return nowStart.Format(timeLayOut), nowEnd.Format(timeLayOut)
  294. }
  295. func getMonthTime(now time.Time)(start string, end string) {
  296. nowStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
  297. nowEnd := nowStart
  298. start = nowStart.Format(timeLayOut)
  299. for {
  300. nowEnd = nowEnd.Add(24*time.Hour)
  301. end = nowEnd.Format(timeLayOut)
  302. if nowEnd.Month() != nowStart.Month() {
  303. return start, end
  304. }
  305. }
  306. return start, end
  307. }
  308. func AlarmIncreaseStatistic(db *gorm.DB)(dayIncrease int64, monthIncrease int64, total int64, err error) {
  309. type Result struct {
  310. Count int64
  311. }
  312. ret := []Result{}
  313. now := time.Now()
  314. dayStart, dayEnd := getDayTime(now)
  315. monthStart, monthEnd := getMonthTime(now)
  316. // 当天新增
  317. sql := fmt.Sprintf("select count(1) as count from t_alarm where first = 1 and is_handle<>1 and time >= '%s' and time < '%s'", dayStart, dayEnd)
  318. err = db.Raw(sql).Scan(&ret).Error
  319. if err != nil {
  320. logger.Error("mysql",
  321. zap.String("sql", sql),
  322. zap.String("error", err.Error()))
  323. return 0, 0, 0, errors.DataBaseError
  324. }
  325. if len(ret) > 0 {
  326. dayIncrease = ret[0].Count
  327. }
  328. ret = []Result{}
  329. // 当月新增
  330. sql = fmt.Sprintf("select count(1) as count from t_alarm where first = 1 and is_handle<>1 and time >= '%s' and time < '%s'", monthStart, monthEnd)
  331. err = db.Raw(sql).Scan(&ret).Error
  332. if err != nil {
  333. logger.Error("mysql",
  334. zap.String("sql", sql),
  335. zap.String("error", err.Error()))
  336. return 0, 0, 0, errors.DataBaseError
  337. }
  338. if len(ret) > 0 {
  339. monthIncrease = ret[0].Count
  340. }
  341. ret = []Result{}
  342. // 总数
  343. sql = fmt.Sprintf("select count(1) as count from t_alarm where first = 1 and is_handle<>1")
  344. err = db.Raw(sql).Scan(&ret).Error
  345. if err != nil {
  346. logger.Error("mysql",
  347. zap.String("sql", sql),
  348. zap.String("error", err.Error()))
  349. return 0, 0, 0, errors.DataBaseError
  350. }
  351. if len(ret) > 0 {
  352. total = ret[0].Count
  353. }
  354. return
  355. }
  356. type AlarmPercentStatisticItem struct {
  357. Count int64
  358. HandleCount int64
  359. Date time.Time
  360. }
  361. func AlarmPercentStatistic(db *gorm.DB, start string, end string) (list []AlarmPercentStatisticItem, err error) {
  362. sql := fmt.Sprintf("select sum(1) as count, sum(is_handle=1) as handle_count, date(time) as date from t_alarm where first=1 and time >= '%s' and time < '%s' group by date(time)", start, end)
  363. ret := []AlarmPercentStatisticItem{}
  364. err = db.Raw(sql).Scan(&ret).Error
  365. if err != nil {
  366. logger.Error("mysql",
  367. zap.String("sql", sql),
  368. zap.String("error", err.Error()))
  369. return nil, errors.DataBaseError
  370. }
  371. return ret, nil
  372. }