feat(server-go): 蚕房健康画像与年度发病统计(#24)

This commit is contained in:
weijuesen
2026-08-13 13:34:13 +08:00
parent 1a6bcd27fe
commit cbcb22e851
5 changed files with 252 additions and 6 deletions
+26
View File
@@ -20,6 +20,7 @@ func RegisterTraceRoutes(rg *gin.RouterGroup, db *gorm.DB) {
write := middleware.RequirePermission(db, "trace:write")
rg.GET("/trace-records", read, listTraceRecords(db))
rg.GET("/trace-records/region-stats", read, traceRegionStats(db))
rg.GET("/trace-records/monthly-stats", read, traceMonthlyStats(db))
rg.GET("/trace-records/:id", read, getTraceRecord(db))
rg.POST("/trace-records", write, createTraceRecord(db))
rg.PATCH("/trace-records/:id", write, updateTraceRecord(db))
@@ -29,6 +30,31 @@ func RegisterTraceRoutes(rg *gin.RouterGroup, db *gorm.DB) {
rg.POST("/trace-records/:id/checklist", write, submitTraceChecklist(db))
}
// traceMonthlyStats 年度发病规律(按月聚合)
func traceMonthlyStats(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
year := time.Now().Year()
if y, err := strconv.Atoi(c.DefaultQuery("year", "0")); err == nil && y >= 2020 && y <= 2100 {
year = y
}
start := time.Date(year, 1, 1, 0, 0, 0, 0, time.Local)
end := start.AddDate(1, 0, 0)
var rows []struct {
Month string `gorm:"column:month"`
Disease string `gorm:"column:disease"`
}
db.Table("trace_records").
Select("to_char(created_at, 'YYYY-MM') AS month, disease").
Where("created_at >= ? AND created_at < ?", start, end).
Scan(&rows)
entries := make([]service.MonthDiseaseEntry, 0, len(rows))
for _, r := range rows {
entries = append(entries, service.MonthDiseaseEntry{Month: r.Month, Disease: r.Disease})
}
c.JSON(http.StatusOK, gin.H{"year": year, "stats": service.AggregateMonthlyStats(entries)})
}
}
// traceRegionStats 区域发病统计(近 N 天,按蚕房 region 聚合)
func traceRegionStats(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {