package postgres import ( "context" "encoding/json" "fmt" "git.nianxx.cn/wangxuming/NianAIGC/backend/internal/billing" ) const SeedBillingPriceRulesSQL = `INSERT INTO public.billing_price_rules (id, provider, capability, req_key, variant_key, unit, standard_unit_price_fen, markup_multiplier, enabled, conditions, quantity_source, priority, note, source, parameter_dimensions) SELECT rule->>'id', rule->>'provider', rule->>'capability', NULLIF(rule->>'reqKey', ''), NULLIF(rule->>'variantKey', ''), rule->>'unit', (rule->>'standardUnitPriceFen')::bigint, (rule->>'markupMultiplier')::numeric, COALESCE((rule->>'enabled')::boolean, true), COALESCE(rule->'conditions', '{}'::jsonb), NULLIF(rule->>'quantitySource', ''), COALESCE((rule->>'priority')::integer, 0), NULLIF(rule->>'note', ''), rule->'source', COALESCE(rule->'parameterDimensions', '[]'::jsonb) FROM jsonb_array_elements($1::jsonb) AS rule ON CONFLICT (provider, capability, COALESCE(req_key, ''), COALESCE(variant_key, ''), COALESCE(conditions, '{}'::jsonb)) DO UPDATE SET req_key = EXCLUDED.req_key, variant_key = EXCLUDED.variant_key, unit = EXCLUDED.unit, standard_unit_price_fen = EXCLUDED.standard_unit_price_fen, enabled = EXCLUDED.enabled, conditions = EXCLUDED.conditions, quantity_source = EXCLUDED.quantity_source, priority = EXCLUDED.priority, note = EXCLUDED.note, source = EXCLUDED.source, parameter_dimensions = EXCLUDED.parameter_dimensions, updated_at = now()` func (db *Database) SeedBillingPriceRules(ctx context.Context, rules []billing.PriceRule) error { if len(rules) == 0 { return nil } if db.config.Backend != BackendPostgres || db.querier == nil { return fmt.Errorf("PostgreSQL is unavailable when ZHINIAN_DATA_BACKEND=%s", db.config.Backend) } payload, err := json.Marshal(rules) if err != nil { return fmt.Errorf("encode billing price rule defaults: %w", err) } rows, err := db.querier.Query(ctx, SeedBillingPriceRulesSQL, payload) if err != nil { return fmt.Errorf("seed billing price rule defaults: %w", err) } defer rows.Close() for rows.Next() { } return rows.Err() } var _ billing.PriceRuleSeeder = (*Database)(nil)