45 lines
1.6 KiB
Go
45 lines
1.6 KiB
Go
package httpapi
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/csv"
|
||
|
|
"net/http"
|
||
|
|
"strconv"
|
||
|
|
|
||
|
|
"github.com/google/uuid"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Usage statements are informational exports, not tax invoices or payment records.
|
||
|
|
func (s *Server) handleBillingUsageExport(w http.ResponseWriter, r *http.Request) {
|
||
|
|
cid, _ := CompanyIDFromContext(r.Context())
|
||
|
|
if cid == uuid.Nil {
|
||
|
|
Error(w, http.StatusUnauthorized, "company required")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
usage, err := s.Billing.UsageSummary(r.Context(), cid, r.URL.Query().Get("range"))
|
||
|
|
if err != nil {
|
||
|
|
LogAndError(w, http.StatusInternalServerError, "could not export usage", err)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||
|
|
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-usage.csv"`)
|
||
|
|
w.Header().Set("Cache-Control", "private, no-store")
|
||
|
|
out := csv.NewWriter(w)
|
||
|
|
_ = out.Write([]string{"company_id", "range", "metric", "value", "notes"})
|
||
|
|
rows := []struct {
|
||
|
|
label string
|
||
|
|
value int64
|
||
|
|
notes string
|
||
|
|
}{
|
||
|
|
{"ai_calls", usage.AICalls, "Recorded provider calls in period"},
|
||
|
|
{"input_tokens", usage.InputTokens, "Includes cached input"},
|
||
|
|
{"cached_input_tokens", usage.CachedInputTokens, "Subset of input"},
|
||
|
|
{"output_tokens", usage.OutputTokens, ""},
|
||
|
|
{"products_processed", int64(usage.ProductsProcessed), "Period"},
|
||
|
|
{"credits_used_wallet", int64(usage.CreditsUsed), "All-time wallet balance, not period credits"},
|
||
|
|
{"credits_remaining", int64(usage.CreditsRemaining), "Current wallet"},
|
||
|
|
}
|
||
|
|
for _, v := range rows {
|
||
|
|
_ = out.Write([]string{cid.String(), usage.Range, v.label, strconv.FormatInt(v.value, 10), v.notes})
|
||
|
|
}
|
||
|
|
out.Flush()
|
||
|
|
}
|