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 float64 notes string }{ {"ai_calls", float64(usage.AICalls), "Recorded provider calls in period"}, {"input_tokens", float64(usage.InputTokens), "Includes cached input"}, {"cached_input_tokens", float64(usage.CachedInputTokens), "Subset of input"}, {"output_tokens", float64(usage.OutputTokens), ""}, {"products_processed", float64(usage.ProductsProcessed), "Period"}, {"credits_used_wallet", usage.CreditsUsed, "All-time wallet balance, not period credits"}, {"credits_remaining", usage.CreditsRemaining, "Current wallet"}, } for _, v := range rows { _ = out.Write([]string{cid.String(), usage.Range, v.label, strconv.FormatFloat(v.value, 'f', -1, 64), v.notes}) } out.Flush() }