Files
sharang 69c15be333
ci / shared (push) Successful in 12s
ci / test (push) Successful in 9m8s
ci / image (push) Successful in 36s
feat(onprem): APP_ENV=onprem with directory users and installation mail (#146)
2026-11-20 16:31:11 +00:00

240 lines
7.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package server
import (
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// ─── usage events (PRODUCT_INTEGRATION_SPEC 2.0 §9.2) ────────────────────
//
// Products push facts continuously; the registry stores them once
// (idempotency_key) and forwards each new one to ERPNext through the outbox
// as a Usage Record. Billing reads ERP; the portal reads the registry.
type usageEventIn struct {
IdempotencyKey string `json:"idempotency_key"`
TenantID string `json:"tenant_id"`
Product string `json:"product"`
Metric string `json:"metric"`
Quantity *float64 `json:"quantity"`
OccurredAt string `json:"occurred_at"`
Properties map[string]interface{} `json:"properties"`
}
type usageBatch struct {
Events []usageEventIn `json:"events"`
}
// postUsageEvents accepts one event, an array, or {"events": [...]}.
func (s *Server) postUsageEvents(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
var raw json.RawMessage
if err := dec.Decode(&raw); err != nil {
writeError(w, http.StatusBadRequest, "invalid_json", err.Error())
return
}
var events []usageEventIn
switch {
case len(raw) > 0 && raw[0] == '[':
if err := json.Unmarshal(raw, &events); err != nil {
writeError(w, http.StatusBadRequest, "invalid_json", err.Error())
return
}
default:
var b usageBatch
if err := json.Unmarshal(raw, &b); err != nil {
writeError(w, http.StatusBadRequest, "invalid_json", err.Error())
return
}
if b.Events == nil {
var one usageEventIn
if err := json.Unmarshal(raw, &one); err != nil {
writeError(w, http.StatusBadRequest, "invalid_json", err.Error())
return
}
events = []usageEventIn{one}
} else {
events = b.Events
}
}
if len(events) == 0 || len(events) > 500 {
writeError(w, http.StatusBadRequest, "invalid_input", "1..500 events per request")
return
}
p, _ := authn.PrincipalFrom(r.Context())
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
accepted, duplicates := 0, 0
rejected := []map[string]any{}
for i, in := range events {
if p.IsUser() {
in.TenantID = p.TenantID // users may only report for their own tenant
}
if in.IdempotencyKey == "" || in.TenantID == "" || in.Product == "" || in.Metric == "" {
rejected = append(rejected, map[string]any{"index": i, "reason": "idempotency_key, tenant_id, product and metric are required"})
continue
}
// Usage under a staff preview grant is metered but never invoiced:
// tagged preview=true and kept out of the ERP outbox. A product not
// for sale yet is accepted only under such a grant.
preview := s.previewActive(ctx, in.TenantID, in.Product)
if !preview && !s.knownProduct(ctx, in.Product) {
rejected = append(rejected, map[string]any{"index": i, "reason": "unknown_product"})
continue
}
if preview {
props := map[string]interface{}{}
for k, v := range in.Properties {
props[k] = v
}
props["preview"] = true
in.Properties = props
}
qty := 1.0
if in.Quantity != nil {
qty = *in.Quantity
}
occurred := s.now()
if in.OccurredAt != "" {
ts, err := time.Parse(time.RFC3339, in.OccurredAt)
if err != nil {
rejected = append(rejected, map[string]any{"index": i, "reason": "occurred_at must be RFC3339"})
continue
}
occurred = ts.UTC()
}
ev, inserted, err := s.Store.InsertUsageEvent(ctx, store.UsageEvent{
IdempotencyKey: in.IdempotencyKey, TenantID: in.TenantID, Product: in.Product, Metric: in.Metric,
Quantity: qty, OccurredAt: occurred, Properties: in.Properties,
})
if err != nil {
if errors.Is(err, store.ErrNotFound) {
rejected = append(rejected, map[string]any{"index": i, "reason": "tenant_not_found"})
continue
}
if errors.Is(err, store.ErrInvalidInput) {
rejected = append(rejected, map[string]any{"index": i, "reason": "invalid_input"})
continue
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if !inserted {
duplicates++
continue
}
accepted++
if preview {
continue
}
if _, err := s.enqueueERP(ctx, store.OutboxItem{
Kind: store.OutboxUsageRecord, TenantID: ev.TenantID,
Payload: map[string]interface{}{"usage_event_id": ev.ID, "idempotency_key": ev.IdempotencyKey, "product": ev.Product,
"metric": ev.Metric, "quantity": ev.Quantity, "occurred_at": ev.OccurredAt.Format(time.RFC3339)},
}); err != nil {
s.Log.Error("enqueue usage outbox failed", "err", err, "usage_event_id", ev.ID)
}
}
code := http.StatusAccepted
if accepted == 0 && duplicates == 0 {
code = http.StatusBadRequest
}
writeJSON(w, code, map[string]any{"accepted": accepted, "duplicates": duplicates, "rejected": rejected})
}
// usageFilterFrom reads tenant_id, product, metric, since and until. User
// tokens are pinned to their own tenant. It writes the 400 and returns false
// on bad input.
func usageFilterFrom(w http.ResponseWriter, r *http.Request) (store.UsageFilter, bool) {
q := r.URL.Query()
f := store.UsageFilter{TenantID: q.Get("tenant_id"), Product: q.Get("product"), Metric: q.Get("metric")}
if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() {
f.TenantID = p.TenantID
}
if f.TenantID == "" {
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id query param is required")
return f, false
}
for name, dst := range map[string]**time.Time{"since": &f.Since, "until": &f.Until} {
if v := q.Get(name); v != "" {
ts, err := time.Parse(time.RFC3339, v)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid_"+name, "must be RFC3339")
return f, false
}
ts = ts.UTC()
*dst = &ts
}
}
return f, true
}
// listUsageEvents — GET /v1/usage/events?tenant_id=&product=&metric=&since=&until=&limit=
func (s *Server) listUsageEvents(w http.ResponseWriter, r *http.Request) {
f, ok := usageFilterFrom(w, r)
if !ok {
return
}
q := r.URL.Query()
if v := q.Get("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n <= 0 || n > 1000 {
writeError(w, http.StatusBadRequest, "invalid_limit", "limit must be 1..1000")
return
}
f.Limit = n
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
items, err := s.Store.ListUsageEvents(ctx, f)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
// summarizeUsage — GET /v1/usage/summary?tenant_id=&product=&metric=&since=&until=
//
// Counts and quantity sums per product × metric, and per UTC day × metric,
// over every matching event: the portal's 30-day views read this instead of
// folding a capped page of /v1/usage/events.
func (s *Server) summarizeUsage(w http.ResponseWriter, r *http.Request) {
f, ok := usageFilterFrom(w, r)
if !ok {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
sum, err := s.Store.SummarizeUsage(ctx, f)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
writeJSON(w, http.StatusOK, sum)
}
// previewActive reports whether the tenant uses product under an unexpired
// staff preview grant. Lookup errors count as no: the event is then treated
// like any other and refused for a product not for sale.
func (s *Server) previewActive(ctx context.Context, tenantID, product string) bool {
tps, err := s.Store.ListTenantProducts(ctx, tenantID)
if err != nil {
return false
}
now := s.now()
for _, tp := range tps {
if tp.Product == product && tp.PreviewActive(now) {
return true
}
}
return false
}