feat: implement automatic margin pricing and margin reverse engineering in sync
This commit is contained in:
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from decimal import Decimal
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
@@ -14,7 +14,7 @@ from app.models.upstream import Upstream
|
||||
from app.models.upstream_key import UpstreamGeneratedKey
|
||||
from app.models.website import Website, WebsiteGroupBinding, WebsiteSyncLog
|
||||
from app.services.auth_config import normalize_auth_config
|
||||
from app.services.website_client import Sub2ApiWebsiteClient, WebsiteError, _extract_id, calculate_target_rate
|
||||
from app.services.website_client import Sub2ApiWebsiteClient, WebsiteError, _extract_id, calculate_target_rate, parse_positive_decimal
|
||||
from app.services.upstream_client import UpstreamClient
|
||||
from app.services import webhook_service
|
||||
from app.utils.number import fixed_decimal_string
|
||||
@@ -168,6 +168,21 @@ def sync_binding(db: Session, binding: WebsiteGroupBinding, write: bool = True)
|
||||
})
|
||||
try:
|
||||
target_rate = calculate_target_rate([item.get("rate") for item in source_rates], binding.percent, binding.algorithm)
|
||||
if binding.algorithm == "priority_weighted_plus_percent":
|
||||
rates = [rate for rate in (parse_positive_decimal(item.get("rate")) for item in source_rates) if rate is not None]
|
||||
if rates:
|
||||
rates_sorted = sorted(rates)
|
||||
N = len(rates_sorted)
|
||||
if N == 1:
|
||||
base = rates_sorted[0]
|
||||
else:
|
||||
w1 = Decimal("0.85")
|
||||
w_others = Decimal("0.15") / Decimal(N - 1)
|
||||
base = rates_sorted[0] * w1 + sum(rates_sorted[1:], Decimal("0")) * w_others
|
||||
|
||||
if base > 0:
|
||||
effective_percent = (target_rate / base - Decimal("1")) * Decimal("100")
|
||||
binding.percent = fixed_decimal_string(effective_percent.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP), 2)
|
||||
except Exception as exc:
|
||||
return _log(db, binding, website, source_rates, "failed", str(exc))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user