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
|
||||
}
|
||||
Reference in new issue
Block a user