fix
This commit is contained in:
1 parent
feebf7d3c1
commit
486502852e
41 files changed
+1311
-259
No files matched your search
@@ -0,0 +1,205 @@
|
||||
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",
|
||||
}
|
||||
|
||||
var defaultContentUnits = map[string]int64{
|
||||
"title": 1000,
|
||||
"description": 2500,
|
||||
"seo_meta": 1000,
|
||||
}
|
||||
|
||||
// ContentDebitUnits calculates exactly one charge per selected output. A missing
|
||||
// selection means the legacy job mode determines which outputs were requested.
|
||||
func ContentDebitUnits(selected []string, processingType string, rates map[string]int64) (int64, error) {
|
||||
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"}
|
||||
}
|
||||
}
|
||||
// Never let an unsupported output bypass validation in flat-rate mode.
|
||||
for _, item := range selected {
|
||||
if _, known := contentFeatures[item]; !known {
|
||||
return 0, fmt.Errorf("unknown content processing type %q", item)
|
||||
}
|
||||
}
|
||||
// A flat product rate is opt-in through the assigned plan. It takes
|
||||
// precedence over per-output rates even when callers request all outputs.
|
||||
if productUnits, ok := rates["product"]; ok {
|
||||
if productUnits < 0 || productUnits > 1000000*contentCreditScale {
|
||||
return 0, errors.New("invalid per-product credit price")
|
||||
}
|
||||
return productUnits, nil
|
||||
}
|
||||
seen := make(map[string]bool, 3)
|
||||
var result int64
|
||||
for _, item := range selected {
|
||||
if _, ok := contentFeatures[item]; !ok {
|
||||
return 0, fmt.Errorf("unknown content processing type %q", item)
|
||||
}
|
||||
if seen[item] {
|
||||
continue
|
||||
}
|
||||
seen[item] = true
|
||||
units, ok := rates[item]
|
||||
if !ok {
|
||||
units = defaultContentUnits[item]
|
||||
}
|
||||
if units < 0 || units > 1000000*contentCreditScale {
|
||||
return 0, errors.New("invalid content credit price")
|
||||
}
|
||||
result += units
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
rates, err := contentRatesFrom(ctx, tx, companyID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
units, err := ContentDebitUnits(selected, processingType, rates)
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package billing
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestContentDebitUnits(t *testing.T) {
|
||||
rates := map[string]int64{"title": 1000, "description": 2500, "seo_meta": 1000}
|
||||
cases := []struct {
|
||||
selected []string
|
||||
processingType string
|
||||
want int64
|
||||
}{
|
||||
{[]string{"title"}, "title", 1000},
|
||||
{[]string{"title", "description"}, "enhance", 3500},
|
||||
{[]string{"title", "description", "seo_meta"}, "enhance", 4500},
|
||||
{[]string{"seo_meta"}, "seo_meta", 1000},
|
||||
{[]string{"title", "title"}, "title", 1000},
|
||||
{nil, "description", 2500},
|
||||
}
|
||||
for _, tt := range cases {
|
||||
got, err := ContentDebitUnits(tt.selected, tt.processingType, rates)
|
||||
if err != nil || got != tt.want {
|
||||
t.Errorf("%v/%s => %d, %v; expected %d", tt.selected, tt.processingType, got, err, tt.want)
|
||||
}
|
||||
}
|
||||
if _, err := ContentDebitUnits([]string{"campaign_copy"}, "full", rates); err == nil {
|
||||
t.Fatal("unknown type accepted")
|
||||
}
|
||||
for _, outputs := range [][]string{nil, {"title"}, {"title", "description", "seo_meta"}} {
|
||||
got, err := ContentDebitUnits(outputs, "enhance", map[string]int64{"title": 1000, "description": 2500, "seo_meta": 1000, "product": 3750})
|
||||
if err != nil || got != 3750 {
|
||||
t.Errorf("per-product price outputs=%v got=%d err=%v", outputs, got, err)
|
||||
}
|
||||
}
|
||||
zero, err := ContentDebitUnits([]string{"title"}, "title", map[string]int64{"title": 0})
|
||||
if err != nil || zero != 0 {
|
||||
t.Fatalf("zero cost %v %v", zero, err)
|
||||
}
|
||||
}
|
||||
@@ -131,7 +131,7 @@ func ComputeEntitlements(planName string, monthlyCredits, remaining int, isTrial
|
||||
func (s *Service) EntitlementsForCompany(ctx context.Context, companyID uuid.UUID) (Entitlements, error) {
|
||||
var total, used int
|
||||
err := s.Pool.QueryRow(ctx, `
|
||||
SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID).
|
||||
SELECT total_credits, (total_credits - CEIL(GREATEST(0,total_credits-used_credits-fractional_credits_used)))::integer FROM credit_balances WHERE company_id = $1`, companyID).
|
||||
Scan(&total, &used)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
total, used = 0, 0
|
||||
|
||||
@@ -36,9 +36,9 @@ const featureGatesCacheTTL = 30 * time.Second
|
||||
|
||||
type CreditsOverview struct {
|
||||
TotalCredits int `json:"total_credits"`
|
||||
UsedCredits int `json:"used_credits"`
|
||||
Remaining int `json:"remaining"`
|
||||
RemainingCredits int `json:"remaining_credits"`
|
||||
UsedCredits float64 `json:"used_credits"`
|
||||
Remaining float64 `json:"remaining"`
|
||||
RemainingCredits float64 `json:"remaining_credits"`
|
||||
LowCredits bool `json:"low_credits"`
|
||||
LowCreditsThreshold int `json:"low_credits_threshold"`
|
||||
ProductCount int `json:"product_count"`
|
||||
@@ -69,9 +69,10 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
|
||||
lowThreshold = 100
|
||||
}
|
||||
var total, used int
|
||||
var fractional float64
|
||||
err := s.Pool.QueryRow(ctx, `
|
||||
SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID).
|
||||
Scan(&total, &used)
|
||||
SELECT total_credits, used_credits, fractional_credits_used::double precision FROM credit_balances WHERE company_id = $1`, companyID).
|
||||
Scan(&total, &used, &fractional)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
_, _ = s.Pool.Exec(ctx, `INSERT INTO credit_balances (company_id) VALUES ($1) ON CONFLICT DO NOTHING`, companyID)
|
||||
total, used = 0, 0
|
||||
@@ -79,10 +80,13 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
|
||||
return CreditsOverview{}, err
|
||||
}
|
||||
|
||||
remaining := RemainingCreditsClamped(total, used)
|
||||
remaining := float64(total-used) - fractional
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
out := CreditsOverview{
|
||||
TotalCredits: total,
|
||||
UsedCredits: used,
|
||||
UsedCredits: float64(used) + fractional,
|
||||
Remaining: remaining,
|
||||
RemainingCredits: remaining,
|
||||
LowCreditsThreshold: lowThreshold,
|
||||
@@ -157,7 +161,7 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
|
||||
planName = "Free"
|
||||
featuresRaw = []byte("{}")
|
||||
}
|
||||
ent := ComputeEntitlements(planName, monthlyVal, remaining, isTrial)
|
||||
ent := ComputeEntitlements(planName, monthlyVal, int(remaining+0.9999), isTrial)
|
||||
out.CanUseAI = ent.CanUseAI
|
||||
out.CanUseEPREL = ent.CanUseEPREL
|
||||
out.IsFreePlan = ent.IsFreePlan
|
||||
@@ -214,6 +218,9 @@ func (s *Service) AIBrandApplyAllowed(ctx context.Context, companyID uuid.UUID)
|
||||
type ProcessingGateOpts struct {
|
||||
// RequiresAI when true enforces can_use_ai + credit wallet (AI-only job types).
|
||||
RequiresAI bool
|
||||
// CreditsPerProduct is the effective per-output rate for this job.
|
||||
// Zero retains legacy one-credit minimum for callers without content pricing.
|
||||
CreditsPerProduct float64
|
||||
// RequiresEPREL when true enforces can_use_eprel (EPREL-only job types).
|
||||
RequiresEPREL bool
|
||||
}
|
||||
@@ -239,9 +246,15 @@ func (s *Service) AssertCanStartProcessing(ctx context.Context, companyID uuid.U
|
||||
if ent.RemainingCredits < 1 {
|
||||
return fmt.Errorf("%w: no credits remaining — upgrade your plan to continue AI processing", ErrInsufficientCredits)
|
||||
}
|
||||
if ent.RemainingCredits < batchSize {
|
||||
return fmt.Errorf("%w: need at least %d credits for this batch (have %d) — upgrade or select fewer products",
|
||||
ErrInsufficientCredits, batchSize, ent.RemainingCredits)
|
||||
needed := float64(batchSize)
|
||||
if opts.CreditsPerProduct > 0 {
|
||||
needed *= opts.CreditsPerProduct
|
||||
}
|
||||
// The wallet debit uses precise fractional values and remains authoritative.
|
||||
// The coarse entitlement is rounded up, so avoid rejecting a valid sub-credit job.
|
||||
if float64(ent.RemainingCredits)+0.000001 < needed {
|
||||
return fmt.Errorf("%w: need about %.2f credits for this batch (up to %d whole-credit units available)",
|
||||
ErrInsufficientCredits, needed, ent.RemainingCredits)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,7 +398,7 @@ func (s *Service) applyCreditDebit(ctx context.Context, tx pgx.Tx, companyID uui
|
||||
WITH upd AS (
|
||||
UPDATE credit_balances
|
||||
SET used_credits = used_credits + $2, updated_at = now()
|
||||
WHERE company_id = $1 AND (total_credits - used_credits) >= $2
|
||||
WHERE company_id = $1 AND (total_credits - used_credits - fractional_credits_used) >= $2
|
||||
RETURNING company_id
|
||||
),
|
||||
cyc AS (
|
||||
@@ -462,7 +475,7 @@ func (s *Service) lookupCost(ctx context.Context, feature string, fallback int)
|
||||
|
||||
var cost int
|
||||
err := s.Pool.QueryRow(ctx, `
|
||||
SELECT cost_per_unit FROM processing_costs
|
||||
SELECT cost_per_unit::integer FROM processing_costs
|
||||
WHERE feature_name = $1 AND is_active = true`, feature).Scan(&cost)
|
||||
if err != nil || cost <= 0 {
|
||||
return fallback
|
||||
@@ -884,7 +897,7 @@ func (s *Service) AssignPlan(ctx context.Context, companyID uuid.UUID, planID in
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at)
|
||||
VALUES ($1, $2, 0, now())
|
||||
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, updated_at = now()`,
|
||||
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, fractional_credits_used = 0, updated_at = now()`,
|
||||
companyID, alloc)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -931,9 +944,9 @@ type UsageDayPoint struct {
|
||||
type UsageSummary struct {
|
||||
CompanyID uuid.UUID `json:"company_id"`
|
||||
Range string `json:"range"`
|
||||
CreditsUsed int `json:"credits_used"`
|
||||
CreditsUsed float64 `json:"credits_used"`
|
||||
CreditsTotal int `json:"credits_total"`
|
||||
CreditsRemaining int `json:"credits_remaining"`
|
||||
CreditsRemaining float64 `json:"credits_remaining"`
|
||||
ProductsProcessed int `json:"products_processed"`
|
||||
ProductsTotal int `json:"products_total"`
|
||||
Tokens int64 `json:"tokens"`
|
||||
@@ -969,17 +982,21 @@ func (s *Service) UsageSummary(ctx context.Context, companyID uuid.UUID, rangeRa
|
||||
}
|
||||
|
||||
var total, used int
|
||||
var fractional float64
|
||||
err := s.Pool.QueryRow(ctx, `
|
||||
SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID).
|
||||
Scan(&total, &used)
|
||||
SELECT total_credits, used_credits, fractional_credits_used::double precision FROM credit_balances WHERE company_id = $1`, companyID).
|
||||
Scan(&total, &used, &fractional)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
total, used = 0, 0
|
||||
} else if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.CreditsTotal = total
|
||||
out.CreditsUsed = used
|
||||
out.CreditsRemaining = RemainingCreditsClamped(total, used)
|
||||
out.CreditsUsed = float64(used) + fractional
|
||||
out.CreditsRemaining = float64(total-used) - fractional
|
||||
if out.CreditsRemaining < 0 {
|
||||
out.CreditsRemaining = 0
|
||||
}
|
||||
out.Notes = append(out.Notes,
|
||||
"Credits are the live wallet (credit_balances). Daily credit history is not ledgered yet — range filters apply to products and tokens only.")
|
||||
|
||||
@@ -1250,7 +1267,7 @@ func (s *Service) claimAndRollDueCompanyPlan(ctx context.Context, rowID int64) (
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at)
|
||||
VALUES ($1, $2, 0, now())
|
||||
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, updated_at = now()`,
|
||||
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, fractional_credits_used = 0, updated_at = now()`,
|
||||
companyID, monthly)
|
||||
if err != nil {
|
||||
return false, err
|
||||
|
||||
Reference in new issue
Block a user