Files
descrybe/apps/api/internal/billing/content_credits.go
T

171 lines
6.5 KiB
Go
Raw Normal View History

2026-10-16 13:48:51 +02:00
package billing
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// Content credit rates use fixed four-decimal units (1 credit = 10,000 units).
// They are independent of provider token billing and cannot be rounded to an int.
const contentCreditScale int64 = 10000
var contentFeatures = map[string]string{
"title": "title_ai",
"description": "description_ai",
"seo_meta": "seo_meta_ai",
}
2026-10-20 17:50:32 +02:00
// ContentDebitUnits bills one credit for one processed product in one language,
// regardless of which supported outputs were selected. The EUR value of a
// credit is a separate reference value and is never a processing multiplier.
// rates is retained for existing callers, but output-level admin prices no
// longer affect the product enrichment charge.
2026-10-16 13:48:51 +02:00
func ContentDebitUnits(selected []string, processingType string, rates map[string]int64) (int64, error) {
2026-10-20 17:50:32 +02:00
_ = rates
2026-10-16 13:48:51 +02:00
if len(selected) == 0 {
switch processingType {
case "seo", "seo_meta", "seo_ai":
selected = []string{"seo_meta"}
case "title":
selected = []string{"title"}
case "description":
selected = []string{"description"}
default:
selected = []string{"title", "description"}
}
}
2026-10-20 17:50:32 +02:00
for _, output := range selected {
if _, ok := contentFeatures[output]; !ok {
return 0, fmt.Errorf("unknown content processing type %q", output)
2026-10-16 13:48:51 +02:00
}
}
2026-10-20 17:50:32 +02:00
return contentCreditScale, nil
2026-10-16 13:48:51 +02:00
}
// ContentRates resolves company overrides > active plan overrides > global default.
// Postgres computes fixed-point integers, avoiding floating-point money arithmetic.
type contentRateQuerier interface {
Query(context.Context, string, ...any) (pgx.Rows, error)
}
func (s *Service) ContentRates(ctx context.Context, companyID uuid.UUID) (map[string]int64, error) {
return contentRatesFrom(ctx, s.Pool, companyID)
}
func contentRatesFrom(ctx context.Context, source contentRateQuerier, companyID uuid.UUID) (map[string]int64, error) {
rows, err := source.Query(ctx, `
SELECT f.output, COALESCE(
(SELECT (cost_per_unit * 10000)::bigint FROM company_processing_costs
WHERE company_id=$1 AND feature_name=f.feature),
(SELECT (pc.cost_per_unit * 10000)::bigint 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=f.feature
ORDER BY cp.created_at DESC LIMIT 1),
(SELECT (cost_per_unit * 10000)::bigint FROM processing_costs
WHERE feature_name=f.feature AND is_active=true),
f.fallback)
FROM (VALUES
('title'::text,'title_ai'::text,1000::bigint),
('description'::text,'description_ai'::text,2500::bigint),
('seo_meta'::text,'seo_meta_ai'::text,1000::bigint)
) AS f(output,feature,fallback)
UNION ALL
SELECT 'product'::text, COALESCE(
(SELECT (cc.cost_per_unit * 10000)::bigint FROM company_processing_costs cc
WHERE cc.company_id=$1 AND cc.feature_name='product_ai'),
(SELECT (pc.cost_per_unit * 10000)::bigint FROM plan_processing_costs pc
WHERE pc.plan_id=(SELECT cp.plan_id FROM company_plans cp
WHERE cp.company_id=$1 AND cp.is_active=true
ORDER BY cp.created_at DESC LIMIT 1)
AND pc.feature_name='product_ai'))
WHERE EXISTS (
SELECT 1 FROM plan_processing_costs pc
WHERE pc.plan_id=(SELECT cp.plan_id FROM company_plans cp
WHERE cp.company_id=$1 AND cp.is_active=true
ORDER BY cp.created_at DESC LIMIT 1)
AND pc.feature_name='product_ai'
)`, companyID)
if err != nil {
return nil, err
}
defer rows.Close()
rates := make(map[string]int64, 3)
for rows.Next() {
var output string
var units int64
if err := rows.Scan(&output, &units); err != nil {
return nil, err
}
rates[output] = units
}
if err := rows.Err(); err != nil {
return nil, err
}
for name := range contentFeatures {
if _, ok := rates[name]; !ok {
return nil, errors.New("incomplete content pricing rules")
}
}
return rates, nil
}
// ConsumeContentCreditsTx atomically debits the fractional wallet and the current
// billing cycle in the caller's product transaction. It never overdraws credits.
func (s *Service) ConsumeContentCreditsTx(ctx context.Context, tx pgx.Tx, companyID uuid.UUID, selected []string, processingType string) (float64, error) {
if tx == nil {
return 0, errors.New("missing billing transaction")
}
2026-10-20 17:50:32 +02:00
units, err := ContentDebitUnits(selected, processingType, nil)
2026-10-16 13:48:51 +02:00
if err != nil {
return 0, err
}
if units == 0 {
return 0, nil
}
// Lock credit_balances once. Both integer legacy debits and fractional debits
// account for this column when checking remaining capacity.
_, err = tx.Exec(ctx, `INSERT INTO credit_balances (company_id) VALUES ($1) ON CONFLICT DO NOTHING`, companyID)
if err != nil {
return 0, err
}
var allowed bool
err = tx.QueryRow(ctx, `
UPDATE credit_balances SET fractional_credits_used=fractional_credits_used+($2::numeric/10000), updated_at=now()
WHERE company_id=$1 AND (total_credits-used_credits-fractional_credits_used)>=($2::numeric/10000)
RETURNING true`, companyID, units).Scan(&allowed)
if errors.Is(err, pgx.ErrNoRows) {
return 0, ErrInsufficientCredits
}
if err != nil {
return 0, err
}
tag, err := tx.Exec(ctx, `
UPDATE billing_cycles SET fractional_credits_used=fractional_credits_used+($2::numeric/10000),
products_processed=products_processed+1, updated_at=now()
WHERE id=(SELECT id FROM billing_cycles WHERE company_id=$1 AND end_date>now() ORDER BY start_date DESC LIMIT 1)`, companyID, units)
if err != nil {
return 0, err
}
if tag.RowsAffected() == 0 {
var start, end time.Time
err = tx.QueryRow(ctx, `SELECT billing_cycle_start,next_billing_date FROM company_plans
WHERE company_id=$1 AND is_active=true ORDER BY created_at DESC LIMIT 1`, companyID).Scan(&start, &end)
if errors.Is(err, pgx.ErrNoRows) {
start = time.Now().UTC()
end = start.AddDate(0, 1, 0)
} else if err != nil {
return 0, err
}
_, err = tx.Exec(ctx, `INSERT INTO billing_cycles (company_id,start_date,end_date,credits_used,fractional_credits_used,products_processed)
VALUES ($1,$2,$3,0,$4::numeric/10000,1)`, companyID, start, end, units)
if err != nil {
return 0, err
}
}
return float64(units) / float64(contentCreditScale), nil
}