package httpapi import ( "math" "net/http" "strconv" "strings" "github.com/google/uuid" ) var editableCostFeatures = map[string]bool{ "title_ai": true, "description_ai": true, "seo_meta_ai": true, "product_ai": true, // presence of a plan rule enables per-product pricing } func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Request) { rows, err := s.Pool.Query(r.Context(), ` SELECT 'default', '', feature_name, cost_per_unit FROM processing_costs WHERE is_active = true AND feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') UNION ALL SELECT 'plan', plan_id::text, feature_name, cost_per_unit FROM plan_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') UNION ALL SELECT 'company', company_id::text, feature_name, cost_per_unit FROM company_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') ORDER BY 1, 2, 3`) if err != nil { LogAndError(w, http.StatusInternalServerError, "could not load processing costs", err) return } defer rows.Close() out := make([]map[string]any, 0, 16) for rows.Next() { var scope, id, feature string var cost float64 if err := rows.Scan(&scope, &id, &feature, &cost); err != nil { LogAndError(w, http.StatusInternalServerError, "could not scan processing costs", err) return } out = append(out, map[string]any{"scope": scope, "id": id, "feature": feature, "cost_per_unit": cost}) } if err := rows.Err(); err != nil { LogAndError(w, http.StatusInternalServerError, "could not read processing costs", err) return } w.Header().Set("Cache-Control", "private, no-store") JSON(w, http.StatusOK, map[string]any{"rules": out, "notes": "Company overrides take priority over plan rules. Changes affect future debits only."}) } func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Request) { var body struct { Scope string `json:"scope"` ID string `json:"id"` Feature string `json:"feature"` Cost *float64 `json:"cost_per_unit"` // null removes an override; cannot remove global rule } if err := DecodeJSON(r, &body); err != nil { Error(w, http.StatusBadRequest, "invalid json") return } body.Scope = strings.TrimSpace(strings.ToLower(body.Scope)) body.Feature = strings.TrimSpace(body.Feature) if !editableCostFeatures[body.Feature] || (body.Cost != nil && (math.IsNaN(*body.Cost) || math.IsInf(*body.Cost, 0) || *body.Cost < 0 || *body.Cost > 1000000 || math.Abs(*body.Cost*10000-math.Round(*body.Cost*10000)) > 0.000001)) { Error(w, http.StatusBadRequest, "invalid feature or credit cost") return } ctx := r.Context() var err error switch body.Scope { case "company": id, parseErr := uuid.Parse(body.ID) if parseErr != nil { Error(w, http.StatusBadRequest, "invalid company id") return } if body.Cost == nil { _, err = s.Pool.Exec(ctx, `DELETE FROM company_processing_costs WHERE company_id = $1 AND feature_name = $2`, id, body.Feature) } else { _, err = s.Pool.Exec(ctx, `INSERT INTO company_processing_costs (company_id,feature_name,cost_per_unit) VALUES ($1,$2,$3) ON CONFLICT(company_id,feature_name) DO UPDATE SET cost_per_unit=EXCLUDED.cost_per_unit,updated_at=now()`, id, body.Feature, *body.Cost) } case "plan": id, parseErr := strconv.ParseInt(body.ID, 10, 64) if parseErr != nil || id <= 0 { Error(w, http.StatusBadRequest, "invalid plan id") return } if body.Cost == nil { _, err = s.Pool.Exec(ctx, `DELETE FROM plan_processing_costs WHERE plan_id = $1 AND feature_name = $2`, id, body.Feature) } else { _, err = s.Pool.Exec(ctx, `INSERT INTO plan_processing_costs (plan_id,feature_name,cost_per_unit) VALUES ($1,$2,$3) ON CONFLICT(plan_id,feature_name) DO UPDATE SET cost_per_unit=EXCLUDED.cost_per_unit,updated_at=now()`, id, body.Feature, *body.Cost) } default: Error(w, http.StatusBadRequest, "scope must be company or plan") return } if err != nil { LogAndError(w, http.StatusBadRequest, "could not save processing cost", err) return } w.Header().Set("Cache-Control", "private, no-store") JSON(w, http.StatusOK, map[string]any{"status": "ok"}) } // handleCompanyContentCosts returns effective plan/company rates to the dashboard. // Never disclose other companies' pricing overrides. func (s *Server) handleCompanyContentCosts(w http.ResponseWriter, r *http.Request) { cid, ok := CompanyIDFromContext(r.Context()) if !ok || cid == uuid.Nil { Error(w, http.StatusUnauthorized, "unauthorized") return } rates, err := s.Billing.ContentRates(r.Context(), cid) if err != nil { LogAndError(w, http.StatusInternalServerError, "could not load credit costs", err) return } out := make(map[string]float64, len(rates)) for key, units := range rates { out[key] = float64(units) / 10000 } mode := "outputs" if _, ok := rates["product"]; ok { mode = "product" } w.Header().Set("Cache-Control", "private, no-store") JSON(w, http.StatusOK, map[string]any{"mode": mode, "credits": out}) } // Monetary credit valuation is an admin reference rate. Stripe invoices, pack // checkout prices and historic wallet ledger values are not changed by it. const creditValueEURSetting = "billing.reference_eur_per_credit" func (s *Server) handleAdminCreditValueEUR(w http.ResponseWriter, r *http.Request) { if s.PlatformSettings == nil { Error(w, http.StatusServiceUnavailable, "platform settings unavailable") return } if r.Method == http.MethodGet { saved, ok, err := s.PlatformSettings.GetKV(r.Context(), creditValueEURSetting) if err != nil { LogAndError(w, http.StatusInternalServerError, "unable to load credit valuation", err) return } var amount any if ok && strings.TrimSpace(saved) != "" { parsed, err := strconv.ParseFloat(saved, 64) if err != nil { LogAndError(w, http.StatusInternalServerError, "invalid stored credit valuation", err) return } amount = parsed } w.Header().Set("Cache-Control", "private, no-store") JSON(w, http.StatusOK, map[string]any{"eur_per_credit": amount, "currency": "EUR", "note": "Reference valuation only; actual customer charges follow Stripe invoices and purchased credit pack prices."}) return } if r.Method != http.MethodPut { Error(w, http.StatusMethodNotAllowed, "method not allowed") return } var body struct { Value *float64 `json:"eur_per_credit"` } if err := DecodeJSON(r, &body); err != nil { Error(w, http.StatusBadRequest, "invalid json") return } if body.Value == nil || math.IsNaN(*body.Value) || math.IsInf(*body.Value, 0) || *body.Value < 0 || *body.Value > 10000 || math.Abs(*body.Value*1000000-math.Round(*body.Value*1000000)) > 0.000001 { Error(w, http.StatusBadRequest, "EUR per credit must be between 0 and 10000 with up to six decimals") return } if err := s.PlatformSettings.SetKV(r.Context(), creditValueEURSetting, strconv.FormatFloat(*body.Value, 'f', -1, 64)); err != nil { LogAndError(w, http.StatusInternalServerError, "unable to save credit valuation", err) return } JSON(w, http.StatusOK, map[string]any{"status": "ok", "eur_per_credit": *body.Value}) }