Files
cpone_dashboard/cpone-dashboard/menu/abnormal/handler.go
2026-04-30 14:27:01 +07:00

126 lines
2.9 KiB
Go

package abnormal
import (
"cpone-dashboard/menu/auth"
"cpone-dashboard/menu/projects"
"encoding/json"
"html/template"
"net/http"
)
var tmpl *template.Template
var basePath string
func SetTemplates(t *template.Template) { tmpl = t }
func SetBasePath(p string) { basePath = p }
type pageData struct {
Username string
CurrentProject projects.ProjectItem
Group string
Groups []string
Summary AbnormalSummary
StaffJSON template.JS
AgeJSON template.JS
GenderJSON template.JS
DeptJSON template.JS
}
func toJS(v any) template.JS {
b, _ := json.Marshal(v)
return template.JS(b)
}
func Index(w http.ResponseWriter, r *http.Request) {
username := auth.Username(r)
mcuID := auth.SelectedProjectID(r)
if mcuID == 0 {
http.Redirect(w, r, basePath+"/projects", http.StatusSeeOther)
return
}
project, ok, err := projects.GetUserProject(username, mcuID)
if err != nil || !ok {
http.Redirect(w, r, basePath+"/projects", http.StatusSeeOther)
return
}
group := r.URL.Query().Get("group")
groups, err := GetAbnormalGroups(mcuID)
if err != nil {
http.Error(w, "query error", http.StatusInternalServerError)
return
}
total, err := GetTotalPatients(mcuID)
if err != nil {
http.Error(w, "query error", http.StatusInternalServerError)
return
}
abnormalCount, err := GetAbnormalCount(mcuID, group)
if err != nil {
http.Error(w, "query error", http.StatusInternalServerError)
return
}
normalCount := total - abnormalCount
if normalCount < 0 {
normalCount = 0
}
rate := 0
if total > 0 {
rate = abnormalCount * 100 / total
}
ageData, err := GetAgeChartData(mcuID, group)
if err != nil {
http.Error(w, "query error", http.StatusInternalServerError)
return
}
genderData, err := GetGenderChartData(mcuID, group)
if err != nil {
http.Error(w, "query error", http.StatusInternalServerError)
return
}
deptData, err := GetDeptChartData(mcuID, group)
if err != nil {
http.Error(w, "query error", http.StatusInternalServerError)
return
}
t := tmpl
if t == nil {
http.Error(w, "template not ready", http.StatusInternalServerError)
return
}
if err := t.ExecuteTemplate(w, "base", pageData{
Username: username,
CurrentProject: project,
Group: group,
Groups: groups,
Summary: AbnormalSummary{
Total: total,
Abnormal: abnormalCount,
Normal: normalCount,
AbnormalRate: rate,
},
StaffJSON: toJS(map[string]any{
"normal": normalCount,
"abnormal": abnormalCount,
}),
AgeJSON: toJS(map[string]any{
"labels": ageData.Labels,
"abnormal": ageData.Abnormal,
}),
GenderJSON: toJS(map[string]any{
"labels": genderData.Labels,
"abnormal": genderData.Abnormal,
}),
DeptJSON: toJS(map[string]any{
"labels": deptData.Labels,
"abnormal": deptData.Abnormal,
}),
}); err != nil {
http.Error(w, "template error", http.StatusInternalServerError)
}
}