From 1e7c7bbfbb66fb211e02b7622b09f87e4f925745 Mon Sep 17 00:00:00 2001 From: GreenEclipse Date: Fri, 16 Oct 2026 00:34:06 +0200 Subject: [PATCH] fixes --- apps/api/cmd/sync-stripe-packs/main.go | 2 +- apps/api/internal/aiaudit/cost.go | 4 + apps/api/internal/billing/credit_packs.go | 8 +- apps/api/internal/billing/service.go | 60 ++- apps/api/internal/billing/stripe.go | 24 + apps/api/internal/billing/stripe_invoices.go | 56 ++ .../internal/billing/stripe_sales_quote.go | 7 +- .../api/internal/billing/stripe_sync_packs.go | 12 +- apps/api/internal/billing/stripe_test.go | 8 +- apps/api/internal/catalog/service.go | 12 +- .../httpapi/admin_ai_cost_export_handlers.go | 51 ++ .../httpapi/admin_ai_costs_handlers.go | 6 +- .../httpapi/admin_analytics_handlers.go | 23 +- .../httpapi/admin_invoice_export_handlers.go | 37 ++ .../admin_processing_costs_handlers.go | 103 ++++ .../httpapi/admin_stripe_sync_handlers.go | 12 +- apps/api/internal/httpapi/billing_handlers.go | 16 + .../httpapi/billing_usage_export_handlers.go | 45 ++ apps/api/internal/httpapi/feeds_handlers.go | 9 +- .../httpapi/member_feature_middleware.go | 1 + .../internal/httpapi/processing_handlers.go | 11 +- apps/api/internal/httpapi/server.go | 6 + apps/api/internal/httpapi/v1_openapi.go | 484 +++--------------- apps/api/internal/httpapi/v1_openapi_test.go | 21 + .../internal/httpapi/v1_process_handlers.go | 2 +- ...api_catalog_visibility_integration_test.go | 152 ++++++ apps/api/internal/processing/pipeline.go | 89 +++- .../schema/049_processing_cost_overrides.sql | 23 + .../sql/schema/050_ai_model_prices_mini.sql | 14 + .../051_api_processed_catalog_visibility.sql | 14 + apps/web/src/lib/analytics.test.ts | 6 +- apps/web/src/lib/analytics/ecommerce.ts | 16 +- .../components/pricing/PlanCalculator.svelte | 16 +- .../lib/components/pricing/PlanCard.svelte | 4 +- .../lib/components/pricing/credit-packs.ts | 16 +- .../lib/components/pricing/plan-calculator.ts | 20 +- .../lib/components/pricing/pricing-data.ts | 2 +- .../components/products/ProductTable.svelte | 5 +- apps/web/src/lib/components/products/types.ts | 1 + .../src/lib/components/site/PlanCard.svelte | 4 +- apps/web/src/lib/i18n/messages/de.ts | 6 +- apps/web/src/lib/i18n/messages/en.ts | 14 +- apps/web/src/lib/i18n/messages/es.ts | 6 +- apps/web/src/lib/i18n/messages/fr.ts | 6 +- apps/web/src/lib/i18n/messages/it.ts | 6 +- apps/web/src/lib/i18n/messages/ja.ts | 6 +- apps/web/src/lib/i18n/messages/nl.ts | 6 +- apps/web/src/lib/i18n/messages/pl.ts | 6 +- apps/web/src/lib/i18n/messages/pt.ts | 6 +- apps/web/src/lib/pricing-eur.test.ts | 18 + apps/web/src/lib/seo.ts | 2 +- apps/web/src/lib/stripe-billing.ts | 4 +- .../src/routes/admin/analytics/+page.svelte | 132 ++++- .../src/routes/admin/sales/[id]/+page.svelte | 4 +- .../src/routes/admin/settings/+page.svelte | 2 +- apps/web/src/routes/billing/+page.svelte | 68 ++- apps/web/src/routes/plans/+page.svelte | 4 +- apps/web/src/routes/products/+page.svelte | 10 +- docs/GO_IMPORT_CYCLE_FIX_V13.md | 37 ++ docs/PRICING_EUR_JAGER_V14.md | 23 + docs/SVELTE_BUILD_FIX.md | 20 + docs/V15_USAGE_BILLING.md | 32 ++ docs/V16_API_PRODUCTS_DASHBOARD.md | 26 + .../sestanek-dobavitelji-onboarding-sl.md | 137 ++--- docs/public-api-reference.md | 2 +- 65 files changed, 1345 insertions(+), 640 deletions(-) create mode 100644 apps/api/internal/billing/stripe_invoices.go create mode 100644 apps/api/internal/httpapi/admin_ai_cost_export_handlers.go create mode 100644 apps/api/internal/httpapi/admin_invoice_export_handlers.go create mode 100644 apps/api/internal/httpapi/admin_processing_costs_handlers.go create mode 100644 apps/api/internal/httpapi/billing_usage_export_handlers.go create mode 100644 apps/api/internal/processing/api_catalog_visibility_integration_test.go create mode 100644 apps/api/sql/schema/049_processing_cost_overrides.sql create mode 100644 apps/api/sql/schema/050_ai_model_prices_mini.sql create mode 100644 apps/api/sql/schema/051_api_processed_catalog_visibility.sql create mode 100644 apps/web/src/lib/pricing-eur.test.ts create mode 100644 docs/GO_IMPORT_CYCLE_FIX_V13.md create mode 100644 docs/PRICING_EUR_JAGER_V14.md create mode 100644 docs/SVELTE_BUILD_FIX.md create mode 100644 docs/V15_USAGE_BILLING.md create mode 100644 docs/V16_API_PRODUCTS_DASHBOARD.md diff --git a/apps/api/cmd/sync-stripe-packs/main.go b/apps/api/cmd/sync-stripe-packs/main.go index fc5c1f7..4560c14 100644 --- a/apps/api/cmd/sync-stripe-packs/main.go +++ b/apps/api/cmd/sync-stripe-packs/main.go @@ -67,7 +67,7 @@ func main() { flag = "created/updated" } fmt.Printf(" %-8s $%-5d credits=%-6d price=%s product=%s (%s)\n", - r.PackID, r.PriceUSD, r.Credits, r.PriceID, r.ProductID, flag) + r.PackID, r.PriceEUR, r.Credits, r.PriceID, r.ProductID, flag) if *writeSettings { if plat == nil { fmt.Fprintln(os.Stderr, "-write-settings requires DATABASE_URL") diff --git a/apps/api/internal/aiaudit/cost.go b/apps/api/internal/aiaudit/cost.go index dba5353..464b4ee 100644 --- a/apps/api/internal/aiaudit/cost.go +++ b/apps/api/internal/aiaudit/cost.go @@ -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}, diff --git a/apps/api/internal/billing/credit_packs.go b/apps/api/internal/billing/credit_packs.go index 2debb61..4fb94fd 100644 --- a/apps/api/internal/billing/credit_packs.go +++ b/apps/api/internal/billing/credit_packs.go @@ -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{ diff --git a/apps/api/internal/billing/service.go b/apps/api/internal/billing/service.go index 8cffee0..29aaf81 100644 --- a/apps/api/internal/billing/service.go +++ b/apps/api/internal/billing/service.go @@ -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 diff --git a/apps/api/internal/billing/stripe.go b/apps/api/internal/billing/stripe.go index d7dbdba..9224f45 100644 --- a/apps/api/internal/billing/stripe.go +++ b/apps/api/internal/billing/stripe.go @@ -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{} diff --git a/apps/api/internal/billing/stripe_invoices.go b/apps/api/internal/billing/stripe_invoices.go new file mode 100644 index 0000000..b5d664e --- /dev/null +++ b/apps/api/internal/billing/stripe_invoices.go @@ -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 +} diff --git a/apps/api/internal/billing/stripe_sales_quote.go b/apps/api/internal/billing/stripe_sales_quote.go index a930d6a..710d16c 100644 --- a/apps/api/internal/billing/stripe_sales_quote.go +++ b/apps/api/internal/billing/stripe_sales_quote.go @@ -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()) diff --git a/apps/api/internal/billing/stripe_sync_packs.go b/apps/api/internal/billing/stripe_sync_packs.go index a433a35..de7dc6e 100644 --- a/apps/api/internal/billing/stripe_sync_packs.go +++ b/apps/api/internal/billing/stripe_sync_packs.go @@ -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)) diff --git a/apps/api/internal/billing/stripe_test.go b/apps/api/internal/billing/stripe_test.go index f065a7b..4f163da 100644 --- a/apps/api/internal/billing/stripe_test.go +++ b/apps/api/internal/billing/stripe_test.go @@ -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" { diff --git a/apps/api/internal/catalog/service.go b/apps/api/internal/catalog/service.go index d5ae561..58ae09e 100644 --- a/apps/api/internal/catalog/service.go +++ b/apps/api/internal/catalog/service.go @@ -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", diff --git a/apps/api/internal/httpapi/admin_ai_cost_export_handlers.go b/apps/api/internal/httpapi/admin_ai_cost_export_handlers.go new file mode 100644 index 0000000..ec8fa0a --- /dev/null +++ b/apps/api/internal/httpapi/admin_ai_cost_export_handlers.go @@ -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() +} diff --git a/apps/api/internal/httpapi/admin_ai_costs_handlers.go b/apps/api/internal/httpapi/admin_ai_costs_handlers.go index 194195c..9337518 100644 --- a/apps/api/internal/httpapi/admin_ai_costs_handlers.go +++ b/apps/api/internal/httpapi/admin_ai_costs_handlers.go @@ -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) diff --git a/apps/api/internal/httpapi/admin_analytics_handlers.go b/apps/api/internal/httpapi/admin_analytics_handlers.go index 5f831b2..6560bbc 100644 --- a/apps/api/internal/httpapi/admin_analytics_handlers.go +++ b/apps/api/internal/httpapi/admin_analytics_handlers.go @@ -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: | 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 diff --git a/apps/api/internal/httpapi/admin_invoice_export_handlers.go b/apps/api/internal/httpapi/admin_invoice_export_handlers.go new file mode 100644 index 0000000..0ad8eea --- /dev/null +++ b/apps/api/internal/httpapi/admin_invoice_export_handlers.go @@ -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() +} diff --git a/apps/api/internal/httpapi/admin_processing_costs_handlers.go b/apps/api/internal/httpapi/admin_processing_costs_handlers.go new file mode 100644 index 0000000..857bb12 --- /dev/null +++ b/apps/api/internal/httpapi/admin_processing_costs_handlers.go @@ -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"}) +} diff --git a/apps/api/internal/httpapi/admin_stripe_sync_handlers.go b/apps/api/internal/httpapi/admin_stripe_sync_handlers.go index d6aa32a..8305edd 100644 --- a/apps/api/internal/httpapi/admin_stripe_sync_handlers.go +++ b/apps/api/internal/httpapi/admin_stripe_sync_handlers.go @@ -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, }) } diff --git a/apps/api/internal/httpapi/billing_handlers.go b/apps/api/internal/httpapi/billing_handlers.go index e647dfe..d8a68ac 100644 --- a/apps/api/internal/httpapi/billing_handlers.go +++ b/apps/api/internal/httpapi/billing_handlers.go @@ -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"}) +} diff --git a/apps/api/internal/httpapi/billing_usage_export_handlers.go b/apps/api/internal/httpapi/billing_usage_export_handlers.go new file mode 100644 index 0000000..24ce035 --- /dev/null +++ b/apps/api/internal/httpapi/billing_usage_export_handlers.go @@ -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() +} diff --git a/apps/api/internal/httpapi/feeds_handlers.go b/apps/api/internal/httpapi/feeds_handlers.go index 9531223..d79566b 100644 --- a/apps/api/internal/httpapi/feeds_handlers.go +++ b/apps/api/internal/httpapi/feeds_handlers.go @@ -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 diff --git a/apps/api/internal/httpapi/member_feature_middleware.go b/apps/api/internal/httpapi/member_feature_middleware.go index 5a14212..1410cb3 100644 --- a/apps/api/internal/httpapi/member_feature_middleware.go +++ b/apps/api/internal/httpapi/member_feature_middleware.go @@ -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", diff --git a/apps/api/internal/httpapi/processing_handlers.go b/apps/api/internal/httpapi/processing_handlers.go index 858968a..348769d 100644 --- a/apps/api/internal/httpapi/processing_handlers.go +++ b/apps/api/internal/httpapi/processing_handlers.go @@ -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 diff --git a/apps/api/internal/httpapi/server.go b/apps/api/internal/httpapi/server.go index fa13700..dfc1dfd 100644 --- a/apps/api/internal/httpapi/server.go +++ b/apps/api/internal/httpapi/server.go @@ -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) diff --git a/apps/api/internal/httpapi/v1_openapi.go b/apps/api/internal/httpapi/v1_openapi.go index 860c79e..1800b6a 100644 --- a/apps/api/internal/httpapi/v1_openapi.go +++ b/apps/api/internal/httpapi/v1_openapi.go @@ -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 diff --git a/apps/api/internal/httpapi/v1_openapi_test.go b/apps/api/internal/httpapi/v1_openapi_test.go index 6c10e25..7bccbfd 100644 --- a/apps/api/internal/httpapi/v1_openapi_test.go +++ b/apps/api/internal/httpapi/v1_openapi_test.go @@ -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() diff --git a/apps/api/internal/httpapi/v1_process_handlers.go b/apps/api/internal/httpapi/v1_process_handlers.go index 8ea029e..bc4ba13 100644 --- a/apps/api/internal/httpapi/v1_process_handlers.go +++ b/apps/api/internal/httpapi/v1_process_handlers.go @@ -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 { diff --git a/apps/api/internal/processing/api_catalog_visibility_integration_test.go b/apps/api/internal/processing/api_catalog_visibility_integration_test.go new file mode 100644 index 0000000..97c6b21 --- /dev/null +++ b/apps/api/internal/processing/api_catalog_visibility_integration_test.go @@ -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) + } +} diff --git a/apps/api/internal/processing/pipeline.go b/apps/api/internal/processing/pipeline.go index 539ed54..c72c535 100644 --- a/apps/api/internal/processing/pipeline.go +++ b/apps/api/internal/processing/pipeline.go @@ -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 } diff --git a/apps/api/sql/schema/049_processing_cost_overrides.sql b/apps/api/sql/schema/049_processing_cost_overrides.sql new file mode 100644 index 0000000..162814f --- /dev/null +++ b/apps/api/sql/schema/049_processing_cost_overrides.sql @@ -0,0 +1,23 @@ +-- +goose Up +-- Effective credit rules: company > assigned plan > global defaults. +-- These affect future debits only. Existing credit history is never repriced. +CREATE TABLE IF NOT EXISTS plan_processing_costs ( + plan_id BIGINT NOT NULL REFERENCES plans(id) ON DELETE CASCADE, + feature_name TEXT NOT NULL, + cost_per_unit INTEGER NOT NULL CHECK (cost_per_unit >= 1 AND cost_per_unit <= 1000000), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (plan_id, feature_name) +); +CREATE TABLE IF NOT EXISTS company_processing_costs ( + company_id UUID NOT NULL REFERENCES companies(id) ON DELETE CASCADE, + feature_name TEXT NOT NULL, + cost_per_unit INTEGER NOT NULL CHECK (cost_per_unit >= 1 AND cost_per_unit <= 1000000), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (company_id, feature_name) +); +CREATE INDEX IF NOT EXISTS plan_processing_costs_feature_idx ON plan_processing_costs(feature_name); +CREATE INDEX IF NOT EXISTS company_processing_costs_feature_idx ON company_processing_costs(feature_name); + +-- +goose Down +DROP TABLE IF EXISTS company_processing_costs; +DROP TABLE IF EXISTS plan_processing_costs; diff --git a/apps/api/sql/schema/050_ai_model_prices_mini.sql b/apps/api/sql/schema/050_ai_model_prices_mini.sql new file mode 100644 index 0000000..c755453 --- /dev/null +++ b/apps/api/sql/schema/050_ai_model_prices_mini.sql @@ -0,0 +1,14 @@ +-- +goose Up +-- USD per 1M standard text tokens, OpenAI published rates, 2026-10-16. +-- The platform's cost ledger records USD at call time; never reprice history. +-- Existing/admin-custom pricing remains authoritative. +INSERT INTO ai_model_prices (model,input_micros_per_mtok,cached_input_micros_per_mtok,output_micros_per_mtok,source) +VALUES +('gpt-5.4-mini',750000,75000,4500000,'https://developers.openai.com/api/docs/models/gpt-5.4-mini'), +('gpt-5-mini',250000,25000,2000000,'https://developers.openai.com/api/docs/models/gpt-5-mini'), +('gpt-6-luna',100000,10000,500000,'https://developers.openai.com/api/docs/pricing') +ON CONFLICT(model) DO NOTHING; + +-- +goose Down +-- Price rows may be in active use and cost history cannot be re-priced. +SELECT 1; diff --git a/apps/api/sql/schema/051_api_processed_catalog_visibility.sql b/apps/api/sql/schema/051_api_processed_catalog_visibility.sql new file mode 100644 index 0000000..88b70f8 --- /dev/null +++ b/apps/api/sql/schema/051_api_processed_catalog_visibility.sql @@ -0,0 +1,14 @@ +-- +goose Up +-- Make API-origin processing visible in the existing catalog, without changing the +-- review/approval lifecycle of dashboard and feed-initiated jobs. +ALTER TABLE processing_jobs + ADD COLUMN IF NOT EXISTS origin TEXT NOT NULL DEFAULT 'dashboard'; +ALTER TABLE processed_products + ADD COLUMN IF NOT EXISTS processing_origin TEXT NOT NULL DEFAULT 'dashboard'; + +-- Old jobs have no trustworthy origin tag; leave their review state intact. +-- The unique (company_id,raw_product_id) index remains the product identity. + +-- +goose Down +ALTER TABLE processed_products DROP COLUMN IF EXISTS processing_origin; +ALTER TABLE processing_jobs DROP COLUMN IF EXISTS origin; diff --git a/apps/web/src/lib/analytics.test.ts b/apps/web/src/lib/analytics.test.ts index 1e16d45..46d9509 100644 --- a/apps/web/src/lib/analytics.test.ts +++ b/apps/web/src/lib/analytics.test.ts @@ -99,7 +99,7 @@ describe("buildSubscriptionEcommerce", () => { const { ecommerce, extra } = buildSubscriptionEcommerce("starter", "monthly"); assert.equal(extra.plan, "starter"); assert.equal(extra.billing_term, "monthly"); - assert.equal(ecommerce.currency, "USD"); + assert.equal(ecommerce.currency, "EUR"); assert.equal(ecommerce.value, 49); assert.deepEqual(ecommerce.items[0], { item_id: "starter", @@ -124,7 +124,7 @@ describe("buildCreditPackEcommerce", () => { it("includes value/currency/items from CREDIT_PACKS list prices", () => { const { ecommerce, extra } = buildCreditPackEcommerce("tiny"); assert.equal(extra.pack_id, "tiny"); - assert.equal(ecommerce.currency, "USD"); + assert.equal(ecommerce.currency, "EUR"); assert.equal(ecommerce.value, 29); assert.deepEqual(ecommerce.items[0], { item_id: "tiny", @@ -143,7 +143,7 @@ describe("toEcommerceObject + purchase resolve", () => { }); assert.deepEqual(toEcommerceObject(ecommerce), { items: ecommerce.items, - currency: "USD", + currency: "EUR", value: 49, transaction_id: "cs_test_abc" }); diff --git a/apps/web/src/lib/analytics/ecommerce.ts b/apps/web/src/lib/analytics/ecommerce.ts index f34f753..979768d 100644 --- a/apps/web/src/lib/analytics/ecommerce.ts +++ b/apps/web/src/lib/analytics/ecommerce.ts @@ -46,7 +46,7 @@ export function normalizeBillingTerm(raw: string | null | undefined): BillingTer return t === "yearly" || t === "annual" || t === "year" ? "yearly" : "monthly"; } -/** Marketing list price for a subscription term (USD). */ +/** Marketing list price for a subscription term (EUR). */ export function subscriptionListValue( monthlyPrice: number, term: BillingTerm @@ -81,7 +81,7 @@ export function buildSubscriptionEcommerce( }; const ecommerce: Ga4EcommerceFields = { items: [item], - ...(price !== undefined ? { currency: "USD", value: price } : {}), + ...(price !== undefined ? { currency: "EUR", value: price } : {}), ...(opts?.transactionId ? { transaction_id: opts.transactionId } : {}) }; return { @@ -92,15 +92,15 @@ export function buildSubscriptionEcommerce( export function buildCreditPackEcommerce( packId: string, - opts?: { transactionId?: string; priceUsd?: number; itemName?: string } + opts?: { transactionId?: string; priceEur?: number; itemName?: string } ): { ecommerce: Ga4EcommerceFields; extra: Record } { const key = packId.trim().toLowerCase(); const marketing = CREDIT_PACKS.find((p) => p.id === key); const price = - typeof opts?.priceUsd === "number" && opts.priceUsd > 0 - ? opts.priceUsd - : typeof marketing?.priceUSD === "number" && marketing.priceUSD > 0 - ? marketing.priceUSD + typeof opts?.priceEur === "number" && opts.priceEur > 0 + ? opts.priceEur + : typeof marketing?.priceEUR === "number" && marketing.priceEUR > 0 + ? marketing.priceEUR : undefined; const itemName = (opts?.itemName ?? marketing?.name ?? key).trim() || key; const item: Ga4EcommerceItem = { @@ -112,7 +112,7 @@ export function buildCreditPackEcommerce( }; const ecommerce: Ga4EcommerceFields = { items: [item], - ...(price !== undefined ? { currency: "USD", value: price } : {}), + ...(price !== undefined ? { currency: "EUR", value: price } : {}), ...(opts?.transactionId ? { transaction_id: opts.transactionId } : {}) }; return { diff --git a/apps/web/src/lib/components/pricing/PlanCalculator.svelte b/apps/web/src/lib/components/pricing/PlanCalculator.svelte index e955cf3..7fef070 100644 --- a/apps/web/src/lib/components/pricing/PlanCalculator.svelte +++ b/apps/web/src/lib/components/pricing/PlanCalculator.svelte @@ -29,7 +29,7 @@ ); function formatMoney(n: number): string { - return `$${n.toLocaleString()}`; + return `€${n.toLocaleString()}`; } @@ -127,9 +127,9 @@ {#if rec.plan.customPrice} {i18n.t("pricing.card.custom")} {:else if rec.plan.pricePerMonth === 0} - $0 / {i18n.t("pricing.card.perMonth")} + €0 / {i18n.t("pricing.card.perMonth")} {:else} - {formatMoney(rec.monthlyListUSD)} / {i18n.t("pricing.card.perMonth")} + {formatMoney(rec.monthlyListEUR)} / {i18n.t("pricing.card.perMonth")} {/if}

    @@ -145,7 +145,7 @@ {i18n.t("pricing.calc.aiNeedsPacks", { pack: rec.packs.pack.name, count: rec.packs.count, - usd: formatMoney(rec.packs.totalUSD) + usd: formatMoney(rec.packs.totalEUR) })} {/if} @@ -165,11 +165,11 @@

    {budget.plan.name}

    - {formatMoney(budget.monthlyListUSD)} / {i18n.t("pricing.card.perMonth")} - {#if budget.yearlyMonthlyUSD > 0 && budget.yearlyMonthlyUSD < budget.monthlyListUSD} + {formatMoney(budget.monthlyListEUR)} / {i18n.t("pricing.card.perMonth")} + {#if budget.yearlyMonthlyEUR > 0 && budget.yearlyMonthlyEUR < budget.monthlyListEUR} ({i18n.t("pricing.calc.orYearly", { - amount: formatMoney(budget.yearlyMonthlyUSD) + amount: formatMoney(budget.yearlyMonthlyEUR) })}) {/if} @@ -182,7 +182,7 @@ {i18n.t("pricing.calc.aiNeedsPacks", { pack: budget.packs.pack.name, count: budget.packs.count, - usd: formatMoney(budget.packs.totalUSD) + usd: formatMoney(budget.packs.totalEUR) })} {/if} diff --git a/apps/web/src/lib/components/pricing/PlanCard.svelte b/apps/web/src/lib/components/pricing/PlanCard.svelte index 8f7cafb..239c9ee 100644 --- a/apps/web/src/lib/components/pricing/PlanCard.svelte +++ b/apps/web/src/lib/components/pricing/PlanCard.svelte @@ -133,10 +133,10 @@ {#if plan.customPrice} {i18n.t("pricing.card.custom")} {:else if isFree} - $0 + €0 {i18n.t("pricing.card.forever")} {:else} - ${displayPrice} + €{displayPrice} /{displayPeriod} {/if} diff --git a/apps/web/src/lib/components/pricing/credit-packs.ts b/apps/web/src/lib/components/pricing/credit-packs.ts index 7b085d9..2f70cf9 100644 --- a/apps/web/src/lib/components/pricing/credit-packs.ts +++ b/apps/web/src/lib/components/pricing/credit-packs.ts @@ -10,7 +10,7 @@ export type MarketingCreditPack = { description: string; descriptionKey: string; credits: number; - priceUSD: number; + priceEUR: number; aiProducts: number; }; @@ -22,7 +22,7 @@ export const CREDIT_PACKS: MarketingCreditPack[] = [ description: "Smoke tests / tiny fixes (25 credits ≈ 12 AI products)", descriptionKey: "pricing.pack.tiny.desc", credits: 25, - priceUSD: 29, + priceEUR: 29, aiProducts: 12 }, { @@ -32,7 +32,7 @@ export const CREDIT_PACKS: MarketingCreditPack[] = [ description: "Small top-up (65 credits ≈ 32 AI products)", descriptionKey: "pricing.pack.small.desc", credits: 65, - priceUSD: 59, + priceEUR: 59, aiProducts: 32 }, { @@ -42,7 +42,7 @@ export const CREDIT_PACKS: MarketingCreditPack[] = [ description: "Burst top-up (200 credits ≈ 100 AI products)", descriptionKey: "pricing.pack.medium.desc", credits: 200, - priceUSD: 149, + priceEUR: 149, aiProducts: 100 }, { @@ -52,7 +52,7 @@ export const CREDIT_PACKS: MarketingCreditPack[] = [ description: "Mid buffer (500 credits ≈ 250 AI products)", descriptionKey: "pricing.pack.large.desc", credits: 500, - priceUSD: 299, + priceEUR: 299, aiProducts: 250 }, { @@ -62,7 +62,7 @@ export const CREDIT_PACKS: MarketingCreditPack[] = [ description: "Catalog / re-run buffer (1,200 credits ≈ 600 AI products)", descriptionKey: "pricing.pack.xl.desc", credits: 1200, - priceUSD: 599, + priceEUR: 599, aiProducts: 600 }, { @@ -72,7 +72,7 @@ export const CREDIT_PACKS: MarketingCreditPack[] = [ description: "Large multi-language buffer (3,000 credits ≈ 1,500 AI products)", descriptionKey: "pricing.pack.xxl.desc", credits: 3000, - priceUSD: 1299, + priceEUR: 1299, aiProducts: 1500 }, { @@ -82,7 +82,7 @@ export const CREDIT_PACKS: MarketingCreditPack[] = [ description: "Distributor / agency burst (8,000 credits ≈ 4,000 AI products)", descriptionKey: "pricing.pack.mega.desc", credits: 8000, - priceUSD: 2999, + priceEUR: 2999, aiProducts: 4000 } ]; diff --git a/apps/web/src/lib/components/pricing/plan-calculator.ts b/apps/web/src/lib/components/pricing/plan-calculator.ts index 30a25b3..68f7824 100644 --- a/apps/web/src/lib/components/pricing/plan-calculator.ts +++ b/apps/web/src/lib/components/pricing/plan-calculator.ts @@ -19,7 +19,7 @@ export type PackEstimate = { pack: MarketingCreditPack; count: number; totalCredits: number; - totalUSD: number; + totalEUR: number; }; export type PlanRecommendation = { @@ -29,8 +29,8 @@ export type PlanRecommendation = { creditsNeeded: number; creditsShortfall: number; packs: PackEstimate | null; - monthlyListUSD: number; - yearlyMonthlyUSD: number; + monthlyListEUR: number; + yearlyMonthlyEUR: number; }; export type PlanCalculatorResult = { @@ -61,13 +61,13 @@ export function estimatePacksForShortfall(shortfall: number): PackEstimate | nul const count = Math.ceil(shortfall / pack.credits); if (count <= 0) continue; const totalCredits = count * pack.credits; - const totalUSD = count * pack.priceUSD; + const totalEUR = count * pack.priceEUR; if ( !best || - totalUSD < best.totalUSD || - (totalUSD === best.totalUSD && count < best.count) + totalEUR < best.totalEUR || + (totalEUR === best.totalEUR && count < best.count) ) { - best = { pack, count, totalCredits, totalUSD }; + best = { pack, count, totalCredits, totalEUR }; } } return best; @@ -86,8 +86,8 @@ function recommendationFor( creditsNeeded, creditsShortfall: shortfall, packs, - monthlyListUSD: plan.pricePerMonth, - yearlyMonthlyUSD: plan.pricePerMonth > 0 ? Math.round(yearly / 12) : 0 + monthlyListEUR: plan.pricePerMonth, + yearlyMonthlyEUR: plan.pricePerMonth > 0 ? Math.round(yearly / 12) : 0 }; } @@ -134,7 +134,7 @@ export function recommendPlans( // Only offer budget when packs can close AI gap without exceeding ~2 months of // the price delta vs upgrading (keeps Starter+packs from undercutting A1 badly). const lowerRec = recommendationFor(lower, creditsNeeded); - const packCost = lowerRec.packs?.totalUSD ?? 0; + const packCost = lowerRec.packs?.totalEUR ?? 0; const upgradeDelta = fullPlan.pricePerMonth - lower.pricePerMonth; const packOk = packCost === 0 || packCost <= Math.max(upgradeDelta * 2, 149); if (packOk || lowerRec.aiComfortable) { diff --git a/apps/web/src/lib/components/pricing/pricing-data.ts b/apps/web/src/lib/components/pricing/pricing-data.ts index c79d76f..3c2ffd5 100644 --- a/apps/web/src/lib/components/pricing/pricing-data.ts +++ b/apps/web/src/lib/components/pricing/pricing-data.ts @@ -108,7 +108,7 @@ export interface PricingFaqItem { * Never include client deals (A1, Merkur trial, …) — those stay admin-only. * * Limits are product/SKU- and credit-based (no storage meters on public plans). - * List prices are marketing placeholders; self-serve Checkout uses Stripe Price IDs from env/admin. + * List prices are in EUR; Stripe Checkout requires matching EUR Price IDs from settings/env. */ export const PRICING_PLANS: PricingPlan[] = [ { diff --git a/apps/web/src/lib/components/products/ProductTable.svelte b/apps/web/src/lib/components/products/ProductTable.svelte index 38acbe5..8fde1b8 100644 --- a/apps/web/src/lib/components/products/ProductTable.svelte +++ b/apps/web/src/lib/components/products/ProductTable.svelte @@ -689,7 +689,10 @@ import { Check, Edit, MoreHorizontal, X } from "@lucide/svelte"; {/if}