fixes
This commit is contained in:
1 parent
6586722652
commit
1e7c7bbfbb
65 files changed
+1345
-640
No files matched your search
@@ -113,24 +113,24 @@ type CreditPack struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Credits int `json:"credits"`
|
||||
PriceUSD int `json:"price_usd"` // whole dollars for marketing UI
|
||||
PriceEUR int `json:"price_eur"` // whole euros for marketing UI
|
||||
// Approx product×language passes at CreditsPerAIProduct.
|
||||
AIProducts int `json:"ai_products"`
|
||||
}
|
||||
|
||||
func packFromCredits(id, name, desc string, credits, priceUSD int) CreditPack {
|
||||
func packFromCredits(id, name, desc string, credits, priceEUR int) CreditPack {
|
||||
return CreditPack{
|
||||
ID: id,
|
||||
Name: name,
|
||||
Description: desc,
|
||||
Credits: credits,
|
||||
PriceUSD: priceUSD,
|
||||
PriceEUR: priceEUR,
|
||||
AIProducts: credits / CreditsPerAIProduct,
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultCreditPacks is the public top-up ladder (credits-first sizing).
|
||||
// Prices are balanced so small packs are not punitive $/credit vs larger ones,
|
||||
// Prices are balanced so small packs are not punitive €/credit vs larger ones,
|
||||
// while staying expensive enough that packs cannot undercut plan upgrades or A1 (~€300).
|
||||
func DefaultCreditPacks() []CreditPack {
|
||||
return []CreditPack{
|
||||
|
||||
@@ -334,10 +334,10 @@ func (s *Service) consumeCredits(ctx context.Context, tx pgx.Tx, companyID uuid.
|
||||
}
|
||||
_ = s.EnsureDefaultCosts(ctx)
|
||||
|
||||
featureCost := s.lookupCost(ctx, featureName, 1)
|
||||
featureCost := s.lookupCostForCompany(ctx, companyID, featureName, 1)
|
||||
tokenKCost := 1
|
||||
if tokenCount > 0 {
|
||||
tokenKCost = s.lookupCost(ctx, "openai_token_k", 1)
|
||||
tokenKCost = s.lookupCostForCompany(ctx, companyID, "openai_token_k", 1)
|
||||
}
|
||||
var debit int
|
||||
if productCount == 1 {
|
||||
@@ -477,6 +477,43 @@ func (s *Service) lookupCost(ctx context.Context, feature string, fallback int)
|
||||
return cost
|
||||
}
|
||||
|
||||
// lookupCostForCompany resolves credit pricing without caching tenant-specific rules.
|
||||
// Overrides must be positive; the existing credit engine enforces a minimum of 1.
|
||||
// An unconfigured/missing migration retains the global default behavior.
|
||||
func (s *Service) lookupCostForCompany(ctx context.Context, companyID uuid.UUID, feature string, fallback int) int {
|
||||
var cost int
|
||||
err := s.Pool.QueryRow(ctx, `
|
||||
SELECT COALESCE(
|
||||
(SELECT cc.cost_per_unit FROM company_processing_costs cc
|
||||
WHERE cc.company_id = $1 AND cc.feature_name = $2),
|
||||
(SELECT pc.cost_per_unit FROM plan_processing_costs pc
|
||||
JOIN company_plans cp ON cp.plan_id = pc.plan_id
|
||||
WHERE cp.company_id = $1 AND cp.is_active = true AND pc.feature_name = $2
|
||||
ORDER BY cp.created_at DESC LIMIT 1),
|
||||
(SELECT gc.cost_per_unit FROM processing_costs gc
|
||||
WHERE gc.feature_name = $2 AND gc.is_active = true),
|
||||
$3
|
||||
)::integer`, companyID, feature, fallback).Scan(&cost)
|
||||
if err == nil && cost >= 0 {
|
||||
return cost
|
||||
}
|
||||
return s.lookupCost(ctx, feature, fallback)
|
||||
}
|
||||
|
||||
// EstimateDebitForCompany uses the same company/plan pricing rules as the actual debit.
|
||||
func (s *Service) EstimateDebitForCompany(ctx context.Context, companyID uuid.UUID, feature string, tokenCount int) int {
|
||||
if feature == "" {
|
||||
feature = "product_processing"
|
||||
}
|
||||
_ = s.EnsureDefaultCosts(ctx)
|
||||
base := s.lookupCostForCompany(ctx, companyID, feature, 1)
|
||||
perK := 1
|
||||
if tokenCount > 0 {
|
||||
perK = s.lookupCostForCompany(ctx, companyID, "openai_token_k", 1)
|
||||
}
|
||||
return DebitAmount(base, perK, tokenCount)
|
||||
}
|
||||
|
||||
// EnsureDefaultCosts seeds plan-aligned processing cost rows (idempotent).
|
||||
// After a successful seed in this process, subsequent calls no-op (worker seeds at boot).
|
||||
func (s *Service) EnsureDefaultCosts(ctx context.Context) error {
|
||||
@@ -900,6 +937,10 @@ type UsageSummary struct {
|
||||
ProductsProcessed int `json:"products_processed"`
|
||||
ProductsTotal int `json:"products_total"`
|
||||
Tokens int64 `json:"tokens"`
|
||||
InputTokens int64 `json:"input_tokens"`
|
||||
CachedInputTokens int64 `json:"cached_input_tokens"`
|
||||
OutputTokens int64 `json:"output_tokens"`
|
||||
AICalls int64 `json:"ai_calls"`
|
||||
FeedsInput int `json:"feeds_input"`
|
||||
FeedsExport int `json:"feeds_export"`
|
||||
JobsTotal int `json:"jobs_total"`
|
||||
@@ -1010,6 +1051,21 @@ func (s *Service) UsageSummary(ctx context.Context, companyID uuid.UUID, rangeRa
|
||||
out.ProductsProcessed = out.ProductsTotal
|
||||
}
|
||||
|
||||
// Detailed token usage comes from the durable per-call ledger, not processed
|
||||
// product rows (a single product can make several model calls).
|
||||
// A missing old ledger should not prevent viewing the rest of billing.
|
||||
if err := s.Pool.QueryRow(ctx, `
|
||||
SELECT COALESCE(SUM(prompt_tokens),0)::bigint,
|
||||
COALESCE(SUM(cached_prompt_tokens),0)::bigint,
|
||||
COALESCE(SUM(completion_tokens),0)::bigint,
|
||||
COALESCE(SUM(calls),0)::bigint
|
||||
FROM ai_usage_daily
|
||||
WHERE company_id = $1 AND ($2::timestamptz IS NULL OR day >= $2::date)
|
||||
AND ($3::timestamptz IS NULL OR day < $3::date)`,
|
||||
companyID, since, until).Scan(&out.InputTokens, &out.CachedInputTokens, &out.OutputTokens, &out.AICalls); err != nil {
|
||||
out.Notes = append(out.Notes, "Detailed token usage unavailable; check the AI usage ledger migration.")
|
||||
}
|
||||
|
||||
if rangeKey == "7d" || rangeKey == "30d" || (rangeKey == "cycle" && since != nil) {
|
||||
seriesSince := now.Truncate(24*time.Hour).AddDate(0, 0, -29)
|
||||
days := 30
|
||||
|
||||
@@ -328,6 +328,10 @@ func (s *StripeService) CreateCheckoutSession(ctx context.Context, companyID uui
|
||||
return CheckoutResult{}, fmt.Errorf("%w: %s %s", ErrStripePriceMissing, plan, term)
|
||||
}
|
||||
|
||||
if err := s.requireEuroStripePrice(ctx, priceID); err != nil {
|
||||
return CheckoutResult{}, err
|
||||
}
|
||||
|
||||
customerID, err := s.ensureCustomer(ctx, companyID, email, companyName)
|
||||
if err != nil {
|
||||
return CheckoutResult{}, err
|
||||
@@ -406,6 +410,10 @@ func (s *StripeService) CreateCreditPackCheckout(ctx context.Context, companyID
|
||||
return CheckoutResult{}, fmt.Errorf("%w: credit pack %s", ErrStripePriceMissing, pack.ID)
|
||||
}
|
||||
|
||||
if err := s.requireEuroStripePrice(ctx, priceID); err != nil {
|
||||
return CheckoutResult{}, err
|
||||
}
|
||||
|
||||
customerID, err := s.ensureCustomer(ctx, companyID, email, companyName)
|
||||
if err != nil {
|
||||
return CheckoutResult{}, err
|
||||
@@ -1034,6 +1042,22 @@ func verifyStripeSignature(payload []byte, header, secret string, tolerance time
|
||||
return ErrStripeBadSignature
|
||||
}
|
||||
|
||||
// requireEuroStripePrice blocks checkout against old USD Stripe Price IDs.
|
||||
// Publishing euro list prices cannot alter an existing Stripe Price currency.
|
||||
func (s *StripeService) requireEuroStripePrice(ctx context.Context, priceID string) error {
|
||||
var price struct {
|
||||
Currency string `json:"currency"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
if err := s.stripeGET(ctx, "https://api.stripe.com/v1/prices/"+url.PathEscape(priceID), &price); err != nil {
|
||||
return fmt.Errorf("verify Stripe EUR price: %w", err)
|
||||
}
|
||||
if !price.Active || !strings.EqualFold(strings.TrimSpace(price.Currency), "eur") {
|
||||
return errors.New("Stripe Price must be active and denominated in EUR; configure a EUR Price ID before checkout")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadStripePriceIDs reads STRIPE_PRICE_* env into the price map.
|
||||
func LoadStripePriceIDs(getenv func(string) string) map[string]string {
|
||||
out := map[string]string{}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package billing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// StripeInvoice contains only identifiers and URLs supplied by Stripe, never a
|
||||
// locally invented financial document. Amounts are in the invoice currency's
|
||||
// smallest unit, as returned by Stripe.
|
||||
type StripeInvoice struct {
|
||||
ID string `json:"id"`
|
||||
Number string `json:"number"`
|
||||
Status string `json:"status"`
|
||||
Currency string `json:"currency"`
|
||||
Created int64 `json:"created"`
|
||||
AmountDue int64 `json:"amount_due"`
|
||||
AmountPaid int64 `json:"amount_paid"`
|
||||
AmountRemaining int64 `json:"amount_remaining"`
|
||||
HostedInvoiceURL string `json:"hosted_invoice_url,omitempty"`
|
||||
InvoicePDF string `json:"invoice_pdf,omitempty"`
|
||||
}
|
||||
|
||||
func (s *StripeService) ListCompanyInvoices(ctx context.Context, companyID uuid.UUID) ([]StripeInvoice, error) {
|
||||
ctx, cfg, err := s.bindCfg(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.MockMode() {
|
||||
return []StripeInvoice{}, nil
|
||||
}
|
||||
var customerID *string
|
||||
err = s.Pool.QueryRow(ctx, `SELECT stripe_customer_id FROM companies WHERE id=$1`, companyID).Scan(&customerID)
|
||||
if errors.Is(err, pgx.ErrNoRows) || customerID == nil || strings.TrimSpace(*customerID) == "" {
|
||||
return []StripeInvoice{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var result struct {
|
||||
Data []StripeInvoice `json:"data"`
|
||||
}
|
||||
endpoint := "https://api.stripe.com/v1/invoices?limit=100&customer=" + url.QueryEscape(*customerID)
|
||||
if err := s.stripeGET(ctx, endpoint, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if result.Data == nil {
|
||||
result.Data = []StripeInvoice{}
|
||||
}
|
||||
return result.Data, nil
|
||||
}
|
||||
@@ -64,7 +64,10 @@ func (s *StripeService) CreateSalesQuoteCheckout(ctx context.Context, in SalesQu
|
||||
}
|
||||
currency := strings.ToLower(strings.TrimSpace(in.Currency))
|
||||
if currency == "" {
|
||||
currency = "usd"
|
||||
currency = "eur"
|
||||
}
|
||||
if currency != "eur" {
|
||||
return SalesQuoteCheckoutResult{}, fmt.Errorf("%w: only EUR sales quotes are supported", ErrStripePlanUnsupported)
|
||||
}
|
||||
|
||||
ctx, cfg, err := s.bindCfg(ctx)
|
||||
@@ -206,7 +209,7 @@ func (s *StripeService) createSalesQuotePrice(ctx context.Context, productID str
|
||||
form.Set("product", productID)
|
||||
form.Set("currency", strings.ToLower(strings.TrimSpace(in.Currency)))
|
||||
if form.Get("currency") == "" {
|
||||
form.Set("currency", "usd")
|
||||
form.Set("currency", "eur")
|
||||
}
|
||||
form.Set("unit_amount", strconv.Itoa(in.InstallmentAmountCents))
|
||||
form.Set("metadata[descrybe_sales_quote]", in.QuoteID.String())
|
||||
|
||||
@@ -16,7 +16,7 @@ type SyncCreditPackResult struct {
|
||||
PriceID string `json:"price_id"`
|
||||
Created bool `json:"created"`
|
||||
Credits int `json:"credits"`
|
||||
PriceUSD int `json:"price_usd"`
|
||||
PriceEUR int `json:"price_eur"`
|
||||
}
|
||||
|
||||
// SyncCreditPackProducts creates/updates Stripe Products + one-time Prices for
|
||||
@@ -47,7 +47,7 @@ func (s *StripeService) SyncCreditPackProducts(ctx context.Context) ([]SyncCredi
|
||||
PriceID: priceID,
|
||||
Created: createdProduct || createdPrice,
|
||||
Credits: pack.Credits,
|
||||
PriceUSD: pack.PriceUSD,
|
||||
PriceEUR: pack.PriceEUR,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
@@ -73,7 +73,7 @@ func (s *StripeService) ensureCreditPackProduct(ctx context.Context, pack Credit
|
||||
form.Set("metadata[descrybe_pack]", pack.ID)
|
||||
form.Set("metadata[credits]", strconv.Itoa(pack.Credits))
|
||||
form.Set("metadata[ai_products]", strconv.Itoa(pack.AIProducts))
|
||||
form.Set("metadata[price_usd]", strconv.Itoa(pack.PriceUSD))
|
||||
form.Set("metadata[price_eur]", strconv.Itoa(pack.PriceEUR))
|
||||
var product struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
@@ -88,7 +88,7 @@ func (s *StripeService) ensureCreditPackProduct(ctx context.Context, pack Credit
|
||||
|
||||
func (s *StripeService) ensureCreditPackPrice(ctx context.Context, productID string, pack CreditPack) (priceID string, created bool, err error) {
|
||||
// Reuse an active one-time price on this product that matches unit amount.
|
||||
wantCents := pack.PriceUSD * 100
|
||||
wantCents := pack.PriceEUR * 100
|
||||
var list struct {
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
@@ -103,14 +103,14 @@ func (s *StripeService) ensureCreditPackPrice(ctx context.Context, productID str
|
||||
return "", false, err
|
||||
}
|
||||
for _, p := range list.Data {
|
||||
if p.Active && p.Type == "one_time" && strings.EqualFold(p.Currency, "usd") && int(p.UnitAmount) == wantCents {
|
||||
if p.Active && p.Type == "one_time" && strings.EqualFold(p.Currency, "eur") && int(p.UnitAmount) == wantCents {
|
||||
return p.ID, false, nil
|
||||
}
|
||||
}
|
||||
|
||||
form := url.Values{}
|
||||
form.Set("product", productID)
|
||||
form.Set("currency", "usd")
|
||||
form.Set("currency", "eur")
|
||||
form.Set("unit_amount", strconv.Itoa(wantCents))
|
||||
form.Set("metadata[descrybe_pack]", pack.ID)
|
||||
form.Set("metadata[credits]", strconv.Itoa(pack.Credits))
|
||||
|
||||
@@ -205,19 +205,19 @@ func TestCreditPackCatalog(t *testing.T) {
|
||||
t.Fatalf("want at least 7 packs, got %d", len(packs))
|
||||
}
|
||||
tiny, ok := CreditPackByID("tiny")
|
||||
if !ok || tiny.Credits != 25 || tiny.PriceUSD != 29 {
|
||||
if !ok || tiny.Credits != 25 || tiny.PriceEUR != 29 {
|
||||
t.Fatalf("tiny pack: %#v ok=%v", tiny, ok)
|
||||
}
|
||||
small, ok := CreditPackByID("small")
|
||||
if !ok || small.Credits != 65 || small.PriceUSD != 59 {
|
||||
if !ok || small.Credits != 65 || small.PriceEUR != 59 {
|
||||
t.Fatalf("small pack: %#v ok=%v", small, ok)
|
||||
}
|
||||
med, ok := CreditPackByID("medium")
|
||||
if !ok || med.Credits != 200 || med.PriceUSD != 149 {
|
||||
if !ok || med.Credits != 200 || med.PriceEUR != 149 {
|
||||
t.Fatalf("medium pack: %#v ok=%v", med, ok)
|
||||
}
|
||||
mega, ok := CreditPackByID("mega")
|
||||
if !ok || mega.Credits != 8000 || mega.PriceUSD != 2999 {
|
||||
if !ok || mega.Credits != 8000 || mega.PriceEUR != 2999 {
|
||||
t.Fatalf("mega pack: %#v ok=%v", mega, ok)
|
||||
}
|
||||
if CreditPackSettingsKey("small") != "stripe.price.pack.small" {
|
||||
|
||||
Reference in new issue
Block a user