forked from longtao.wu/droboticflow
256 lines
8.0 KiB
Go
256 lines
8.0 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"droboticflow/internal/domain"
|
|
"droboticflow/internal/productionstats"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func (s *server) productionAdmin(w http.ResponseWriter, r *http.Request) (*authenticatedPrincipal, bool) {
|
|
p, ok := currentPrincipal(r)
|
|
if !ok || !isOrganizationAdmin(p) {
|
|
renderJSON(w, http.StatusForbidden, map[string]string{"error": "platform administrator required"})
|
|
return nil, false
|
|
}
|
|
return p, true
|
|
}
|
|
func (s *server) handleProductionScope(w http.ResponseWriter, r *http.Request) {
|
|
p, ok := s.productionAdmin(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
org := s.requestOrganizationID(r)
|
|
projects, err := s.store.ListProjectsByOrganization(r.Context(), org)
|
|
if err != nil {
|
|
renderError(w, 500, err)
|
|
return
|
|
}
|
|
scope, err := s.store.GetProductionStatsScope(r.Context(), org)
|
|
if err != nil {
|
|
renderError(w, 500, err)
|
|
return
|
|
}
|
|
if r.Method == http.MethodPut {
|
|
var input productionstats.Scope
|
|
if err = json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&input); err != nil {
|
|
renderError(w, 400, err)
|
|
return
|
|
}
|
|
allowed := map[string]bool{}
|
|
for _, project := range projects {
|
|
allowed[project.ID] = true
|
|
}
|
|
ids := []string{}
|
|
seen := map[string]bool{}
|
|
for _, id := range input.ProjectIDs {
|
|
if !allowed[id] {
|
|
renderJSON(w, 400, map[string]string{"error": "统计范围包含无权限或已删除的项目"})
|
|
return
|
|
}
|
|
if !seen[id] {
|
|
seen[id] = true
|
|
ids = append(ids, id)
|
|
}
|
|
}
|
|
sort.Strings(ids)
|
|
next := productionstats.Scope{ProjectIDs: ids, Revision: input.Revision + 1, UpdatedAt: time.Now().UTC().Format(time.RFC3339Nano), UpdatedBy: p.User.ID}
|
|
saved, saveErr := s.store.SaveProductionStatsScope(r.Context(), org, next, input.Revision)
|
|
if saveErr != nil {
|
|
renderError(w, 500, saveErr)
|
|
return
|
|
}
|
|
if !saved {
|
|
renderJSON(w, 409, map[string]string{"error": "统计范围已被其他管理员修改,请重新加载"})
|
|
return
|
|
}
|
|
scope = next
|
|
}
|
|
options := []map[string]string{}
|
|
for _, project := range projects {
|
|
options = append(options, map[string]string{"id": project.ID, "name": project.Name, "status": string(project.Status)})
|
|
}
|
|
renderJSON(w, 200, map[string]any{"scope": scope, "projects": options})
|
|
}
|
|
func (s *server) handleProductionDashboard(w http.ResponseWriter, r *http.Request) {
|
|
if _, ok := s.productionAdmin(w, r); !ok {
|
|
return
|
|
}
|
|
started := time.Now().UTC()
|
|
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
|
defer cancel()
|
|
org := s.requestOrganizationID(r)
|
|
scope, err := s.store.GetProductionStatsScope(ctx, org)
|
|
if err != nil {
|
|
renderError(w, 500, err)
|
|
return
|
|
}
|
|
params := r.URL.Query()
|
|
q, err := productionstats.ParseQuery(params.Get("view"), params.Get("from"), params.Get("to"), started)
|
|
if err != nil {
|
|
renderError(w, 400, err)
|
|
return
|
|
}
|
|
q.ProjectID = params.Get("projectId")
|
|
q.SupplierID = params.Get("supplierId")
|
|
q.Group = params.Get("group")
|
|
q.ExceptionCategory = params.Get("exceptionCategory")
|
|
q.Compact = params.Get("compact") == "true"
|
|
if q.Group == "" {
|
|
q.Group = "project"
|
|
}
|
|
if q.Group != "project" && q.Group != "supplier" {
|
|
renderJSON(w, 400, map[string]string{"error": "invalid group"})
|
|
return
|
|
}
|
|
projects, err := s.store.ListProjectsByOrganization(ctx, org)
|
|
if err != nil {
|
|
renderError(w, 500, err)
|
|
return
|
|
}
|
|
allowed := map[string]bool{}
|
|
for _, id := range scope.ProjectIDs {
|
|
allowed[id] = true
|
|
}
|
|
ids := []string{}
|
|
projectOptions := []map[string]string{}
|
|
for _, p := range projects {
|
|
if !allowed[p.ID] || (params.Get("activeOnly") == "true" && p.Status == domain.ProjectStatusArchived) {
|
|
continue
|
|
}
|
|
ids = append(ids, p.ID)
|
|
projectOptions = append(projectOptions, map[string]string{"id": p.ID, "name": p.Name})
|
|
}
|
|
if q.ProjectID != "" {
|
|
found := false
|
|
for _, id := range ids {
|
|
if id == q.ProjectID {
|
|
found = true
|
|
}
|
|
}
|
|
if !found {
|
|
renderJSON(w, 400, map[string]string{"error": "项目不在当前生产统计范围"})
|
|
return
|
|
}
|
|
}
|
|
responseIdentity := fmt.Sprint(scope.Revision) + ":" + q.From.Format(time.RFC3339) + ":" + q.To.Format(time.RFC3339) + ":" + params.Encode()
|
|
if prepared, ok := s.store.(interface {
|
|
PreparedProductionResponse(context.Context, string, []string, string) ([]byte, bool)
|
|
}); ok {
|
|
if data, hit := prepared.PreparedProductionResponse(ctx, org, ids, responseIdentity); hit {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
w.WriteHeader(200)
|
|
_, _ = w.Write(data)
|
|
return
|
|
}
|
|
}
|
|
var report productionstats.Report
|
|
var asOf string
|
|
if prepared, ok := s.store.(interface {
|
|
LoadProductionReport(context.Context, string, []string) (productionstats.Report, string, error)
|
|
}); ok {
|
|
report, asOf, err = prepared.LoadProductionReport(ctx, org, ids)
|
|
} else {
|
|
var snapshot productionstats.Snapshot
|
|
if cached, ok := s.store.(interface {
|
|
LoadProductionStatsCached(context.Context, string, []string) (productionstats.Snapshot, error)
|
|
}); ok {
|
|
snapshot, err = cached.LoadProductionStatsCached(ctx, org, ids)
|
|
} else {
|
|
snapshot, err = s.store.LoadProductionStats(ctx, org, ids)
|
|
}
|
|
if err == nil {
|
|
report = productionstats.Build(snapshot)
|
|
asOf = snapshot.AsOf
|
|
}
|
|
}
|
|
if err != nil {
|
|
renderError(w, 500, err)
|
|
return
|
|
}
|
|
summary := productionstats.Summarize(report, q)
|
|
suppliers, err := s.store.ListSuppliers(ctx, org)
|
|
if err != nil {
|
|
renderError(w, 500, err)
|
|
return
|
|
}
|
|
names := map[string]string{productionstats.Unassigned: "未分配", productionstats.Unknown: "待核对"}
|
|
for _, supplier := range suppliers {
|
|
names[supplier.ID] = supplier.Name
|
|
}
|
|
present := map[string]bool{}
|
|
for _, source := range report.Sources {
|
|
present[source.SupplierID] = true
|
|
}
|
|
for _, event := range report.Events {
|
|
present[event.SupplierID] = true
|
|
}
|
|
supplierOptions := []map[string]string{}
|
|
for id := range present {
|
|
name := names[id]
|
|
if name == "" {
|
|
name = id
|
|
}
|
|
supplierOptions = append(supplierOptions, map[string]string{"id": id, "name": name})
|
|
}
|
|
sort.Slice(supplierOptions, func(i, j int) bool { return supplierOptions[i]["name"] < supplierOptions[j]["name"] })
|
|
// Include configured projects with no data without leaking excluded projects.
|
|
if q.Group == "project" && q.SupplierID == "" {
|
|
seen := map[string]bool{}
|
|
for _, row := range summary.Rows {
|
|
seen[row.ID] = true
|
|
}
|
|
seenPipeline := map[string]bool{}
|
|
for _, row := range summary.PipelineRows {
|
|
seenPipeline[row.ID] = true
|
|
}
|
|
for _, p := range projectOptions {
|
|
if !seen[p["id"]] && (q.ProjectID == "" || q.ProjectID == p["id"]) {
|
|
summary.Rows = append(summary.Rows, productionstats.Row{ID: p["id"], Counts: map[string]int{}})
|
|
}
|
|
if !seenPipeline[p["id"]] && (q.ProjectID == "" || q.ProjectID == p["id"]) {
|
|
summary.PipelineRows = append(summary.PipelineRows, productionstats.Row{ID: p["id"], Counts: map[string]int{}})
|
|
}
|
|
}
|
|
}
|
|
if asOf == "" {
|
|
asOf = started.Format(time.RFC3339Nano)
|
|
}
|
|
response := map[string]any{"configured": scope.Revision > 0, "asOf": asOf, "summary": summary, "projects": projectOptions, "suppliers": supplierOptions, "from": q.From.Format(time.RFC3339), "to": q.To.Format(time.RFC3339)}
|
|
if params.Get("details") == "true" {
|
|
items := productionstats.Details(report, q, params.Get("metric"), strings.TrimSpace(params.Get("search")))
|
|
page, pageErr := strconv.Atoi(params.Get("page"))
|
|
if params.Get("page") != "" && (pageErr != nil || page < 1 || page > 10000000) {
|
|
renderJSON(w, 400, map[string]string{"error": "invalid page"})
|
|
return
|
|
}
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
start := (page - 1) * 25
|
|
if start > len(items) {
|
|
start = len(items)
|
|
}
|
|
end := start + 25
|
|
if end > len(items) {
|
|
end = len(items)
|
|
}
|
|
response["items"] = items[start:end]
|
|
response["total"] = len(items)
|
|
response["page"] = page
|
|
}
|
|
if prepared, ok := s.store.(interface {
|
|
RememberProductionResponse(context.Context, string, []string, string, string, any)
|
|
}); ok {
|
|
prepared.RememberProductionResponse(ctx, org, ids, responseIdentity, asOf, response)
|
|
}
|
|
renderJSON(w, 200, response)
|
|
}
|