droboticflow/internal/store/query_build_fact_document.go
2026-11-15 08:11:09 -08:00

49 lines
1.5 KiB
Go

package store
import (
"droboticflow/internal/queryserving"
"droboticflow/internal/workforcestats"
"encoding/json"
"go.mongodb.org/mongo-driver/bson"
"time"
)
func queryBuildFactDocument(org string, epoch int64, f workforcestats.Fact) (bson.M, string, int, error) {
raw, err := json.Marshal(f)
if err != nil {
return nil, "", 0, err
}
hash := queryserving.Key(workforceFactSchema, string(raw))
encoded, err := bson.Marshal(f)
if err != nil {
return nil, "", 0, err
}
var doc bson.M
if err = bson.Unmarshal(encoded, &doc); err != nil {
return nil, "", 0, err
}
at, err := time.Parse(time.RFC3339Nano, f.CreatedAt)
if err != nil {
return nil, "", 0, err
}
doc["_id"], doc["organizationId"], doc["fromEpoch"], doc["hash"], doc["at"] = queryserving.Key(workforceFactSchema, org, f.Key, epoch), org, epoch, hash, at
doc["atSeconds"], doc["atNanos"] = at.Unix(), at.Nanosecond()
doc["metric"] = workforcestats.MetricCounterValues(f.Metric)
doc["order"] = ""
if f.Detail != nil {
raw, e := json.Marshal(f.Detail)
if e != nil {
return nil, "", 0, e
}
var detail bson.M
if e = bson.UnmarshalExtJSON(raw, false, &detail); e != nil {
return nil, "", 0, e
}
doc["detail"] = detail
doc["return"] = bson.M{"id": f.Detail.ID, "stage": f.Detail.Stage, "taskIds": f.Detail.TaskIDs, "metrics": detail["metrics"]}
doc["order"] = f.Detail.ID + f.Detail.UserID + f.Detail.SupplierID
}
stored, err := bson.Marshal(doc)
return doc, hash, len(stored), err
}