fix
This commit is contained in:
1 parent
feebf7d3c1
commit
486502852e
41 files changed
+1311
-259
No files matched your search
@@ -1,6 +1,7 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -9,19 +10,19 @@ import (
|
||||
)
|
||||
|
||||
var editableCostFeatures = map[string]bool{
|
||||
"product_processing": true,
|
||||
"openai_token_k": true,
|
||||
"seo_meta_ai": true,
|
||||
"campaign_copy": true,
|
||||
"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
|
||||
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
|
||||
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
|
||||
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)
|
||||
@@ -31,7 +32,7 @@ func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Re
|
||||
out := make([]map[string]any, 0, 16)
|
||||
for rows.Next() {
|
||||
var scope, id, feature string
|
||||
var cost int
|
||||
var cost float64
|
||||
if err := rows.Scan(&scope, &id, &feature, &cost); err != nil {
|
||||
LogAndError(w, http.StatusInternalServerError, "could not scan processing costs", err)
|
||||
return
|
||||
@@ -48,10 +49,10 @@ func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Re
|
||||
|
||||
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 *int `json:"cost_per_unit"` // null removes an override; cannot remove global rule
|
||||
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")
|
||||
@@ -59,7 +60,7 @@ func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
body.Scope = strings.TrimSpace(strings.ToLower(body.Scope))
|
||||
body.Feature = strings.TrimSpace(body.Feature)
|
||||
if !editableCostFeatures[body.Feature] || (body.Cost != nil && (*body.Cost < 1 || *body.Cost > 1000000)) {
|
||||
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
|
||||
}
|
||||
@@ -101,3 +102,78 @@ func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Req
|
||||
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})
|
||||
}
|
||||
@@ -27,19 +27,19 @@ func (s *Server) handleBillingUsageExport(w http.ResponseWriter, r *http.Request
|
||||
_ = out.Write([]string{"company_id", "range", "metric", "value", "notes"})
|
||||
rows := []struct {
|
||||
label string
|
||||
value int64
|
||||
value float64
|
||||
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"},
|
||||
{"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.FormatInt(v.value, 10), v.notes})
|
||||
_ = out.Write([]string{cid.String(), usage.Range, v.label, strconv.FormatFloat(v.value, 'f', -1, 64), v.notes})
|
||||
}
|
||||
out.Flush()
|
||||
}
|
||||
@@ -15,6 +15,15 @@ import (
|
||||
|
||||
func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) {
|
||||
cid, _ := CompanyIDFromContext(r.Context())
|
||||
ctx := r.Context()
|
||||
if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" {
|
||||
parsed, err := company.ParseLanguage(lang, false)
|
||||
if err != nil {
|
||||
Error(w, http.StatusBadRequest, "unsupported language")
|
||||
return
|
||||
}
|
||||
ctx = catalog.WithImportLanguage(ctx, parsed)
|
||||
}
|
||||
max := maxPageLimit
|
||||
if r.URL.Query().Get("tree") == "1" {
|
||||
max = maxTreePageLimit
|
||||
@@ -25,7 +34,7 @@ func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) {
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
}
|
||||
items, total, err := s.Catalog.ListCategories(r.Context(), cid, f)
|
||||
items, total, err := s.Catalog.ListCategories(ctx, cid, f)
|
||||
if err != nil {
|
||||
Error(w, http.StatusInternalServerError, "list failed")
|
||||
return
|
||||
@@ -55,12 +64,21 @@ func (s *Server) handleCreateCategory(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) handleGetCategory(w http.ResponseWriter, r *http.Request) {
|
||||
cid, _ := CompanyIDFromContext(r.Context())
|
||||
ctx := r.Context()
|
||||
if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" {
|
||||
parsed, err := company.ParseLanguage(lang, false)
|
||||
if err != nil {
|
||||
Error(w, http.StatusBadRequest, "unsupported language")
|
||||
return
|
||||
}
|
||||
ctx = catalog.WithImportLanguage(ctx, parsed)
|
||||
}
|
||||
id, err := uuid.Parse(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
Error(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
item, err := s.Catalog.GetCategory(r.Context(), cid, id)
|
||||
item, err := s.Catalog.GetCategory(ctx, cid, id)
|
||||
if err != nil {
|
||||
Error(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
@@ -256,6 +274,15 @@ func (s *Server) handleDeleteVariable(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) handleListAttributes(w http.ResponseWriter, r *http.Request) {
|
||||
cid, _ := CompanyIDFromContext(r.Context())
|
||||
ctx := r.Context()
|
||||
if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" {
|
||||
parsed, err := company.ParseLanguage(lang, false)
|
||||
if err != nil {
|
||||
Error(w, http.StatusBadRequest, "unsupported language")
|
||||
return
|
||||
}
|
||||
ctx = catalog.WithImportLanguage(ctx, parsed)
|
||||
}
|
||||
limit, offset := ParseLimitOffset(r)
|
||||
f := catalog.ListFilter{
|
||||
Query: QuerySearch(r),
|
||||
@@ -264,7 +291,7 @@ func (s *Server) handleListAttributes(w http.ResponseWriter, r *http.Request) {
|
||||
RootsOnly: r.URL.Query().Get("roots") == "1",
|
||||
ParentKey: r.URL.Query().Get("parent_key"),
|
||||
}
|
||||
items, total, err := s.Catalog.ListAttributes(r.Context(), cid, f)
|
||||
items, total, err := s.Catalog.ListAttributes(ctx, cid, f)
|
||||
if err != nil {
|
||||
Error(w, http.StatusInternalServerError, "list failed")
|
||||
return
|
||||
|
||||
@@ -2,6 +2,7 @@ package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/feeds"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -200,6 +201,7 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
|
||||
URL string `json:"url"`
|
||||
RequestHeaders map[string]string `json:"request_headers"`
|
||||
Format string `json:"format"`
|
||||
Language string `json:"language"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&req); err != nil {
|
||||
Error(w, http.StatusBadRequest, "invalid JSON request")
|
||||
@@ -209,6 +211,12 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
|
||||
Error(w, http.StatusBadRequest, "url required")
|
||||
return
|
||||
}
|
||||
lang, err := importLanguageParam(req.Language, r.URL.Query().Get("language"), company.LoadLanguage(r.Context(), s.Pool, cid))
|
||||
if err != nil {
|
||||
Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
ctx := catalog.WithImportLanguage(r.Context(), lang)
|
||||
source, err := feeds.DownloadImportSource(r.Context(), req.URL, req.RequestHeaders, catalogMaxUpload)
|
||||
if err != nil {
|
||||
ClientOrLog(w, http.StatusBadRequest, "could not download import URL", err, feeds.ClientError)
|
||||
@@ -226,23 +234,29 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
|
||||
var result catalog.ImportResult
|
||||
switch kind {
|
||||
case "categories":
|
||||
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, data)
|
||||
result, err = s.Catalog.ImportCategoriesCSV(ctx, cid, data)
|
||||
case "attributes":
|
||||
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, data)
|
||||
result, err = s.Catalog.ImportAttributesCSV(ctx, cid, data)
|
||||
case "products":
|
||||
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, data, nil)
|
||||
result, err = s.Catalog.ImportProductsCSV(ctx, cid, data, nil)
|
||||
}
|
||||
if err != nil {
|
||||
ClientOrLog(w, http.StatusBadRequest, "import failed", err, catalog.ClientError)
|
||||
return
|
||||
}
|
||||
JSON(w, http.StatusOK, map[string]any{"kind": kind, "import": result, "source": "url"})
|
||||
JSON(w, http.StatusOK, map[string]any{"kind": kind, "import": result, "source": "url", "language": lang})
|
||||
return
|
||||
}
|
||||
if err := r.ParseMultipartForm(catalogMaxUpload); err != nil {
|
||||
Error(w, http.StatusBadRequest, "invalid multipart form")
|
||||
return
|
||||
}
|
||||
lang, langErr := importLanguageParam(r.FormValue("language"), r.URL.Query().Get("language"), company.LoadLanguage(r.Context(), s.Pool, cid))
|
||||
if langErr != nil {
|
||||
Error(w, http.StatusBadRequest, langErr.Error())
|
||||
return
|
||||
}
|
||||
ctx := catalog.WithImportLanguage(r.Context(), lang)
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
Error(w, http.StatusBadRequest, "file field required")
|
||||
@@ -286,12 +300,12 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
switch kind {
|
||||
case "categories":
|
||||
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, input)
|
||||
result, err = s.Catalog.ImportCategoriesCSV(ctx, cid, input)
|
||||
case "attributes":
|
||||
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, input)
|
||||
result, err = s.Catalog.ImportAttributesCSV(ctx, cid, input)
|
||||
case "products":
|
||||
fid := fileID
|
||||
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, input, &fid)
|
||||
result, err = s.Catalog.ImportProductsCSV(ctx, cid, input, &fid)
|
||||
}
|
||||
if err != nil {
|
||||
public := "import failed"
|
||||
@@ -317,7 +331,7 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
meta, _ = s.Catalog.UpdateFileStatus(r.Context(), cid, fileID, "completed", importMeta)
|
||||
JSON(w, http.StatusOK, map[string]any{"file": meta, "import": result, "kind": kind})
|
||||
JSON(w, http.StatusOK, map[string]any{"file": meta, "import": result, "kind": kind, "language": lang})
|
||||
}
|
||||
|
||||
func importKindFromPath(r *http.Request) string {
|
||||
@@ -341,3 +355,16 @@ func importKindFromPath(r *http.Request) string {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// importLanguageParam accepts explicit dashboard/API language, otherwise uses the
|
||||
// company primary language. Never silently import to an unsupported locale.
|
||||
func importLanguageParam(body, query, primary string) (string, error) {
|
||||
requested := strings.TrimSpace(body)
|
||||
if requested == "" {
|
||||
requested = strings.TrimSpace(query)
|
||||
}
|
||||
if requested == "" {
|
||||
requested = primary
|
||||
}
|
||||
return company.ParseLanguage(requested, false)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package httpapi
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestImportLanguageParam(t *testing.T) {
|
||||
cases := []struct {
|
||||
body, query, primary, want string
|
||||
valid bool
|
||||
}{
|
||||
{"", "", "sl", "sl", true},
|
||||
{"hr", "", "sl", "hr", true},
|
||||
{"", "JA", "en", "ja", true},
|
||||
{"xx", "", "en", "", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got, err := importLanguageParam(tc.body, tc.query, tc.primary)
|
||||
if (err == nil) != tc.valid || (tc.valid && got != tc.want) {
|
||||
t.Fatalf("importLanguageParam(%q,%q,%q) = %q, %v", tc.body, tc.query, tc.primary, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/feeds"
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/processing"
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -53,11 +54,16 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) {
|
||||
FeedType string `json:"feed_type"`
|
||||
SyncIntervalMinutes int `json:"sync_interval_minutes"`
|
||||
RequestHeaders map[string]string `json:"request_headers"`
|
||||
ContentLanguage string `json:"content_language"`
|
||||
}
|
||||
if err := DecodeJSON(r, &body); err != nil {
|
||||
Error(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
if body.ContentLanguage != "" && !company.IsAllowedLanguage(body.ContentLanguage) {
|
||||
Error(w, http.StatusBadRequest, "unsupported content language")
|
||||
return
|
||||
}
|
||||
item, err := s.Feeds.Create(r.Context(), cid, feeds.CreateInput{
|
||||
Name: body.Name,
|
||||
URL: body.URL,
|
||||
@@ -65,6 +71,7 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) {
|
||||
FeedType: body.FeedType,
|
||||
SyncIntervalMinutes: body.SyncIntervalMinutes,
|
||||
RequestHeaders: body.RequestHeaders,
|
||||
ContentLanguage: company.NormalizeLanguage(body.ContentLanguage),
|
||||
})
|
||||
if err != nil {
|
||||
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
|
||||
@@ -84,6 +91,11 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
|
||||
feedType := strings.TrimSpace(r.FormValue("feed_type"))
|
||||
itemPath := strings.TrimSpace(r.FormValue("item_path"))
|
||||
interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes")))
|
||||
contentLanguage := strings.TrimSpace(r.FormValue("content_language"))
|
||||
if contentLanguage != "" && !company.IsAllowedLanguage(contentLanguage) {
|
||||
Error(w, http.StatusBadRequest, "unsupported content language")
|
||||
return
|
||||
}
|
||||
headers := map[string]string{}
|
||||
if raw := strings.TrimSpace(r.FormValue("request_headers")); raw != "" {
|
||||
if err := json.Unmarshal([]byte(raw), &headers); err != nil {
|
||||
@@ -147,6 +159,7 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
|
||||
SyncIntervalMinutes: interval,
|
||||
Options: options,
|
||||
RequestHeaders: headers,
|
||||
ContentLanguage: company.NormalizeLanguage(contentLanguage),
|
||||
})
|
||||
if err != nil {
|
||||
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
|
||||
@@ -186,6 +199,13 @@ func (s *Server) handleUpdateFeed(w http.ResponseWriter, r *http.Request) {
|
||||
Error(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
if raw, exists := body["content_language"]; exists {
|
||||
code, ok := raw.(string)
|
||||
if !ok || (code != "" && !company.IsAllowedLanguage(code)) {
|
||||
Error(w, http.StatusBadRequest, "unsupported content language")
|
||||
return
|
||||
}
|
||||
}
|
||||
item, err := s.Feeds.Update(r.Context(), cid, id, body)
|
||||
if err != nil {
|
||||
if feeds.IsNotFound(err) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
@@ -41,14 +42,21 @@ func (s *Server) handleStartProcessingJob(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
// Do not schedule jobs with unknown outputs (or create orphaned jobs).
|
||||
for _, requested := range body.ProcessingTypes {
|
||||
if requested != "title" && requested != "description" && requested != "seo_meta" {
|
||||
Error(w, http.StatusBadRequest, fmt.Sprintf("unsupported processing output: %s", requested))
|
||||
return
|
||||
}
|
||||
}
|
||||
// The shared handler serves session dashboard jobs and /api/v1/process.
|
||||
// Public API results should be directly visible in the Processed catalog tab.
|
||||
var jobs []processing.Job
|
||||
var err error
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v1/") {
|
||||
jobs, err = s.Processing.StartAPIJob(r.Context(), cid, uid, ids, body.ProcessingType)
|
||||
jobs, err = s.Processing.StartAPIJobWithTypes(r.Context(), cid, uid, ids, body.ProcessingType, body.ProcessingTypes)
|
||||
} else {
|
||||
jobs, err = s.Processing.StartJob(r.Context(), cid, uid, ids, body.ProcessingType)
|
||||
jobs, err = s.Processing.StartJobWithTypes(r.Context(), cid, uid, ids, body.ProcessingType, body.ProcessingTypes)
|
||||
}
|
||||
if err != nil {
|
||||
if writePlanGate(w, err) {
|
||||
@@ -65,6 +73,7 @@ func (s *Server) handleStartProcessingJob(w http.ResponseWriter, r *http.Request
|
||||
LogAndError(w, http.StatusBadRequest, "could not start processing job", err)
|
||||
return
|
||||
}
|
||||
// Jobs already store the selected outputs transactionally, before enqueueing.
|
||||
for _, job := range jobs {
|
||||
if err := s.Jobs.EnqueueProcessingJob(r.Context(), job.ID); err != nil {
|
||||
Error(w, http.StatusInternalServerError, "enqueue failed")
|
||||
|
||||
@@ -409,6 +409,8 @@ func (s *Server) Router() http.Handler {
|
||||
r.Get("/ai-costs", s.handleAdminAICosts)
|
||||
r.Get("/ai-costs/export", s.handleAdminExportAICosts)
|
||||
r.Get("/billing/invoices/export", s.handleAdminExportCompanyInvoices)
|
||||
r.Get("/credit-value-eur", s.handleAdminCreditValueEUR)
|
||||
r.Put("/credit-value-eur", s.handleAdminCreditValueEUR)
|
||||
r.Get("/processing-costs", s.handleAdminGetProcessingCosts)
|
||||
r.Put("/processing-costs", s.handleAdminPutProcessingCost)
|
||||
r.Get("/ai-calls/{id}", s.handleAdminGetAICall)
|
||||
@@ -478,6 +480,7 @@ func (s *Server) Router() http.Handler {
|
||||
r.Delete("/api-keys/{id}", s.handleRevokeAPIKey)
|
||||
|
||||
r.Get("/billing/credits", s.handleCreditsOverview)
|
||||
r.Get("/billing/processing-costs", s.handleCompanyContentCosts)
|
||||
r.Get("/billing/capabilities", s.handleGetCapabilities)
|
||||
r.Get("/billing/usage", s.handleBillingUsage)
|
||||
r.Get("/billing/usage/export", s.handleBillingUsageExport)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/feeds"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
@@ -68,6 +69,7 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) {
|
||||
FeedType string `json:"feed_type"`
|
||||
SyncIntervalMinutes int `json:"sync_interval_minutes"`
|
||||
SyncFrequency int `json:"sync_frequency"` // legacy hours
|
||||
ContentLanguage string `json:"content_language"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
}
|
||||
if err := DecodeJSON(r, &body); err != nil {
|
||||
@@ -87,6 +89,10 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if body.ContentLanguage != "" && !company.IsAllowedLanguage(body.ContentLanguage) {
|
||||
v1Err(w, http.StatusBadRequest, "validation_error", "unsupported content language")
|
||||
return
|
||||
}
|
||||
item, err := s.Feeds.Create(r.Context(), cid, feeds.CreateInput{
|
||||
Name: name,
|
||||
URL: url,
|
||||
@@ -94,6 +100,7 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) {
|
||||
FeedType: body.FeedType,
|
||||
SyncIntervalMinutes: body.SyncIntervalMinutes,
|
||||
SyncFrequencyHours: body.SyncFrequency,
|
||||
ContentLanguage: company.NormalizeLanguage(body.ContentLanguage),
|
||||
})
|
||||
if err != nil {
|
||||
if msg, ok := feeds.ClientError(err); ok {
|
||||
@@ -126,6 +133,11 @@ func (s *Server) createV1FeedFromMultipart(w http.ResponseWriter, r *http.Reques
|
||||
feedType := strings.TrimSpace(r.FormValue("feed_type"))
|
||||
interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes")))
|
||||
freq, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_frequency")))
|
||||
contentLanguage := strings.TrimSpace(r.FormValue("content_language"))
|
||||
if contentLanguage != "" && !company.IsAllowedLanguage(contentLanguage) {
|
||||
v1Err(w, http.StatusBadRequest, "validation_error", "unsupported content language")
|
||||
return
|
||||
}
|
||||
|
||||
file, header, fileErr := r.FormFile("file")
|
||||
var options map[string]any
|
||||
@@ -187,6 +199,7 @@ func (s *Server) createV1FeedFromMultipart(w http.ResponseWriter, r *http.Reques
|
||||
FeedType: feedType,
|
||||
SyncIntervalMinutes: interval,
|
||||
SyncFrequencyHours: freq,
|
||||
ContentLanguage: company.NormalizeLanguage(contentLanguage),
|
||||
Options: options,
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -2136,6 +2136,12 @@ paths:
|
||||
- csv
|
||||
- json
|
||||
description: Source format. xml, csv or json; defaults to xml when not detected.
|
||||
content_language:
|
||||
type: string
|
||||
description: |
|
||||
Optional source-language code (e.g. en, sl, hr, de). Defaults to the
|
||||
company's primary content language. Affects where the synchronized
|
||||
product's original supplier text is stored; it does not translate.
|
||||
sync_interval_minutes:
|
||||
type: integer
|
||||
minimum: 1
|
||||
@@ -2156,6 +2162,7 @@ paths:
|
||||
item_path: channel/item
|
||||
url: https://feeds.example.com/nordic/google-merchant.xml
|
||||
feed_type: xml
|
||||
content_language: sl
|
||||
sync_interval_minutes: 60
|
||||
is_active: true
|
||||
responses:
|
||||
|
||||
@@ -411,5 +411,10 @@ func (s *Server) assertV1ProcessGates(ctx context.Context, companyID uuid.UUID,
|
||||
RequiresAI: billing.ProcessingTypeRequiresAI(processingType) || billing.ProcessingTypeIsEmailCampaignAI(processingType),
|
||||
RequiresEPREL: billing.ProcessingTypeRequiresEPREL(processingType),
|
||||
}
|
||||
if rates, err := s.Billing.ContentRates(ctx, companyID); err == nil {
|
||||
if units, err := billing.ContentDebitUnits(nil, processingType, rates); err == nil {
|
||||
opts.CreditsPerProduct = float64(units) / 10000
|
||||
}
|
||||
}
|
||||
return s.Billing.AssertCanStartProcessing(ctx, companyID, batchSize, opts)
|
||||
}
|
||||
Reference in new issue
Block a user