fixes
This commit is contained in:
1 parent
6586722652
commit
1e7c7bbfbb
65 files changed
+1345
-640
No files matched your search
@@ -36,6 +36,10 @@ type ModelPrice struct {
|
||||
// GPT-5.6 rates here means a fresh database still costs correctly before the
|
||||
// migration seed is edited. Rates: OpenAI list price, 2026-07-30.
|
||||
var defaultModelPrices = map[string]ModelPrice{
|
||||
// OpenAI public standard-rate text models, verified 2026-10-16.
|
||||
"gpt-5.4-mini": {InputPerMTok: 750_000, CachedInputPerMTok: 75_000, OutputPerMTok: 4_500_000},
|
||||
"gpt-5-mini": {InputPerMTok: 250_000, CachedInputPerMTok: 25_000, OutputPerMTok: 2_000_000},
|
||||
"gpt-6-luna": {InputPerMTok: 100_000, CachedInputPerMTok: 10_000, OutputPerMTok: 500_000},
|
||||
"gpt-5.6-luna": {InputPerMTok: 200_000, CachedInputPerMTok: 20_000, OutputPerMTok: 1_200_000},
|
||||
"gpt-5.6-terra": {InputPerMTok: 2_000_000, CachedInputPerMTok: 200_000, OutputPerMTok: 12_000_000},
|
||||
"gpt-5.6-sol": {InputPerMTok: 5_000_000, CachedInputPerMTok: 500_000, OutputPerMTok: 30_000_000},
|
||||
|
||||
@@ -113,24 +113,24 @@ type CreditPack struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Credits int `json:"credits"`
|
||||
PriceUSD int `json:"price_usd"` // whole dollars for marketing UI
|
||||
PriceEUR int `json:"price_eur"` // whole euros for marketing UI
|
||||
// Approx product×language passes at CreditsPerAIProduct.
|
||||
AIProducts int `json:"ai_products"`
|
||||
}
|
||||
|
||||
func packFromCredits(id, name, desc string, credits, priceUSD int) CreditPack {
|
||||
func packFromCredits(id, name, desc string, credits, priceEUR int) CreditPack {
|
||||
return CreditPack{
|
||||
ID: id,
|
||||
Name: name,
|
||||
Description: desc,
|
||||
Credits: credits,
|
||||
PriceUSD: priceUSD,
|
||||
PriceEUR: priceEUR,
|
||||
AIProducts: credits / CreditsPerAIProduct,
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultCreditPacks is the public top-up ladder (credits-first sizing).
|
||||
// Prices are balanced so small packs are not punitive $/credit vs larger ones,
|
||||
// Prices are balanced so small packs are not punitive €/credit vs larger ones,
|
||||
// while staying expensive enough that packs cannot undercut plan upgrades or A1 (~€300).
|
||||
func DefaultCreditPacks() []CreditPack {
|
||||
return []CreditPack{
|
||||
|
||||
@@ -334,10 +334,10 @@ func (s *Service) consumeCredits(ctx context.Context, tx pgx.Tx, companyID uuid.
|
||||
}
|
||||
_ = s.EnsureDefaultCosts(ctx)
|
||||
|
||||
featureCost := s.lookupCost(ctx, featureName, 1)
|
||||
featureCost := s.lookupCostForCompany(ctx, companyID, featureName, 1)
|
||||
tokenKCost := 1
|
||||
if tokenCount > 0 {
|
||||
tokenKCost = s.lookupCost(ctx, "openai_token_k", 1)
|
||||
tokenKCost = s.lookupCostForCompany(ctx, companyID, "openai_token_k", 1)
|
||||
}
|
||||
var debit int
|
||||
if productCount == 1 {
|
||||
@@ -477,6 +477,43 @@ func (s *Service) lookupCost(ctx context.Context, feature string, fallback int)
|
||||
return cost
|
||||
}
|
||||
|
||||
// lookupCostForCompany resolves credit pricing without caching tenant-specific rules.
|
||||
// Overrides must be positive; the existing credit engine enforces a minimum of 1.
|
||||
// An unconfigured/missing migration retains the global default behavior.
|
||||
func (s *Service) lookupCostForCompany(ctx context.Context, companyID uuid.UUID, feature string, fallback int) int {
|
||||
var cost int
|
||||
err := s.Pool.QueryRow(ctx, `
|
||||
SELECT COALESCE(
|
||||
(SELECT cc.cost_per_unit FROM company_processing_costs cc
|
||||
WHERE cc.company_id = $1 AND cc.feature_name = $2),
|
||||
(SELECT pc.cost_per_unit FROM plan_processing_costs pc
|
||||
JOIN company_plans cp ON cp.plan_id = pc.plan_id
|
||||
WHERE cp.company_id = $1 AND cp.is_active = true AND pc.feature_name = $2
|
||||
ORDER BY cp.created_at DESC LIMIT 1),
|
||||
(SELECT gc.cost_per_unit FROM processing_costs gc
|
||||
WHERE gc.feature_name = $2 AND gc.is_active = true),
|
||||
$3
|
||||
)::integer`, companyID, feature, fallback).Scan(&cost)
|
||||
if err == nil && cost >= 0 {
|
||||
return cost
|
||||
}
|
||||
return s.lookupCost(ctx, feature, fallback)
|
||||
}
|
||||
|
||||
// EstimateDebitForCompany uses the same company/plan pricing rules as the actual debit.
|
||||
func (s *Service) EstimateDebitForCompany(ctx context.Context, companyID uuid.UUID, feature string, tokenCount int) int {
|
||||
if feature == "" {
|
||||
feature = "product_processing"
|
||||
}
|
||||
_ = s.EnsureDefaultCosts(ctx)
|
||||
base := s.lookupCostForCompany(ctx, companyID, feature, 1)
|
||||
perK := 1
|
||||
if tokenCount > 0 {
|
||||
perK = s.lookupCostForCompany(ctx, companyID, "openai_token_k", 1)
|
||||
}
|
||||
return DebitAmount(base, perK, tokenCount)
|
||||
}
|
||||
|
||||
// EnsureDefaultCosts seeds plan-aligned processing cost rows (idempotent).
|
||||
// After a successful seed in this process, subsequent calls no-op (worker seeds at boot).
|
||||
func (s *Service) EnsureDefaultCosts(ctx context.Context) error {
|
||||
@@ -900,6 +937,10 @@ type UsageSummary struct {
|
||||
ProductsProcessed int `json:"products_processed"`
|
||||
ProductsTotal int `json:"products_total"`
|
||||
Tokens int64 `json:"tokens"`
|
||||
InputTokens int64 `json:"input_tokens"`
|
||||
CachedInputTokens int64 `json:"cached_input_tokens"`
|
||||
OutputTokens int64 `json:"output_tokens"`
|
||||
AICalls int64 `json:"ai_calls"`
|
||||
FeedsInput int `json:"feeds_input"`
|
||||
FeedsExport int `json:"feeds_export"`
|
||||
JobsTotal int `json:"jobs_total"`
|
||||
@@ -1010,6 +1051,21 @@ func (s *Service) UsageSummary(ctx context.Context, companyID uuid.UUID, rangeRa
|
||||
out.ProductsProcessed = out.ProductsTotal
|
||||
}
|
||||
|
||||
// Detailed token usage comes from the durable per-call ledger, not processed
|
||||
// product rows (a single product can make several model calls).
|
||||
// A missing old ledger should not prevent viewing the rest of billing.
|
||||
if err := s.Pool.QueryRow(ctx, `
|
||||
SELECT COALESCE(SUM(prompt_tokens),0)::bigint,
|
||||
COALESCE(SUM(cached_prompt_tokens),0)::bigint,
|
||||
COALESCE(SUM(completion_tokens),0)::bigint,
|
||||
COALESCE(SUM(calls),0)::bigint
|
||||
FROM ai_usage_daily
|
||||
WHERE company_id = $1 AND ($2::timestamptz IS NULL OR day >= $2::date)
|
||||
AND ($3::timestamptz IS NULL OR day < $3::date)`,
|
||||
companyID, since, until).Scan(&out.InputTokens, &out.CachedInputTokens, &out.OutputTokens, &out.AICalls); err != nil {
|
||||
out.Notes = append(out.Notes, "Detailed token usage unavailable; check the AI usage ledger migration.")
|
||||
}
|
||||
|
||||
if rangeKey == "7d" || rangeKey == "30d" || (rangeKey == "cycle" && since != nil) {
|
||||
seriesSince := now.Truncate(24*time.Hour).AddDate(0, 0, -29)
|
||||
days := 30
|
||||
|
||||
@@ -328,6 +328,10 @@ func (s *StripeService) CreateCheckoutSession(ctx context.Context, companyID uui
|
||||
return CheckoutResult{}, fmt.Errorf("%w: %s %s", ErrStripePriceMissing, plan, term)
|
||||
}
|
||||
|
||||
if err := s.requireEuroStripePrice(ctx, priceID); err != nil {
|
||||
return CheckoutResult{}, err
|
||||
}
|
||||
|
||||
customerID, err := s.ensureCustomer(ctx, companyID, email, companyName)
|
||||
if err != nil {
|
||||
return CheckoutResult{}, err
|
||||
@@ -406,6 +410,10 @@ func (s *StripeService) CreateCreditPackCheckout(ctx context.Context, companyID
|
||||
return CheckoutResult{}, fmt.Errorf("%w: credit pack %s", ErrStripePriceMissing, pack.ID)
|
||||
}
|
||||
|
||||
if err := s.requireEuroStripePrice(ctx, priceID); err != nil {
|
||||
return CheckoutResult{}, err
|
||||
}
|
||||
|
||||
customerID, err := s.ensureCustomer(ctx, companyID, email, companyName)
|
||||
if err != nil {
|
||||
return CheckoutResult{}, err
|
||||
@@ -1034,6 +1042,22 @@ func verifyStripeSignature(payload []byte, header, secret string, tolerance time
|
||||
return ErrStripeBadSignature
|
||||
}
|
||||
|
||||
// requireEuroStripePrice blocks checkout against old USD Stripe Price IDs.
|
||||
// Publishing euro list prices cannot alter an existing Stripe Price currency.
|
||||
func (s *StripeService) requireEuroStripePrice(ctx context.Context, priceID string) error {
|
||||
var price struct {
|
||||
Currency string `json:"currency"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
if err := s.stripeGET(ctx, "https://api.stripe.com/v1/prices/"+url.PathEscape(priceID), &price); err != nil {
|
||||
return fmt.Errorf("verify Stripe EUR price: %w", err)
|
||||
}
|
||||
if !price.Active || !strings.EqualFold(strings.TrimSpace(price.Currency), "eur") {
|
||||
return errors.New("Stripe Price must be active and denominated in EUR; configure a EUR Price ID before checkout")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadStripePriceIDs reads STRIPE_PRICE_* env into the price map.
|
||||
func LoadStripePriceIDs(getenv func(string) string) map[string]string {
|
||||
out := map[string]string{}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package billing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// StripeInvoice contains only identifiers and URLs supplied by Stripe, never a
|
||||
// locally invented financial document. Amounts are in the invoice currency's
|
||||
// smallest unit, as returned by Stripe.
|
||||
type StripeInvoice struct {
|
||||
ID string `json:"id"`
|
||||
Number string `json:"number"`
|
||||
Status string `json:"status"`
|
||||
Currency string `json:"currency"`
|
||||
Created int64 `json:"created"`
|
||||
AmountDue int64 `json:"amount_due"`
|
||||
AmountPaid int64 `json:"amount_paid"`
|
||||
AmountRemaining int64 `json:"amount_remaining"`
|
||||
HostedInvoiceURL string `json:"hosted_invoice_url,omitempty"`
|
||||
InvoicePDF string `json:"invoice_pdf,omitempty"`
|
||||
}
|
||||
|
||||
func (s *StripeService) ListCompanyInvoices(ctx context.Context, companyID uuid.UUID) ([]StripeInvoice, error) {
|
||||
ctx, cfg, err := s.bindCfg(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.MockMode() {
|
||||
return []StripeInvoice{}, nil
|
||||
}
|
||||
var customerID *string
|
||||
err = s.Pool.QueryRow(ctx, `SELECT stripe_customer_id FROM companies WHERE id=$1`, companyID).Scan(&customerID)
|
||||
if errors.Is(err, pgx.ErrNoRows) || customerID == nil || strings.TrimSpace(*customerID) == "" {
|
||||
return []StripeInvoice{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var result struct {
|
||||
Data []StripeInvoice `json:"data"`
|
||||
}
|
||||
endpoint := "https://api.stripe.com/v1/invoices?limit=100&customer=" + url.QueryEscape(*customerID)
|
||||
if err := s.stripeGET(ctx, endpoint, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if result.Data == nil {
|
||||
result.Data = []StripeInvoice{}
|
||||
}
|
||||
return result.Data, nil
|
||||
}
|
||||
@@ -64,7 +64,10 @@ func (s *StripeService) CreateSalesQuoteCheckout(ctx context.Context, in SalesQu
|
||||
}
|
||||
currency := strings.ToLower(strings.TrimSpace(in.Currency))
|
||||
if currency == "" {
|
||||
currency = "usd"
|
||||
currency = "eur"
|
||||
}
|
||||
if currency != "eur" {
|
||||
return SalesQuoteCheckoutResult{}, fmt.Errorf("%w: only EUR sales quotes are supported", ErrStripePlanUnsupported)
|
||||
}
|
||||
|
||||
ctx, cfg, err := s.bindCfg(ctx)
|
||||
@@ -206,7 +209,7 @@ func (s *StripeService) createSalesQuotePrice(ctx context.Context, productID str
|
||||
form.Set("product", productID)
|
||||
form.Set("currency", strings.ToLower(strings.TrimSpace(in.Currency)))
|
||||
if form.Get("currency") == "" {
|
||||
form.Set("currency", "usd")
|
||||
form.Set("currency", "eur")
|
||||
}
|
||||
form.Set("unit_amount", strconv.Itoa(in.InstallmentAmountCents))
|
||||
form.Set("metadata[descrybe_sales_quote]", in.QuoteID.String())
|
||||
|
||||
@@ -16,7 +16,7 @@ type SyncCreditPackResult struct {
|
||||
PriceID string `json:"price_id"`
|
||||
Created bool `json:"created"`
|
||||
Credits int `json:"credits"`
|
||||
PriceUSD int `json:"price_usd"`
|
||||
PriceEUR int `json:"price_eur"`
|
||||
}
|
||||
|
||||
// SyncCreditPackProducts creates/updates Stripe Products + one-time Prices for
|
||||
@@ -47,7 +47,7 @@ func (s *StripeService) SyncCreditPackProducts(ctx context.Context) ([]SyncCredi
|
||||
PriceID: priceID,
|
||||
Created: createdProduct || createdPrice,
|
||||
Credits: pack.Credits,
|
||||
PriceUSD: pack.PriceUSD,
|
||||
PriceEUR: pack.PriceEUR,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
@@ -73,7 +73,7 @@ func (s *StripeService) ensureCreditPackProduct(ctx context.Context, pack Credit
|
||||
form.Set("metadata[descrybe_pack]", pack.ID)
|
||||
form.Set("metadata[credits]", strconv.Itoa(pack.Credits))
|
||||
form.Set("metadata[ai_products]", strconv.Itoa(pack.AIProducts))
|
||||
form.Set("metadata[price_usd]", strconv.Itoa(pack.PriceUSD))
|
||||
form.Set("metadata[price_eur]", strconv.Itoa(pack.PriceEUR))
|
||||
var product struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
@@ -88,7 +88,7 @@ func (s *StripeService) ensureCreditPackProduct(ctx context.Context, pack Credit
|
||||
|
||||
func (s *StripeService) ensureCreditPackPrice(ctx context.Context, productID string, pack CreditPack) (priceID string, created bool, err error) {
|
||||
// Reuse an active one-time price on this product that matches unit amount.
|
||||
wantCents := pack.PriceUSD * 100
|
||||
wantCents := pack.PriceEUR * 100
|
||||
var list struct {
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
@@ -103,14 +103,14 @@ func (s *StripeService) ensureCreditPackPrice(ctx context.Context, productID str
|
||||
return "", false, err
|
||||
}
|
||||
for _, p := range list.Data {
|
||||
if p.Active && p.Type == "one_time" && strings.EqualFold(p.Currency, "usd") && int(p.UnitAmount) == wantCents {
|
||||
if p.Active && p.Type == "one_time" && strings.EqualFold(p.Currency, "eur") && int(p.UnitAmount) == wantCents {
|
||||
return p.ID, false, nil
|
||||
}
|
||||
}
|
||||
|
||||
form := url.Values{}
|
||||
form.Set("product", productID)
|
||||
form.Set("currency", "usd")
|
||||
form.Set("currency", "eur")
|
||||
form.Set("unit_amount", strconv.Itoa(wantCents))
|
||||
form.Set("metadata[descrybe_pack]", pack.ID)
|
||||
form.Set("metadata[credits]", strconv.Itoa(pack.Credits))
|
||||
|
||||
@@ -205,19 +205,19 @@ func TestCreditPackCatalog(t *testing.T) {
|
||||
t.Fatalf("want at least 7 packs, got %d", len(packs))
|
||||
}
|
||||
tiny, ok := CreditPackByID("tiny")
|
||||
if !ok || tiny.Credits != 25 || tiny.PriceUSD != 29 {
|
||||
if !ok || tiny.Credits != 25 || tiny.PriceEUR != 29 {
|
||||
t.Fatalf("tiny pack: %#v ok=%v", tiny, ok)
|
||||
}
|
||||
small, ok := CreditPackByID("small")
|
||||
if !ok || small.Credits != 65 || small.PriceUSD != 59 {
|
||||
if !ok || small.Credits != 65 || small.PriceEUR != 59 {
|
||||
t.Fatalf("small pack: %#v ok=%v", small, ok)
|
||||
}
|
||||
med, ok := CreditPackByID("medium")
|
||||
if !ok || med.Credits != 200 || med.PriceUSD != 149 {
|
||||
if !ok || med.Credits != 200 || med.PriceEUR != 149 {
|
||||
t.Fatalf("medium pack: %#v ok=%v", med, ok)
|
||||
}
|
||||
mega, ok := CreditPackByID("mega")
|
||||
if !ok || mega.Credits != 8000 || mega.PriceUSD != 2999 {
|
||||
if !ok || mega.Credits != 8000 || mega.PriceEUR != 2999 {
|
||||
t.Fatalf("mega pack: %#v ok=%v", mega, ok)
|
||||
}
|
||||
if CreditPackSettingsKey("small") != "stripe.price.pack.small" {
|
||||
|
||||
@@ -1159,7 +1159,7 @@ func (s *Service) ListProcessedProducts(ctx context.Context, companyID uuid.UUID
|
||||
p.category,
|
||||
cat.name AS category_name,
|
||||
COALESCE(cat.unique_id, NULLIF(BTRIM(p.category), '')) AS category_unique_id,
|
||||
p.status, p.raw_product_id, COALESCE(p.feed_id, r.feed_id) AS feed_id, r.gtin,
|
||||
p.status, p.processing_origin, p.raw_product_id, COALESCE(p.feed_id, r.feed_id) AS feed_id, r.gtin,
|
||||
f.name AS feed_name,
|
||||
f.last_synced_at AS feed_last_synced_at,
|
||||
r.updated_at AS raw_updated_at,
|
||||
@@ -1184,7 +1184,7 @@ func (s *Service) ListProcessedProducts(ctx context.Context, companyID uuid.UUID
|
||||
defer rows.Close()
|
||||
items, err := scanMaps(rows, []string{
|
||||
"id", "product_id", "name", "original_name", "processed_name", "category", "category_name", "category_unique_id",
|
||||
"status", "raw_product_id", "feed_id", "gtin",
|
||||
"status", "processing_origin", "raw_product_id", "feed_id", "gtin",
|
||||
"feed_name", "feed_last_synced_at", "raw_updated_at",
|
||||
"has_name", "has_processed_name", "has_description", "has_processed_description", "has_category", "has_attributes", "has_processed_attributes",
|
||||
"has_eprel",
|
||||
@@ -1250,7 +1250,7 @@ func (s *Service) ListProcessedProductsDetailed(ctx context.Context, companyID u
|
||||
cat.name AS category_name,
|
||||
COALESCE(cat.unique_id, NULLIF(BTRIM(p.category), '')) AS category_unique_id,
|
||||
`+processedFeedCategorySQL+` AS feed_category,
|
||||
p.status, p.raw_product_id, p.feed_id, r.gtin,
|
||||
p.status, p.processing_origin, p.raw_product_id, p.feed_id, r.gtin,
|
||||
`+processedPreferredDescriptionSQL+` AS description,
|
||||
`+processedOriginalDescriptionSQL+` AS original_description,
|
||||
p.processed_name, p.processed_description,
|
||||
@@ -1268,7 +1268,7 @@ func (s *Service) ListProcessedProductsDetailed(ctx context.Context, companyID u
|
||||
items, err := scanMaps(rows, []string{
|
||||
"id", "product_id", "name", "original_name", "category", "category_name", "category_unique_id",
|
||||
"feed_category",
|
||||
"status", "raw_product_id", "feed_id", "gtin",
|
||||
"status", "processing_origin", "raw_product_id", "feed_id", "gtin",
|
||||
"description", "original_description", "processed_name", "processed_description",
|
||||
"meta_title", "meta_description",
|
||||
"attributes", "processed_attributes", "mapped_data",
|
||||
@@ -1299,7 +1299,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
|
||||
p.processed_name, p.processed_description,
|
||||
COALESCE(p.meta_title, '') AS meta_title,
|
||||
COALESCE(p.meta_description, '') AS meta_description,
|
||||
p.status, p.attributes, p.processed_attributes, r.gtin, r.mapped_data,
|
||||
p.status, p.processing_origin, p.attributes, p.processed_attributes, r.gtin, r.mapped_data,
|
||||
COALESCE(p.feed_id, r.feed_id) AS feed_id,
|
||||
f.name AS feed_name,
|
||||
f.last_synced_at AS feed_last_synced_at,
|
||||
@@ -1320,7 +1320,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
|
||||
"feed_category",
|
||||
"description", "original_description", "processed_name", "processed_description",
|
||||
"meta_title", "meta_description",
|
||||
"status", "attributes", "processed_attributes", "gtin", "mapped_data",
|
||||
"status", "processing_origin", "attributes", "processed_attributes", "gtin", "mapped_data",
|
||||
"feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
|
||||
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
|
||||
"has_eprel",
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Exports audited AI usage by company. This is an operational cost report, NOT
|
||||
// a customer invoice or the amount charged by Stripe.
|
||||
func (s *Server) handleAdminExportAICosts(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
from, to, err := adminCostRange(q.Get("from"), q.Get("to"), q.Get("days"))
|
||||
if err != nil {
|
||||
Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
args := []any{from, to}
|
||||
where := "day >= $1 AND day <= $2"
|
||||
if raw := strings.TrimSpace(q.Get("company_id")); raw != "" {
|
||||
cid, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
Error(w, http.StatusBadRequest, "invalid company_id")
|
||||
return
|
||||
}
|
||||
args = append(args, cid)
|
||||
where += " AND company_id = $3"
|
||||
}
|
||||
result, err := s.scanCostGroup(r.Context(), costGroupCompany, where, args)
|
||||
if err != nil {
|
||||
LogAndError(w, http.StatusInternalServerError, "could not export AI costs", err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-ai-usage-costs.csv"`)
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
out := csv.NewWriter(w)
|
||||
_ = out.Write([]string{"from", "to", "company_id", "company", "calls", "failed_calls", "input_tokens", "cached_input_tokens", "output_tokens", "total_tokens", "provider_cost_usd", "notice"})
|
||||
v := func(row map[string]any, key string) string { return strconv.FormatInt(int64(row[key].(int64)), 10) }
|
||||
for _, row := range result {
|
||||
cost := float64(row["cost_micros"].(int64)) / 1000000.0
|
||||
_ = out.Write([]string{from.Format("2006-01-02"), to.Format("2006-01-02"), row["id"].(string), row["label"].(string),
|
||||
v(row, "calls"), v(row, "failed_calls"), v(row, "prompt_tokens"), v(row, "cached_prompt_tokens"),
|
||||
v(row, "completion_tokens"), v(row, "total_tokens"), strconv.FormatFloat(cost, 'f', 6, 64),
|
||||
"Provider operating cost in USD; NOT client revenue, Stripe invoice, or payable total"})
|
||||
}
|
||||
out.Flush()
|
||||
}
|
||||
@@ -172,7 +172,7 @@ func (s *Server) scanCostGroup(ctx context.Context, group costGroup, whereSQL st
|
||||
COALESCE(sum(u.cost_micros),0)
|
||||
FROM ai_usage_daily u
|
||||
LEFT JOIN companies c ON c.id = u.company_id
|
||||
WHERE ` + whereSQL + `
|
||||
WHERE ` + strings.ReplaceAll(whereSQL, "company_id =", "u.company_id =") + `
|
||||
GROUP BY u.company_id, c.name
|
||||
ORDER BY COALESCE(sum(u.cost_micros),0) DESC
|
||||
LIMIT ` + strconv.Itoa(adminAICostsMaxRows)
|
||||
@@ -186,7 +186,7 @@ func (s *Server) scanCostGroup(ctx context.Context, group costGroup, whereSQL st
|
||||
FROM ai_usage_daily u
|
||||
LEFT JOIN users usr ON usr.id = u.user_id
|
||||
LEFT JOIN companies c ON c.id = u.company_id
|
||||
WHERE ` + whereSQL + `
|
||||
WHERE ` + strings.ReplaceAll(whereSQL, "company_id =", "u.company_id =") + `
|
||||
GROUP BY u.user_id, usr.email, u.company_id, c.name
|
||||
ORDER BY COALESCE(sum(u.cost_micros),0) DESC
|
||||
LIMIT ` + strconv.Itoa(adminAICostsMaxRows)
|
||||
@@ -198,7 +198,7 @@ func (s *Server) scanCostGroup(ctx context.Context, group costGroup, whereSQL st
|
||||
COALESCE(sum(u.completion_tokens),0), COALESCE(sum(u.total_tokens),0),
|
||||
COALESCE(sum(u.cost_micros),0)
|
||||
FROM ai_usage_daily u
|
||||
WHERE ` + whereSQL + `
|
||||
WHERE ` + strings.ReplaceAll(whereSQL, "company_id =", "u.company_id =") + `
|
||||
GROUP BY u.model
|
||||
ORDER BY COALESCE(sum(u.cost_micros),0) DESC
|
||||
LIMIT ` + strconv.Itoa(adminAICostsMaxRows)
|
||||
|
||||
@@ -151,13 +151,16 @@ func (s *Server) handleAdminAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
tokenByDay := map[string]adminDayPoint{}
|
||||
tokRows, err := s.Pool.Query(ctx, `
|
||||
SELECT (created_at AT TIME ZONE 'UTC')::date AS d,
|
||||
COALESCE(SUM(COALESCE(total_tokens, 0)), 0)::bigint,
|
||||
COUNT(*)::bigint
|
||||
FROM processed_products
|
||||
WHERE created_at >= $1
|
||||
GROUP BY 1
|
||||
ORDER BY 1`, since)
|
||||
WITH tokens AS (
|
||||
SELECT day AS d, COALESCE(SUM(total_tokens),0)::bigint AS tok
|
||||
FROM ai_usage_daily WHERE day >= $1::date GROUP BY 1
|
||||
), products AS (
|
||||
SELECT (created_at AT TIME ZONE 'UTC')::date AS d, COUNT(*)::bigint AS cnt
|
||||
FROM processed_products WHERE created_at >= $1 GROUP BY 1
|
||||
)
|
||||
SELECT COALESCE(t.d,p.d) AS d, COALESCE(t.tok,0)::bigint, COALESCE(p.cnt,0)::bigint
|
||||
FROM tokens t FULL OUTER JOIN products p ON t.d=p.d
|
||||
ORDER BY 1`, since)
|
||||
if err != nil {
|
||||
Error(w, http.StatusInternalServerError, "analytics token series failed")
|
||||
return
|
||||
@@ -326,7 +329,7 @@ func (s *Server) handleAdminAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
"providers": providers,
|
||||
"tokens_by_provider_detail": providerDetail,
|
||||
"notes": []string{
|
||||
"Tokens come from processed_products.total_tokens (LLM usage recorded per product).",
|
||||
"Tokens come from the durable ai_usage_daily call ledger (input + output), including multiple calls per product.",
|
||||
"Provider classes use processed_products.ai_provider_mode: internal | popular:<name> | custom (blank/unknown rolled into the internal card).",
|
||||
"Job tokens use processing_jobs.estimated_tokens (running tally during jobs).",
|
||||
"Jobs stuck = status running with updated_at older than 2 hours (same threshold as diagnostics).",
|
||||
@@ -353,12 +356,12 @@ func (s *Server) loadAdminAnalyticsSummary(ctx context.Context, since time.Time)
|
||||
(SELECT COUNT(*)::bigint FROM companies WHERE created_at >= $1),
|
||||
(SELECT COALESCE(SUM(total_credits), 0)::bigint FROM credit_balances),
|
||||
(SELECT COALESCE(SUM(used_credits), 0)::bigint FROM credit_balances),
|
||||
(SELECT COALESCE(SUM(COALESCE(total_tokens, 0)), 0)::bigint FROM processed_products),
|
||||
(SELECT COALESCE(SUM(total_tokens), 0)::bigint FROM ai_usage_daily),
|
||||
(SELECT COUNT(*)::bigint FROM processed_products),
|
||||
(SELECT COUNT(*)::bigint FROM raw_products),
|
||||
(SELECT COUNT(*)::bigint FROM input_feeds),
|
||||
(SELECT COUNT(*)::bigint FROM export_feeds),
|
||||
(SELECT COALESCE(SUM(COALESCE(total_tokens, 0)), 0)::bigint FROM processed_products WHERE created_at >= $1),
|
||||
(SELECT COALESCE(SUM(total_tokens), 0)::bigint FROM ai_usage_daily WHERE day >= $1::date),
|
||||
(SELECT COUNT(*)::bigint FROM processing_jobs WHERE created_at >= $1 AND status = 'failed'),
|
||||
(SELECT COUNT(*)::bigint FROM processing_jobs WHERE created_at >= $1 AND status = 'completed'),
|
||||
(SELECT COUNT(*)::bigint FROM processing_jobs
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Platform-admin export of actual Stripe invoice amounts (not estimated usage).
|
||||
// Scope must be a single company; customer IDs are resolved server-side.
|
||||
func (s *Server) handleAdminExportCompanyInvoices(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := uuid.Parse(strings.TrimSpace(r.URL.Query().Get("company_id")))
|
||||
if err != nil {
|
||||
Error(w, http.StatusBadRequest, "company_id is required")
|
||||
return
|
||||
}
|
||||
rows, err := s.stripeSvc().ListCompanyInvoices(r.Context(), id)
|
||||
if err != nil {
|
||||
LogAndError(w, http.StatusBadGateway, "could not export Stripe invoices", err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-stripe-invoices.csv"`)
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
out := csv.NewWriter(w)
|
||||
_ = out.Write([]string{"company_id", "invoice_id", "number", "status", "currency", "created_unix", "amount_due_minor", "amount_paid_minor", "amount_remaining_minor", "hosted_invoice_url", "invoice_pdf"})
|
||||
for _, row := range rows {
|
||||
_ = out.Write([]string{id.String(), row.ID, row.Number, row.Status, row.Currency,
|
||||
strconv.FormatInt(row.Created, 10), strconv.FormatInt(row.AmountDue, 10),
|
||||
strconv.FormatInt(row.AmountPaid, 10), strconv.FormatInt(row.AmountRemaining, 10),
|
||||
row.HostedInvoiceURL, row.InvoicePDF})
|
||||
}
|
||||
out.Flush()
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var editableCostFeatures = map[string]bool{
|
||||
"product_processing": true,
|
||||
"openai_token_k": true,
|
||||
"seo_meta_ai": true,
|
||||
"campaign_copy": true,
|
||||
}
|
||||
|
||||
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
|
||||
UNION ALL
|
||||
SELECT 'plan', plan_id::text, feature_name, cost_per_unit FROM plan_processing_costs
|
||||
UNION ALL
|
||||
SELECT 'company', company_id::text, feature_name, cost_per_unit FROM company_processing_costs
|
||||
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 int
|
||||
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 *int `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 && (*body.Cost < 1 || *body.Cost > 1000000)) {
|
||||
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"})
|
||||
}
|
||||
@@ -57,12 +57,12 @@ func (s *Server) handleAdminSyncStripeCreditPacks(w http.ResponseWriter, r *http
|
||||
return
|
||||
}
|
||||
written = append(written, map[string]any{
|
||||
"pack_id": row.PackID,
|
||||
"product_id": row.ProductID,
|
||||
"price_id": row.PriceID,
|
||||
"credits": row.Credits,
|
||||
"price_usd": row.PriceUSD,
|
||||
"created": row.Created,
|
||||
"pack_id": row.PackID,
|
||||
"product_id": row.ProductID,
|
||||
"price_id": row.PriceID,
|
||||
"credits": row.Credits,
|
||||
"price_eur": row.PriceEUR,
|
||||
"created": row.Created,
|
||||
"settings_key": key,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -155,3 +155,19 @@ func (s *Server) handleRunBillingCycles(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
JSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// handleListBillingInvoices lists genuine Stripe invoices for the active company.
|
||||
// Private Stripe payment and PDF links are only accessible to company owners.
|
||||
func (s *Server) handleListBillingInvoices(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.allowCompanyOwnerOrPlatform(w, r) {
|
||||
return
|
||||
}
|
||||
cid, _ := CompanyIDFromContext(r.Context())
|
||||
invoices, err := s.stripeSvc().ListCompanyInvoices(r.Context(), cid)
|
||||
if err != nil {
|
||||
LogAndError(w, http.StatusBadGateway, "could not load invoices", err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
JSON(w, http.StatusOK, map[string]any{"invoices": invoices, "source": "stripe"})
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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()
|
||||
}
|
||||
@@ -403,7 +403,14 @@ func (s *Server) handleSyncAndProcessSample(w http.ResponseWriter, r *http.Reque
|
||||
return
|
||||
}
|
||||
|
||||
procJobs, err := s.Processing.StartJob(r.Context(), cid, uid, rawIDs, processingType)
|
||||
// Public API feed sample processing is API-origin too. The session-based
|
||||
// feed preview keeps the review workflow used by the dashboard.
|
||||
var procJobs []processing.Job
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v1/") {
|
||||
procJobs, err = s.Processing.StartAPIJob(r.Context(), cid, uid, rawIDs, processingType)
|
||||
} else {
|
||||
procJobs, err = s.Processing.StartJob(r.Context(), cid, uid, rawIDs, processingType)
|
||||
}
|
||||
if err != nil {
|
||||
ClientOrLog(w, http.StatusBadRequest, "could not start processing", err, processing.ClientError)
|
||||
return
|
||||
|
||||
@@ -43,6 +43,7 @@ var apiFeatureRoutes = map[string]string{
|
||||
"/api/billing/checkout": "billing.checkout",
|
||||
"/api/billing/portal": "billing.customer_portal",
|
||||
"/api/billing/usage": "billing.overview",
|
||||
"/api/billing/invoices": "billing.overview",
|
||||
"/api/billing/plans": "billing.plans_compare",
|
||||
"/api/billing/credit-packs": "billing.overview",
|
||||
"/api/billing/stripe": "billing.overview",
|
||||
|
||||
@@ -3,6 +3,7 @@ package httpapi
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/billing"
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/processing"
|
||||
@@ -40,7 +41,15 @@ func (s *Server) handleStartProcessingJob(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
jobs, err := s.Processing.StartJob(r.Context(), cid, uid, ids, body.ProcessingType)
|
||||
// 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)
|
||||
} else {
|
||||
jobs, err = s.Processing.StartJob(r.Context(), cid, uid, ids, body.ProcessingType)
|
||||
}
|
||||
if err != nil {
|
||||
if writePlanGate(w, err) {
|
||||
return
|
||||
|
||||
@@ -407,6 +407,10 @@ func (s *Server) Router() http.Handler {
|
||||
r.Get("/diagnostics", s.handleAdminDiagnostics)
|
||||
r.Get("/ai-calls", s.handleAdminListAICalls)
|
||||
r.Get("/ai-costs", s.handleAdminAICosts)
|
||||
r.Get("/ai-costs/export", s.handleAdminExportAICosts)
|
||||
r.Get("/billing/invoices/export", s.handleAdminExportCompanyInvoices)
|
||||
r.Get("/processing-costs", s.handleAdminGetProcessingCosts)
|
||||
r.Put("/processing-costs", s.handleAdminPutProcessingCost)
|
||||
r.Get("/ai-calls/{id}", s.handleAdminGetAICall)
|
||||
r.Get("/analytics", s.handleAdminAnalytics)
|
||||
r.Get("/jobs", s.handleAdminListJobs)
|
||||
@@ -476,6 +480,8 @@ func (s *Server) Router() http.Handler {
|
||||
r.Get("/billing/credits", s.handleCreditsOverview)
|
||||
r.Get("/billing/capabilities", s.handleGetCapabilities)
|
||||
r.Get("/billing/usage", s.handleBillingUsage)
|
||||
r.Get("/billing/usage/export", s.handleBillingUsageExport)
|
||||
r.Get("/billing/invoices", s.handleListBillingInvoices)
|
||||
r.Get("/billing/plans", s.handleListPublicPlans)
|
||||
r.Get("/billing/credit-packs", s.handleListCreditPacks)
|
||||
r.Get("/billing/stripe", s.handleStripeStatus)
|
||||
|
||||
@@ -18,12 +18,9 @@ info:
|
||||
## Authentication
|
||||
|
||||
Public /api/v1 operations require a company API key (Bearer or X-API-Key)
|
||||
except GET /health and GET /openapi.yaml. Dashboard-only Team/Admin
|
||||
operations described separately use a signed-in session and CSRF header;
|
||||
they are not executable with a company API key.
|
||||
except GET /health and GET /openapi.yaml.
|
||||
|
||||
Document-level security is BearerAuth OR ApiKeyAuth (same key value).
|
||||
Do not send dashboard session cookies or CSRF tokens to /api/v1.
|
||||
|
||||
### Security schemes (components.securitySchemes)
|
||||
|
||||
@@ -38,10 +35,8 @@ info:
|
||||
|
||||
1. Sign in at https://api.descrybe.io
|
||||
2. Open Settings -> API keys (/settings?tab=api-keys)
|
||||
3. Company admins or teammates granted API Keys management permission create
|
||||
a key via dashboard POST /api/api-keys
|
||||
(session cookie + CSRF; not this public OpenAPI surface). The secret is
|
||||
shown once and starts with dk_.
|
||||
3. Authorized users can create keys in Settings -> API keys. The secret is
|
||||
shown once and starts with dk_.
|
||||
4. Store it securely. Later list/revoke shows only key_prefix (first 10
|
||||
characters). Revoked keys fail auth immediately.
|
||||
|
||||
@@ -64,22 +59,19 @@ info:
|
||||
|
||||
### 403 Forbidden
|
||||
|
||||
Bad API keys on /api/v1 never return 403 (always 401). Tenant scope comes
|
||||
from the key; cross-company resources typically 404. HTTP 403 appears on
|
||||
dashboard /api/* session routes (admin required, CSRF mismatch) under
|
||||
Team/Admin tags (SessionCookie + CSRFHeader) - not this public key surface.
|
||||
Invalid API keys return 401. Access to unrelated company resources
|
||||
is denied by tenant-scoped authorization.
|
||||
|
||||
### Rate limits
|
||||
|
||||
Heavy mutations are limited to 30 requests per minute per company
|
||||
(in-process per API replica; not shared across replicas). Counts HTTP
|
||||
requests, not products inside a bulk body. Limited POST paths:
|
||||
Processing and feed mutations are rate limited. Counts are per HTTP
|
||||
request, not per product in a batch. Limited POST paths:
|
||||
|
||||
- /products/process, /process, /process/{id}/retry
|
||||
- /feeds/{id}/sync, /feeds/{id}/extract-schema, /feeds/{id}/sync-process-sample
|
||||
- /export-feeds/{id}/generate, /export-feeds/{id}/export-products, /export-feeds/{id}/rotate-token (admin)
|
||||
- /export-feeds/{id}/generate, /export-feeds/{id}/export-products, /export-feeds/{id}/rotate-token
|
||||
|
||||
Over limit: HTTP 429, header Retry-After: 60, body
|
||||
Over limit: HTTP 429 with Retry-After and body
|
||||
{ "error": "rate limit exceeded" } (see TooManyRequests). Ordinary GETs and
|
||||
other mutations are outside this HTTP budget (process starts may still return
|
||||
402 for plan/credits).
|
||||
@@ -104,8 +96,8 @@ info:
|
||||
- Plan gates (credits / product limit / AI / EPREL / feature flags) run before
|
||||
EnsureRaw catalog writes on the items[].ean path; blocked starts return HTTP 402
|
||||
|
||||
2. **Internal / dashboard-style jobs**
|
||||
- POST /process with raw_product_ids (same body as POST /api/processing/jobs)
|
||||
2. **Product processing jobs**
|
||||
- POST /process with existing raw_product_ids
|
||||
- GET /process, GET /process/{id}, cancel/terminate/retry
|
||||
- Flat JSON (no data wrapper); 202 Accepted on start/retry
|
||||
- Plan gates return HTTP 402 with PlanGateError (error + code + upgrade_url)
|
||||
@@ -142,8 +134,7 @@ info:
|
||||
product titles or descriptions. Company feature policies may still suppress
|
||||
metadata output.
|
||||
|
||||
Note: Dashboard JSON under /api/* uses session cookies + CSRF and is separate
|
||||
from this public API-key surface. Other path aliases
|
||||
Other path aliases
|
||||
(/categories/create, /attributes/create, /campaigns) appear next to canonical paths.
|
||||
servers:
|
||||
- url: https://api.descrybe.io/api/v1
|
||||
@@ -161,10 +152,6 @@ tags:
|
||||
- name: Campaigns
|
||||
description: Seasonal content calendar (/campaigns aliases)
|
||||
- name: Processing
|
||||
- name: Team
|
||||
description: Dashboard session routes under /api (not API-key)
|
||||
- name: Admin
|
||||
description: Platform-admin dashboard routes under /api (not API-key)
|
||||
paths:
|
||||
/health:
|
||||
get:
|
||||
@@ -498,7 +485,7 @@ paths:
|
||||
responses:
|
||||
'200':
|
||||
description: Selected products returned to unprocessed. Returned when ResetProductsToUnprocessed
|
||||
commits. Requires company-admin capability (API keys use role api and pass).
|
||||
commits. Requires a valid company API key.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@@ -528,14 +515,14 @@ paths:
|
||||
example:
|
||||
error: product_ids is required
|
||||
'403':
|
||||
description: Caller role is neither admin nor api (requireCompanyAdmin). Valid company API keys
|
||||
description: Access denied. Valid company API keys
|
||||
use role api and do not hit this.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'500':
|
||||
description: Unexpected reset failure after validation.
|
||||
content:
|
||||
@@ -642,15 +629,13 @@ paths:
|
||||
example:
|
||||
error: internal error
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -762,15 +747,13 @@ paths:
|
||||
example:
|
||||
error: internal error
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'404':
|
||||
description: Resource id not found for this API-key company (or wrong tenant).
|
||||
content:
|
||||
@@ -1034,15 +1017,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -1350,15 +1331,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -1467,15 +1446,13 @@ paths:
|
||||
example:
|
||||
error: internal error
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -1550,15 +1527,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -1931,15 +1906,13 @@ paths:
|
||||
example:
|
||||
error: internal error
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -2013,15 +1986,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -2321,15 +2292,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -2447,15 +2416,13 @@ paths:
|
||||
example:
|
||||
error: internal error
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -2482,7 +2449,7 @@ paths:
|
||||
- Feeds
|
||||
summary: Delete feed
|
||||
description: >-
|
||||
Company-admin only. Atomically removes the input feed and its exclusively
|
||||
Removes the input feed and its exclusively
|
||||
owned, unprocessed or failed raw products. Previously processed products
|
||||
are retained; active processing rows are not deleted, and products shared
|
||||
with another existing feed are reassigned to that feed. Flat response
|
||||
@@ -2508,13 +2475,13 @@ paths:
|
||||
example:
|
||||
error: invalid id
|
||||
'403':
|
||||
description: requireCompanyAdmin rejected the caller (session non-admin). API keys pass.
|
||||
description: Access denied.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'404':
|
||||
description: Feed not found.
|
||||
content:
|
||||
@@ -2608,15 +2575,13 @@ paths:
|
||||
code: not_found
|
||||
message: Feed not found
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -2726,15 +2691,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -2834,15 +2797,13 @@ paths:
|
||||
example:
|
||||
error: internal error
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -2934,15 +2895,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -2971,7 +2930,7 @@ paths:
|
||||
- Feeds
|
||||
summary: Sync feed then process a sample of raw products
|
||||
description: |
|
||||
Optionally syncs the feed, then starts dashboard-style processing for up to N raw products
|
||||
Optionally syncs the feed, then starts processing for up to N raw products
|
||||
(default 10, max 100). Flat JSON; HTTP 202 when a job is queued, 200 when sync finishes with no products.
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/ID"
|
||||
@@ -3061,15 +3020,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -3342,15 +3299,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -3450,15 +3405,13 @@ paths:
|
||||
example:
|
||||
error: internal error
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -3484,10 +3437,10 @@ paths:
|
||||
tags:
|
||||
- Export feeds
|
||||
summary: Delete export feed
|
||||
description: "Company-admin only. Flat { status: ok } (not SuccessMessage)."
|
||||
description: "Delete an export feed. Returns a deletion confirmation."
|
||||
responses:
|
||||
'200':
|
||||
description: Export feed deleted (admin capability; API keys pass). Flat deleted marker.
|
||||
description: Export feed deleted.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@@ -3504,13 +3457,13 @@ paths:
|
||||
example:
|
||||
error: invalid id
|
||||
'403':
|
||||
description: requireCompanyAdmin rejected session non-admin.
|
||||
description: Access denied.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'404':
|
||||
description: Export feed not found.
|
||||
content:
|
||||
@@ -3640,15 +3593,13 @@ paths:
|
||||
example:
|
||||
error: internal error
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -3677,7 +3628,7 @@ paths:
|
||||
summary: Rotate public export URL token
|
||||
description: |
|
||||
Replaces public_token so the previous /api/public/export-feeds/{token}.{xml|csv|json}
|
||||
URL stops working immediately. Requires company admin (or platform staff).
|
||||
URL stops working immediately.
|
||||
Response is a flat ExportFeedDetail including the new public_token.
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/ID"
|
||||
@@ -3703,13 +3654,13 @@ paths:
|
||||
schema:
|
||||
$ref: "#/components/schemas/CodedAPIError"
|
||||
'403':
|
||||
description: Admin required.
|
||||
description: Access denied.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"422": { $ref: "#/components/responses/ValidationError" }
|
||||
"500": { $ref: "#/components/responses/InternalServerError" }
|
||||
@@ -3792,15 +3743,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -3901,15 +3850,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -4294,7 +4241,7 @@ paths:
|
||||
- $ref: "#/components/parameters/Limit"
|
||||
responses:
|
||||
'200':
|
||||
description: "Recent dashboard-style jobs. Flat object with jobs[] and limit (handleV1ListProcessJobs\
|
||||
description: "Recent processing jobs. Flat object with jobs[] and limit (\
|
||||
\ — not a data envelope)."
|
||||
content:
|
||||
application/json:
|
||||
@@ -4343,7 +4290,7 @@ paths:
|
||||
summary: Start processing job by raw_product_ids
|
||||
description: |
|
||||
Enqueues AI processing for existing raw product UUIDs.
|
||||
Same pipeline as dashboard POST /api/processing/jobs.
|
||||
Uses the standard product processing pipeline.
|
||||
Flat JSON body/response (no data wrapper); HTTP 202.
|
||||
Pass raw_products.id only (GET /products data[].raw_product_id), never PresentProduct.id.
|
||||
|
||||
@@ -4505,15 +4452,13 @@ paths:
|
||||
example:
|
||||
error: internal error
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'422':
|
||||
description: Validation failed. Current public v1 handlers emit these cases as HTTP 400 (flat
|
||||
or coded). 422 is documented for clients that expect an explicit validation status; body matches
|
||||
@@ -4582,15 +4527,13 @@ paths:
|
||||
example:
|
||||
error: internal error
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'404':
|
||||
description: Resource id not found for this API-key company (or wrong tenant).
|
||||
content:
|
||||
@@ -4668,15 +4611,13 @@ paths:
|
||||
example:
|
||||
error: internal error
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'404':
|
||||
description: Resource id not found for this API-key company (or wrong tenant).
|
||||
content:
|
||||
@@ -4754,15 +4695,13 @@ paths:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'403':
|
||||
description: Insufficient role or wrong company. On API-key routes, cross-tenant ids usually
|
||||
return 404 instead. requireCompanyAdmin returns flat 'admin required' for session non-admin
|
||||
callers (API keys use role api and pass).
|
||||
description: Access denied or resource unavailable to this company.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
error: forbidden
|
||||
'404':
|
||||
description: Resource id not found for this API-key company (or wrong tenant).
|
||||
content:
|
||||
@@ -4792,265 +4731,6 @@ paths:
|
||||
error:
|
||||
code: validation_error
|
||||
message: invalid json
|
||||
/team/{userID}:
|
||||
parameters:
|
||||
- name: userID
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Membership user id within the selected company
|
||||
patch:
|
||||
tags:
|
||||
- Team
|
||||
summary: Update team member role
|
||||
description: |
|
||||
Company admin or platform admin. Demoting the last active admin returns 409.
|
||||
Requires session cookie + CSRF double-submit (X-CSRF-Token).
|
||||
Dashboard surface under /api (not the public /api/v1 API-key base).
|
||||
security:
|
||||
- SessionCookie: []
|
||||
CSRFHeader: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- role
|
||||
properties:
|
||||
role:
|
||||
type: string
|
||||
enum:
|
||||
- admin
|
||||
- member
|
||||
description: Normalized to admin|member (case-insensitive input accepted)
|
||||
example:
|
||||
role: member
|
||||
responses:
|
||||
'200':
|
||||
description: Role updated (or unchanged)
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- status
|
||||
- role
|
||||
- user_id
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
example: ok
|
||||
role:
|
||||
type: string
|
||||
enum:
|
||||
- admin
|
||||
- member
|
||||
user_id:
|
||||
type: string
|
||||
format: uuid
|
||||
example:
|
||||
status: ok
|
||||
role: member
|
||||
user_id: 4f3c2b1a-0e9d-4c8b-7a6f-5e4d3c2b1a09
|
||||
'400':
|
||||
description: Invalid request for this route (HTTP 400).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: invalid json
|
||||
'403':
|
||||
description: Forbidden (not company/platform admin)
|
||||
'404':
|
||||
description: Resource not found (HTTP 404).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: not found
|
||||
'409':
|
||||
description: Cannot demote the last admin
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: cannot demote the last admin
|
||||
'401':
|
||||
description: Missing or invalid API key. RequireAPIKey returns this when Authorization Bearer
|
||||
and X-API-Key are both absent/empty or AuthenticateAPIKey returns ErrInvalidAPIKey. Coded
|
||||
envelope (not a flat string).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/CodedAPIError"
|
||||
example:
|
||||
error:
|
||||
code: unauthorized
|
||||
message: Unauthorized
|
||||
'422':
|
||||
description: Validation failed. Dashboard routes may use this status; prefer reading the message.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: validation failed
|
||||
'500':
|
||||
description: Unexpected server error (HTTP 500).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: list failed
|
||||
/admin/emails/set-password:
|
||||
post:
|
||||
tags:
|
||||
- Admin
|
||||
summary: Re-issue set-password invites
|
||||
description: |
|
||||
Platform admin only. Prefers durable invite reissue (ReissueSetPasswordInvite);
|
||||
falls back to HMAC set-password tokens when the user has no active membership.
|
||||
Skips synthetic placeholder emails. Rate-limited per admin.
|
||||
When SMTP is disabled and a single user_id is provided, the response may include
|
||||
a one-time token for local/staging link copy (never logs email/token).
|
||||
Dashboard surface under /api (not the public /api/v1 API-key base).
|
||||
security:
|
||||
- SessionCookie: []
|
||||
CSRFHeader: []
|
||||
requestBody:
|
||||
required: false
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
user_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: |
|
||||
Target user UUID. When omitted, bulk-targets users needing a password (capped).
|
||||
example:
|
||||
user_id: 4f3c2b1a-0e9d-4c8b-7a6f-5e4d3c2b1a09
|
||||
responses:
|
||||
'200':
|
||||
description: Issue/send summary
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- sent
|
||||
- issued
|
||||
- skipped
|
||||
- smtp_enabled
|
||||
- mode
|
||||
properties:
|
||||
sent:
|
||||
type: integer
|
||||
issued:
|
||||
type: integer
|
||||
skipped:
|
||||
type: integer
|
||||
skipped_synthetic:
|
||||
type: integer
|
||||
skipped_ineligible:
|
||||
type: integer
|
||||
skipped_rate_limited:
|
||||
type: integer
|
||||
skipped_send:
|
||||
type: integer
|
||||
smtp_enabled:
|
||||
type: boolean
|
||||
mode:
|
||||
type: string
|
||||
example: invite
|
||||
token:
|
||||
type: string
|
||||
description: Present only for single-user reissue when SMTP is off
|
||||
example:
|
||||
sent: 1
|
||||
issued: 1
|
||||
skipped: 0
|
||||
skipped_synthetic: 0
|
||||
skipped_ineligible: 0
|
||||
skipped_rate_limited: 0
|
||||
skipped_send: 0
|
||||
smtp_enabled: true
|
||||
mode: invite
|
||||
'401':
|
||||
description: Unauthorized — missing session or privilege for this dashboard route.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: unauthorized
|
||||
'429':
|
||||
description: Rate limit exceeded for this admin action. May include Retry-After.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: Too many requests
|
||||
'503':
|
||||
description: Dependency unavailable (for example mailer down).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: mailer unavailable
|
||||
'400':
|
||||
description: Invalid request for this route (HTTP 400).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: invalid json
|
||||
'403':
|
||||
description: Forbidden for this route (HTTP 403).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: admin required
|
||||
'409':
|
||||
description: Conflict with current resource state.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: conflict
|
||||
'422':
|
||||
description: Validation failed. Dashboard routes may use this status; prefer reading the message.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: validation failed
|
||||
'500':
|
||||
description: Unexpected server error (HTTP 500).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/FlatAPIError"
|
||||
example:
|
||||
error: list failed
|
||||
components:
|
||||
securitySchemes:
|
||||
BearerAuth:
|
||||
@@ -5074,18 +4754,6 @@ components:
|
||||
Alternate scheme for /api/v1. Same company API key as BearerAuth, sent
|
||||
as header X-API-Key: dk_your_key. When both Authorization Bearer and
|
||||
X-API-Key are present, Bearer wins.
|
||||
SessionCookie:
|
||||
type: apiKey
|
||||
in: cookie
|
||||
name: descrybe_session
|
||||
description: Dashboard session cookie only (SESSION_COOKIE_NAME; default descrybe_session). Not
|
||||
valid for /api/v1 public routes.
|
||||
CSRFHeader:
|
||||
type: apiKey
|
||||
in: header
|
||||
name: X-CSRF-Token
|
||||
description: Dashboard CSRF double-submit header (must match descrybe_csrf cookie). Not used by
|
||||
/api/v1 API-key routes.
|
||||
parameters:
|
||||
ID:
|
||||
in: path
|
||||
|
||||
@@ -11,6 +11,27 @@ import (
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func TestV1OpenAPIYAMLDoesNotPublishAdminRoutes(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := mustParseOpenAPIRoot(t, v1OpenAPIYAML)
|
||||
paths, ok := root["paths"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatal("missing paths map")
|
||||
}
|
||||
for path := range paths {
|
||||
if strings.HasPrefix(path, "/admin/") || strings.HasPrefix(path, "/team/") {
|
||||
t.Fatalf("non-public dashboard path leaked: %s", path)
|
||||
}
|
||||
}
|
||||
schemes := root["components"].(map[string]any)["securitySchemes"].(map[string]any)
|
||||
if _, ok := schemes["SessionCookie"]; ok {
|
||||
t.Fatal("session-cookie authentication leaked into public docs")
|
||||
}
|
||||
if _, ok := schemes["CSRFHeader"]; ok {
|
||||
t.Fatal("CSRF authentication leaked into public docs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestV1OpenAPIYAMLParses(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -375,7 +375,7 @@ func (s *Server) startV1Jobs(ctx context.Context, companyID, userID uuid.UUID, r
|
||||
if s != nil && s.testStartJobs != nil {
|
||||
return s.testStartJobs(ctx, companyID, userID, rawIDs, processingType)
|
||||
}
|
||||
return s.Processing.StartJob(ctx, companyID, userID, rawIDs, processingType)
|
||||
return s.Processing.StartAPIJob(ctx, companyID, userID, rawIDs, processingType)
|
||||
}
|
||||
|
||||
func (s *Server) enqueueV1Job(ctx context.Context, jobID uuid.UUID) error {
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package processing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// API jobs and dashboard jobs share one catalog. API completion is immediately
|
||||
// visible in Processed; dashboard jobs retain explicit Needs review approval.
|
||||
func TestAPIProcessedProductVisibleInCatalog(t *testing.T) {
|
||||
dsn := os.Getenv("DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("DATABASE_URL is not set")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
pg, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pg.Close()
|
||||
|
||||
var userID uuid.UUID
|
||||
if err := pg.QueryRow(ctx, `SELECT id FROM users LIMIT 1`).Scan(&userID); err != nil {
|
||||
t.Skipf("test user unavailable: %v", err)
|
||||
}
|
||||
companyID := uuid.New()
|
||||
if _, err := pg.Exec(ctx, `INSERT INTO companies (id,name) VALUES ($1,'API catalog visibility test')`, companyID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cleanupCancel()
|
||||
_, _ = pg.Exec(cleanupCtx, `DELETE FROM processing_job_products WHERE job_id IN (SELECT id FROM processing_jobs WHERE company_id=$1)`, companyID)
|
||||
_, _ = pg.Exec(cleanupCtx, `DELETE FROM processing_jobs WHERE company_id=$1`, companyID)
|
||||
_, _ = pg.Exec(cleanupCtx, `DELETE FROM processed_products WHERE company_id=$1`, companyID)
|
||||
_, _ = pg.Exec(cleanupCtx, `DELETE FROM raw_products WHERE company_id=$1`, companyID)
|
||||
_, _ = pg.Exec(cleanupCtx, `DELETE FROM companies WHERE id=$1`, companyID)
|
||||
}()
|
||||
|
||||
raws := []uuid.UUID{uuid.New(), uuid.New()}
|
||||
for i, id := range raws {
|
||||
if _, err := pg.Exec(ctx, `INSERT INTO raw_products (id,company_id,gtin,raw_data,mapped_data,is_processed,processing_status)
|
||||
VALUES ($1,$2,$3,'{}'::jsonb,'{}'::jsonb,false,'unprocessed')`, id, companyID, []string{"1234567890123", "1234567890124"}[i]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
p := NewPipeline(pg)
|
||||
p.Billing = nil
|
||||
p.Limiter = nil
|
||||
apiJobs, err := p.StartAPIJob(ctx, companyID, userID, raws[:1], "full")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
uiJobs, err := p.StartJob(ctx, companyID, userID, raws[1:], "full")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(apiJobs) != 1 || len(uiJobs) != 1 {
|
||||
t.Fatal("expected one job each")
|
||||
}
|
||||
for _, check := range []struct {
|
||||
id uuid.UUID
|
||||
origin string
|
||||
}{{apiJobs[0].ID, "api"}, {uiJobs[0].ID, "dashboard"}} {
|
||||
var actual string
|
||||
if err := pg.QueryRow(ctx, `SELECT origin FROM processing_jobs WHERE id=$1`, check.id).Scan(&actual); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if actual != check.origin {
|
||||
t.Fatalf("job origin=%q want %q", actual, check.origin)
|
||||
}
|
||||
}
|
||||
|
||||
for i, origin := range []string{"api", "dashboard"} {
|
||||
original := "Supplier title"
|
||||
title := "AI title"
|
||||
if i == 1 {
|
||||
title = "Dashboard title"
|
||||
}
|
||||
result := StepResult{
|
||||
Name: original, Description: "Supplier description", ProcessedName: title,
|
||||
ProcessedDescription: "Updated AI description", MetaTitle: "SEO title", MetaDescription: "SEO description",
|
||||
Attributes: map[string]any{}, ProcessedAttributes: map[string]any{"power": "5W"},
|
||||
GPTResponse: map[string]any{}, FieldSources: map[string]any{},
|
||||
}
|
||||
_, err := p.upsertProcessedProduct(ctx, nil, companyID, raws[i], []string{"1234567890123", "1234567890124"}[i], result, []byte(`{}`), []byte(`{"power":"5W"}`), []byte(`{}`), []byte(`{}`), "internal", "sl", origin)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
svc := &catalog.Service{Pool: pg}
|
||||
approved, total, err := svc.ListProcessedProducts(ctx, companyID, catalog.ProductFilter{Status: "completed", Limit: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total != 1 || len(approved) != 1 {
|
||||
t.Fatalf("completed total=%d items=%d", total, len(approved))
|
||||
}
|
||||
if approved[0]["processing_origin"] != "api" || approved[0]["name"] != "AI title" {
|
||||
t.Fatalf("API result missing: %+v", approved[0])
|
||||
}
|
||||
reviewed, reviewTotal, err := svc.ListProcessedProducts(ctx, companyID, catalog.ProductFilter{Status: "needs_review", Limit: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reviewTotal != 1 || len(reviewed) != 1 {
|
||||
t.Fatalf("review total=%d", reviewTotal)
|
||||
}
|
||||
if reviewed[0]["processing_origin"] != "dashboard" {
|
||||
t.Fatalf("dashboard status changed: %+v", reviewed[0])
|
||||
}
|
||||
productID, err := uuid.Parse(fmt.Sprint(approved[0]["id"]))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A later API SEO-only run must update SEO fields without erasing an earlier
|
||||
// AI title, description, category, attributes or localized content.
|
||||
seo := StepResult{MetaTitle: "Revised SEO title", MetaDescription: "Revised SEO description", Attributes: map[string]any{}, ProcessedAttributes: map[string]any{}, GPTResponse: map[string]any{}, FieldSources: map[string]any{}}
|
||||
_, err = p.upsertProcessedProduct(ctx, nil, companyID, raws[0], "1234567890123", seo, []byte(`{}`), []byte(`{}`), []byte(`{}`), []byte(`{}`), "internal", "sl", "api")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The list must still show the same product once (upsert, not duplicate).
|
||||
_, afterTotal, err := svc.ListProcessedProducts(ctx, companyID, catalog.ProductFilter{Status: "completed", Limit: 20})
|
||||
if err != nil || afterTotal != 1 {
|
||||
t.Fatalf("API reprocess duplicated/missing product total=%d: %v", afterTotal, err)
|
||||
}
|
||||
detail, err := svc.GetProcessedProduct(ctx, companyID, productID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail["processed_description"] != "Updated AI description" {
|
||||
t.Fatalf("SEO-only pass erased description: %+v", detail)
|
||||
}
|
||||
if detail["processed_name"] != "AI title" || detail["meta_title"] != "Revised SEO title" || detail["meta_description"] != "Revised SEO description" {
|
||||
t.Fatalf("missing processed detail: %+v", detail)
|
||||
}
|
||||
otherCompany := uuid.New()
|
||||
_, otherTotal, err := svc.ListProcessedProducts(ctx, otherCompany, catalog.ProductFilter{Status: "completed", Limit: 20})
|
||||
if err != nil || otherTotal != 0 {
|
||||
t.Fatalf("company data leaked: %d %v", otherTotal, err)
|
||||
}
|
||||
}
|
||||
@@ -135,6 +135,16 @@ type Job struct {
|
||||
// of ≤maxJobProducts so ClaimNext SKIP LOCKED workers stay parallelizable.
|
||||
// Absolute request cap is MaxStartProducts (100k–1M scale).
|
||||
func (p *Pipeline) StartJob(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string) ([]Job, error) {
|
||||
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "dashboard")
|
||||
}
|
||||
|
||||
// StartAPIJob uses the same processing pipeline and company-scoped catalog as the
|
||||
// dashboard, but completed API results do not require a dashboard approval action.
|
||||
func (p *Pipeline) StartAPIJob(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string) ([]Job, error) {
|
||||
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "api")
|
||||
}
|
||||
|
||||
func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType, origin string) ([]Job, error) {
|
||||
if processingType == "" {
|
||||
processingType = "full"
|
||||
}
|
||||
@@ -191,9 +201,9 @@ func (p *Pipeline) StartJob(ctx context.Context, companyID, userID uuid.UUID, ra
|
||||
var jobID uuid.UUID
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO processing_jobs (
|
||||
company_id, user_id, status, total_products, processing_type, current_step, step_progress
|
||||
) VALUES ($1, $2, 'pending', $3, $4, $5, $6::jsonb) RETURNING id`,
|
||||
companyID, userID, len(chunk), processingType, firstStep, progressJSON).Scan(&jobID)
|
||||
company_id, user_id, status, total_products, processing_type, current_step, step_progress, origin
|
||||
) VALUES ($1, $2, 'pending', $3, $4, $5, $6::jsonb, $7) RETURNING id`,
|
||||
companyID, userID, len(chunk), processingType, firstStep, progressJSON, origin).Scan(&jobID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -590,12 +600,12 @@ func (p *Pipeline) RetryJob(ctx context.Context, companyID, id uuid.UUID) (Job,
|
||||
func (p *Pipeline) ProcessJob(ctx context.Context, jobID uuid.UUID) error {
|
||||
var companyID uuid.UUID
|
||||
var jobUserID *uuid.UUID
|
||||
var status, processingType string
|
||||
var status, processingType, origin string
|
||||
var alreadyProcessed int
|
||||
err := p.Pool.QueryRow(ctx, `
|
||||
SELECT company_id, user_id, status, processing_type, processed_products
|
||||
FROM processing_jobs WHERE id = $1`, jobID).
|
||||
Scan(&companyID, &jobUserID, &status, &processingType, &alreadyProcessed)
|
||||
SELECT company_id, user_id, status, processing_type, processed_products, origin
|
||||
FROM processing_jobs WHERE id = $1`, jobID).
|
||||
Scan(&companyID, &jobUserID, &status, &processingType, &alreadyProcessed, &origin)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -755,7 +765,7 @@ func (p *Pipeline) ProcessJob(ctx context.Context, jobID uuid.UUID) error {
|
||||
return fmt.Errorf("processing: check cancel job=%s: %w", jobID, err)
|
||||
}
|
||||
}
|
||||
ok, tokens, result, itemErr := p.processOne(ctx, companyID, jobID, &items[i], processingType, jobEngine, modeLabel, usingBYOK, &jobCache)
|
||||
ok, tokens, result, itemErr := p.processOne(ctx, companyID, jobID, &items[i], processingType, origin, jobEngine, modeLabel, usingBYOK, &jobCache)
|
||||
if itemErr != nil {
|
||||
failed++
|
||||
if _, err := p.Pool.Exec(ctx, `
|
||||
@@ -1444,7 +1454,7 @@ func (p *Pipeline) reclaimOrphanedProcessingItems(ctx context.Context, jobID uui
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, it *jobItem, processingType string, engine *Engine, modeLabel string, usingBYOK bool, cache *jobScopedCache) (bool, int, StepResult, error) {
|
||||
func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, it *jobItem, processingType, origin string, engine *Engine, modeLabel string, usingBYOK bool, cache *jobScopedCache) (bool, int, StepResult, error) {
|
||||
if it == nil {
|
||||
return false, 0, StepResult{}, fmt.Errorf("processing: nil job item")
|
||||
}
|
||||
@@ -1700,10 +1710,10 @@ func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, i
|
||||
if err := p.Billing.ConsumeCreditsTx(ctx, tx, companyID, result.TotalTokens, "product_processing"); err != nil {
|
||||
return false, 0, result, err
|
||||
}
|
||||
cache.noteCreditDebit(p.Billing.EstimateDebit(ctx, "product_processing", result.TotalTokens))
|
||||
cache.noteCreditDebit(p.Billing.EstimateDebitForCompany(ctx, companyID, "product_processing", result.TotalTokens))
|
||||
}
|
||||
|
||||
processedID, err := p.upsertProcessedProduct(ctx, tx, companyID, it.RawID, gtin, result, attrsJSON, procAttrsJSON, gptJSON, sourcesJSON, providerMode, language)
|
||||
processedID, err := p.upsertProcessedProduct(ctx, tx, companyID, it.RawID, gtin, result, attrsJSON, procAttrsJSON, gptJSON, sourcesJSON, providerMode, language, origin)
|
||||
if err != nil {
|
||||
return false, 0, result, err
|
||||
}
|
||||
@@ -1765,27 +1775,51 @@ const upsertProcessedProductSQL = `
|
||||
company_id, raw_product_id, product_id, name, category, description,
|
||||
processed_name, processed_description, status, attributes, processed_attributes,
|
||||
gpt_response, total_tokens, field_sources, ai_provider_mode, localized_content,
|
||||
meta_title, meta_description
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'needs_review',$9,$10,$11,$12,$13,$14,$15::jsonb,$16,$17)
|
||||
meta_title, meta_description, processing_origin
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,
|
||||
CASE WHEN $18 = 'api' THEN 'completed' ELSE 'needs_review' END,
|
||||
$9,$10,$11,$12,$13,$14,$15::jsonb,$16,$17,$18)
|
||||
ON CONFLICT (company_id, raw_product_id) DO UPDATE SET
|
||||
product_id = EXCLUDED.product_id,
|
||||
name = EXCLUDED.name,
|
||||
category = CASE
|
||||
name = CASE
|
||||
WHEN EXCLUDED.processing_origin = 'api' THEN COALESCE(NULLIF(BTRIM(EXCLUDED.name), ''), processed_products.name)
|
||||
ELSE EXCLUDED.name
|
||||
END,
|
||||
category = CASE
|
||||
WHEN COALESCE(EXCLUDED.field_sources->>'category', '') = 'cleared_invalid' THEN ''
|
||||
ELSE COALESCE(NULLIF(BTRIM(EXCLUDED.category), ''), processed_products.category)
|
||||
END,
|
||||
description = EXCLUDED.description,
|
||||
processed_name = EXCLUDED.processed_name,
|
||||
processed_description = EXCLUDED.processed_description,
|
||||
status = 'needs_review',
|
||||
attributes = EXCLUDED.attributes,
|
||||
processed_attributes = EXCLUDED.processed_attributes,
|
||||
description = CASE
|
||||
WHEN EXCLUDED.processing_origin = 'api' THEN COALESCE(NULLIF(BTRIM(EXCLUDED.description), ''), processed_products.description)
|
||||
ELSE EXCLUDED.description
|
||||
END,
|
||||
processed_name = CASE
|
||||
WHEN EXCLUDED.processing_origin = 'api' THEN COALESCE(NULLIF(BTRIM(EXCLUDED.processed_name), ''), processed_products.processed_name)
|
||||
ELSE EXCLUDED.processed_name
|
||||
END,
|
||||
processed_description = CASE
|
||||
WHEN EXCLUDED.processing_origin = 'api' THEN COALESCE(NULLIF(BTRIM(EXCLUDED.processed_description), ''), processed_products.processed_description)
|
||||
ELSE EXCLUDED.processed_description
|
||||
END,
|
||||
status = EXCLUDED.status,
|
||||
processing_origin = EXCLUDED.processing_origin,
|
||||
attributes = CASE
|
||||
WHEN EXCLUDED.processing_origin = 'api' AND EXCLUDED.attributes = '{}'::jsonb
|
||||
THEN processed_products.attributes ELSE EXCLUDED.attributes END,
|
||||
processed_attributes = CASE
|
||||
WHEN EXCLUDED.processing_origin = 'api' AND EXCLUDED.processed_attributes = '{}'::jsonb
|
||||
THEN processed_products.processed_attributes ELSE EXCLUDED.processed_attributes END,
|
||||
gpt_response = EXCLUDED.gpt_response,
|
||||
total_tokens = COALESCE(processed_products.total_tokens, 0) + EXCLUDED.total_tokens,
|
||||
field_sources = EXCLUDED.field_sources,
|
||||
ai_provider_mode = EXCLUDED.ai_provider_mode,
|
||||
localized_content = EXCLUDED.localized_content,
|
||||
meta_title = CASE
|
||||
localized_content = CASE
|
||||
WHEN EXCLUDED.processing_origin = 'api'
|
||||
THEN COALESCE(processed_products.localized_content, '{}'::jsonb) || EXCLUDED.localized_content
|
||||
ELSE EXCLUDED.localized_content END,
|
||||
meta_title = CASE
|
||||
WHEN EXCLUDED.processing_origin = 'api' AND NULLIF(BTRIM(EXCLUDED.meta_title), '') IS NOT NULL
|
||||
THEN NULLIF(BTRIM(EXCLUDED.meta_title), '')
|
||||
WHEN NULLIF(BTRIM(processed_products.meta_title), '') IS NULL
|
||||
THEN NULLIF(BTRIM(EXCLUDED.meta_title), '')
|
||||
WHEN BTRIM(processed_products.meta_title) ~ '\|\s+[0-9]+$'
|
||||
@@ -1800,8 +1834,10 @@ const upsertProcessedProductSQL = `
|
||||
THEN NULLIF(BTRIM(EXCLUDED.meta_title), '')
|
||||
ELSE processed_products.meta_title
|
||||
END,
|
||||
meta_description = CASE
|
||||
WHEN NULLIF(BTRIM(processed_products.meta_description), '') IS NULL
|
||||
meta_description = CASE
|
||||
WHEN EXCLUDED.processing_origin = 'api' AND NULLIF(BTRIM(EXCLUDED.meta_description), '') IS NOT NULL
|
||||
THEN NULLIF(BTRIM(EXCLUDED.meta_description), '')
|
||||
WHEN NULLIF(BTRIM(processed_products.meta_description), '') IS NULL
|
||||
THEN NULLIF(BTRIM(EXCLUDED.meta_description), '')
|
||||
WHEN LOWER(processed_products.meta_description) LIKE '%prefer 1-3%'
|
||||
OR LOWER(processed_products.meta_description) LIKE '%short retail title%'
|
||||
@@ -1848,6 +1884,7 @@ func (p *Pipeline) upsertProcessedProduct(
|
||||
attrsJSON, procAttrsJSON, gptJSON, sourcesJSON []byte,
|
||||
providerMode string,
|
||||
primaryLang string,
|
||||
origin string,
|
||||
) (uuid.UUID, error) {
|
||||
localized := result.LocalizedContent
|
||||
if localized == nil {
|
||||
@@ -1875,7 +1912,7 @@ func (p *Pipeline) upsertProcessedProduct(
|
||||
err = queryRow(ctx, upsertProcessedProductSQL,
|
||||
companyID, rawID, gtin, result.Name, result.Category, result.Description,
|
||||
result.ProcessedName, result.ProcessedDescription, attrsJSON, procAttrsJSON, gptJSON, result.TotalTokens, sourcesJSON, providerMode, string(locJSON),
|
||||
result.MetaTitle, result.MetaDescription,
|
||||
result.MetaTitle, result.MetaDescription, origin,
|
||||
).Scan(&processedID)
|
||||
return processedID, err
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user