Переглянути джерело

feat: add payment processing fee calculation and migration support

jerry 1 місяць тому
батько
коміт
4f9da9341c

+ 15 - 1
app/api/endpoints/common.py

@@ -6,7 +6,7 @@ from app.core.database import get_db
 from app.utils.response import success
 from app.schemas.common import ApiResponse
 from app.schemas.http_session import HttpSessionCreate, HttpSessionOut
-from app.schemas.llm import ParseUserInputsOut, ParseUserInputsPayload
+from app.schemas.llm import ParseUserInputsOut, ParseUserInputsPayload, ParseTutorialOut, ParseTutorialPayload
 from app.schemas.resource import FileUploadOut
 from app.schemas.short_url import ShortUrlCreate, ShortUrlOut
 from app.services.http_session_service import HttpSessionService
@@ -202,3 +202,17 @@ async def vas_llm_data_parsing(
 ):
     out = await LlmService.handle_parse(db, payload)
     return success(data=out)
+
+
+@admin_required_router.post("/vas/llm/parse_tutorial", summary="AI解析用户教程与操作指引配置", tags=["textskin"], response_model=ApiResponse[ParseTutorialOut])
+async def vas_llm_parse_tutorial(
+    payload: ParseTutorialPayload,
+):
+    if not payload.prompt or not payload.prompt.strip():
+        raise BizLogicError("Please provide a valid natural language tutorial description")
+    parsed_config = await LlmService.parse_tutorial_async(
+        prompt=payload.prompt,
+        model=payload.model,
+        system_prompt=payload.system_prompt,
+    )
+    return success(data=ParseTutorialOut(tutorial_config=parsed_config))

+ 5 - 0
app/models/payment.py

@@ -20,6 +20,8 @@ class VasPayment(Base):
       `amount` INT NOT NULL,
       `currency` VARCHAR(10) NOT NULL,
       `random_offset` INT NOT NULL,
+      `fee_rate` DECIMAL(6,4) NOT NULL DEFAULT 0.0000,
+      `fee_amount` INT NOT NULL DEFAULT 0,
       `exchange_rate` DECIMAL(18,8) NOT NULL,
       `qr_id` INT NULL,
       `payment_url` TEXT NULL,
@@ -69,6 +71,9 @@ class VasPayment(Base):
     currency = Column(String(10), nullable=False)
     random_offset = Column(Integer, nullable=False)
     
+    fee_rate = Column(DECIMAL(6, 4), nullable=False, default=0.0)
+    fee_amount = Column(Integer, nullable=False, default=0)
+
     exchange_rate = Column(DECIMAL(18, 8), nullable=False)
 
     qr_id = Column(Integer)

+ 10 - 0
app/schemas/llm.py

@@ -11,3 +11,13 @@ class ParseUserInputsPayload(BaseModel):
 class ParseUserInputsOut(BaseModel):
     parsed_obj: Optional[Dict[str, Any]]
 
+
+class ParseTutorialPayload(BaseModel):
+    prompt: str
+    system_prompt: Optional[str] = None
+    model: Optional[str] = None
+
+
+class ParseTutorialOut(BaseModel):
+    tutorial_config: Dict[str, Any]
+

+ 3 - 0
app/schemas/payment.py

@@ -52,6 +52,9 @@ class VasPaymentOut(VasPaymentBase):
     currency: str
     random_offset: int
     
+    fee_rate: float = 0.0
+    fee_amount: int = 0
+
     exchange_rate: float  # 注意:仅用于展示,DB 里是 DECIMAL
 
     external_refund_no: Optional[str]

+ 2 - 0
app/schemas/settlement.py

@@ -38,6 +38,8 @@ class SettlementOrderDetailOut(BaseModel):
     developer_name: Optional[str] = None
     order_amount: int
     currency: str = "CNY" # 订单流水实际币种 (CNY, EUR, USD等)
+    gross_amount: Optional[int] = None # 用户实付流水总额(分)
+    fee_amount: int = 0                # 扣除的通道手续费(分)
     original_amount: Optional[int] = None
     original_currency: Optional[str] = None
     avg_cost: int

+ 182 - 0
app/services/llm_service.py

@@ -174,6 +174,188 @@ Extract data from the text strictly based on the provided JSON Schema.
 
         raise BizLogicError("LLM request failed")
 
+    @classmethod
+    async def parse_tutorial_async(
+        cls,
+        prompt: str,
+        system_prompt: Optional[str] = None,
+        model: Optional[str] = None,
+        max_retries: int = 1,
+    ) -> Dict[str, Any]:
+        """
+        利用大模型 (如 DeepSeek) 根据用户的自然语言需求,自动生成商品用户使用教程与操作指引结构化配置
+        支持前端传入自定义/微调后的 system_prompt
+        """
+        api_key = cls.get_api_key()
+        if not api_key:
+            logger.warning("[LlmService] No LLM API Key configured.")
+            raise BizLogicError("LLM API Key not configured")
+
+        url = cls.get_completions_url()
+        selected_model = (model or "").strip() or cls.get_default_model()
+        temperature = 0.3
+        timeout_seconds = settings.llm_timeout_seconds or 45
+
+        headers = {
+            "Authorization": f"Bearer {api_key}",
+            "Content-Type": "application/json",
+        }
+
+        default_instruction = (
+            "You are an expert e-commerce operations specialist for international visa, embassy, and appointment booking services.\n"
+            "Your primary mission is to generate a MANDATORY PRE-ORDER PREREQUISITE CHECKLIST (下单前置必备条件与门槛说明) for customers before they can purchase this service.\n\n"
+            "CORE EMPHASIS:\n"
+            "The single most important purpose of this guide is establishing the HARD PRE-CONDITIONS required BEFORE placing an order. Customers must satisfy these prerequisites first; otherwise, their automated booking order cannot proceed and will fail.\n\n"
+            "CORE WRITING STYLE:\n"
+            "1. PREREQUISITE-FIRST & ULTRA-CONCISE: Focus exclusively on what the buyer MUST have ready before paying. Avoid generic website tutorials or fluffy disclaimers. Every word must count.\n"
+            "2. ALL ENGLISH: Regardless of input language, generate crisp, authoritative, professional English.\n\n"
+            "JSON SCHEMA:\n"
+            "{\n"
+            '  "display_type": "both", // Allowed: "both", "modal", "link", "embedded"\n'
+            '  "button_text": "⚠️ Mandatory Pre-Order Checklist", // Short warning/checklist label (3-5 words with emoji)\n'
+            '  "modal_title": "Mandatory Prerequisites Before Placing Order", // Clear pre-order gate title (5-8 words)\n'
+            '  "link_url": "https://...", // Official portal URL if mentioned, else ""\n'
+            '  "link_text": "Official Portal ↗", // Short label (2-3 words)\n'
+            '  "badge_text": "Mandatory Prerequisite", // Badge indicating required pre-order gate (1-3 words)\n'
+            '  "summary": "...", // STRICTLY 1-2 punchy sentences warning the buyer what MUST be ready before ordering (under 30 words).\n'
+            '  "steps": [\n'
+            '    {\n'
+            '      "step_no": 1,\n'
+            '      "title": "Action Title", // 2-4 words (e.g. "Activated Portal Account", "Valid Passport Scan", "Cancel Prior Bookings")\n'
+            '      "desc": "One crisp sentence explaining the exact prerequisite required before order (strictly under 20 words)."\n'
+            '    }\n'
+            '  ],\n'
+            '  "content": "..." // Max 2 critical FAQs addressing pre-order blockers (e.g. can I order first without account? overlapping bookings?). Format: **Q: ...?**\\nA: One crisp sentence.\n'
+            "}\n\n"
+            "CRITICAL RULES:\n"
+            "1. FOCUS ON PRE-CONDITIONS: Every single step MUST be a prerequisite task completed BEFORE ordering.\n"
+            "2. MAX 3 STEPS: Each step's description MUST be strictly 1 single, compact sentence (< 20 words).\n"
+            "3. SUMMARY: Strictly 1 to 2 sentences max (< 35 words total).\n"
+            "4. FAQ: Strictly 2 questions maximum, with direct 1-sentence answers.\n"
+            "5. Output STRICT JSON only without Markdown wrappers or greetings."
+        )
+
+        effective_system_prompt = system_prompt.strip() if (system_prompt and system_prompt.strip()) else default_instruction
+
+        payload = {
+            "model": selected_model,
+            "messages": [
+                {"role": "system", "content": effective_system_prompt},
+                {"role": "user", "content": prompt}
+            ],
+            "temperature": temperature,
+            "response_format": {"type": "json_object"}
+        }
+
+        timeout = aiohttp.ClientTimeout(total=float(timeout_seconds))
+
+        for attempt in range(max_retries + 1):
+            try:
+                async with aiohttp.ClientSession(timeout=timeout) as session:
+                    async with session.post(url, headers=headers, json=payload) as response:
+                        if response.status != 200:
+                            error_text = await response.text()
+                            logger.error(f"[LlmService] HTTP {response.status} from {url}: {error_text}")
+                            if attempt == max_retries:
+                                raise BizLogicError(f"LLM request failed: HTTP {response.status}")
+                            await asyncio.sleep(0.5)
+                            continue
+
+                        result = await response.json()
+                        choices = result.get("choices", [])
+                        if not choices:
+                            raise BizLogicError("LLM response did not contain completion choices")
+
+                        content_str = choices[0].get("message", {}).get("content", "")
+                        parsed = cls.clean_json_response(content_str)
+                        if not isinstance(parsed, dict):
+                            raise BizLogicError("LLM returned non-dict JSON")
+
+                        # 若模型在顶层嵌套了 tutorial_config / tutorial / config / data,先解包
+                        if "tutorial_config" in parsed and isinstance(parsed["tutorial_config"], dict):
+                            parsed = parsed["tutorial_config"]
+                        elif "tutorial" in parsed and isinstance(parsed["tutorial"], dict):
+                            parsed = parsed["tutorial"]
+                        elif "config" in parsed and isinstance(parsed["config"], dict):
+                            parsed = parsed["config"]
+                        elif "data" in parsed and isinstance(parsed["data"], dict):
+                            parsed = parsed["data"]
+
+                        # 全量健壮字段对齐与多格式兼容,确保精准填充至表单各位置
+                        btn_txt = parsed.get("button_text") or parsed.get("button_label") or parsed.get("btn_text") or "📖 Guide: Prepare Your Account"
+                        m_title = parsed.get("modal_title") or parsed.get("title") or parsed.get("name") or "Official Portal Registration & Booking Guide"
+                        l_url = parsed.get("link_url") or parsed.get("url") or parsed.get("link") or ""
+                        l_txt = parsed.get("link_text") or parsed.get("url_text") or "Open Official Portal ↗"
+                        summ = parsed.get("summary") or parsed.get("overview") or parsed.get("description") or ""
+                        raw_faq = parsed.get("content") or parsed.get("faq") or parsed.get("faq_content") or parsed.get("details") or ""
+                        if isinstance(raw_faq, list):
+                            faq_lines = []
+                            for i, item in enumerate(raw_faq):
+                                if isinstance(item, dict):
+                                    q = item.get("q") or item.get("question") or item.get("title") or f"Question {i+1}"
+                                    a = item.get("a") or item.get("answer") or item.get("desc") or item.get("content") or ""
+                                    faq_lines.append(f"**Q{i+1}. {q}**\n{a}")
+                                elif isinstance(item, str):
+                                    faq_lines.append(item)
+                            faq_content = "\n\n".join(faq_lines)
+                        else:
+                            faq_content = str(raw_faq)
+
+                        badge_txt = parsed.get("badge_text") or "Prerequisite Guide"
+
+                        d_type = str(parsed.get("display_type", "both")).lower()
+                        if "modal" in d_type:
+                            d_type = "modal"
+                        elif "link" in d_type:
+                            d_type = "link"
+                        elif "embed" in d_type:
+                            d_type = "embedded"
+                        else:
+                            d_type = "both"
+
+                        steps_raw = parsed.get("steps", [])
+                        if not isinstance(steps_raw, list):
+                            if isinstance(steps_raw, str):
+                                steps_raw = [s.strip() for s in steps_raw.split("\n") if s.strip()]
+                            else:
+                                steps_raw = []
+                        normalized_steps = []
+                        for idx, step in enumerate(steps_raw):
+                            if isinstance(step, dict):
+                                normalized_steps.append({
+                                    "step_no": step.get("step_no", idx + 1),
+                                    "title": step.get("title") or step.get("step_title") or step.get("name") or f"Step {idx + 1}",
+                                    "desc": step.get("desc") or step.get("description") or step.get("content") or step.get("detail") or "",
+                                })
+                            elif isinstance(step, str) and step.strip():
+                                normalized_steps.append({
+                                    "step_no": idx + 1,
+                                    "title": f"Step {idx + 1}",
+                                    "desc": step.strip(),
+                                })
+
+                        return {
+                            "enabled": True,
+                            "display_type": d_type,
+                            "button_text": btn_txt,
+                            "modal_title": m_title,
+                            "link_url": l_url,
+                            "link_text": l_txt,
+                            "badge_text": badge_txt,
+                            "summary": summ,
+                            "steps": normalized_steps,
+                            "content": faq_content,
+                        }
+            except BizLogicError:
+                raise
+            except Exception as e:
+                logger.error(f"[LlmService] parse_tutorial_async attempt {attempt} failed: {e}")
+                if attempt == max_retries:
+                    raise BizLogicError(f"AI tutorial parsing failed: {str(e)}")
+                await asyncio.sleep(0.5)
+
+        raise BizLogicError("AI tutorial parsing failed")
+
     @classmethod
     async def chat_completion_with_tools_async(
         cls,

+ 75 - 15
app/services/payment_service.py

@@ -99,6 +99,27 @@ class PaymentService:
         else:
             raise BizLogicError("Invalid type for 'EXCHANGE_RATES' configuration")
 
+    @staticmethod
+    def _calculate_processing_fee(amount_converted: Decimal, provider_config: Optional[Any]) -> tuple[Decimal, int]:
+        """
+        根据服务商配置计算通道手续费 (简单直加模式)
+        fee_amount = round(amount_converted * fee_rate) + fee_fixed
+        """
+        if not provider_config:
+            return Decimal("0.0"), 0
+        if isinstance(provider_config, str):
+            try:
+                provider_config = json.loads(provider_config)
+            except Exception:
+                return Decimal("0.0"), 0
+        if not isinstance(provider_config, dict):
+            return Decimal("0.0"), 0
+
+        fee_rate = Decimal(str(provider_config.get("fee_rate", 0) or 0))
+        fee_fixed = int(provider_config.get("fee_fixed", 0) or 0)
+        fee_amount = int((amount_converted * fee_rate).quantize(Decimal("1"), rounding=ROUND_HALF_UP)) + fee_fixed
+        return fee_rate, max(0, fee_amount)
+
     @staticmethod
     async def create_payment(
         db: AsyncSession,
@@ -469,8 +490,13 @@ class PaymentService:
         else:
             discount = 0
 
+        # --- 手续费计算 (简单直加) ---
+        fee_rate, fee_amount = PaymentService._calculate_processing_fee(amount_converted, provider.config)
+
+        payment.fee_rate = fee_rate
+        payment.fee_amount = fee_amount
         payment.exchange_rate = current_exchange_rate
-        payment.amount = int(amount_converted) - discount
+        payment.amount = max(0, int(amount_converted) + fee_amount - discount)
         payment.currency = provider.currency
         payment.random_offset = discount
 
@@ -509,8 +535,13 @@ class PaymentService:
              
         current_exchange_rate = rate_from / rate_to
 
+        # --- 手续费计算 (简单直加) ---
+        fee_rate, fee_amount = PaymentService._calculate_processing_fee(amount_converted, provider.config)
+
+        payment.fee_rate = fee_rate
+        payment.fee_amount = fee_amount
         payment.exchange_rate = current_exchange_rate
-        payment.amount = int(amount_converted)
+        payment.amount = max(0, int(amount_converted) + fee_amount)
         payment.currency = provider.currency
         payment.random_offset = 0 # Stripe 不需要随机减免
 
@@ -559,8 +590,13 @@ class PaymentService:
             raise BizLogicError("Invalid target currency rate (0)")
         current_exchange_rate = rate_from / rate_to
 
+        # --- 手续费计算 (简单直加) ---
+        fee_rate, fee_amount = PaymentService._calculate_processing_fee(amount_converted, provider.config)
+
+        payment.fee_rate = fee_rate
+        payment.fee_amount = fee_amount
         payment.exchange_rate = current_exchange_rate
-        payment.amount = int(amount_converted)
+        payment.amount = max(0, int(amount_converted) + fee_amount)
         payment.currency = target_currency
         payment.random_offset = 0
 
@@ -614,21 +650,37 @@ class PaymentService:
     ):
         expires_at = int(time.time()) + 30 * 60
 
+        base_product_amount = payment.amount - (payment.fee_amount or 0)
+        line_items = [
+            {
+                "price_data": {
+                    "currency": payment.currency.lower(),
+                    "product_data": {
+                        "name": f"Visa Service Order {order.id}",
+                    },
+                    "unit_amount": base_product_amount,
+                },
+                "quantity": 1,
+            }
+        ]
+
+        if payment.fee_amount and payment.fee_amount > 0:
+            fee_label = f"Processing Fee ({float(payment.fee_rate) * 100:.1f}%)" if payment.fee_rate else "Processing Fee"
+            line_items.append({
+                "price_data": {
+                    "currency": payment.currency.lower(),
+                    "product_data": {
+                        "name": fee_label,
+                    },
+                    "unit_amount": payment.fee_amount,
+                },
+                "quantity": 1,
+            })
+
         return stripe.checkout.Session.create(
             mode="payment",
             payment_method_types=["card"],
-            line_items=[
-                {
-                    "price_data": {
-                        "currency": payment.currency.lower(),
-                        "product_data": {
-                            "name": f"Visa Service Order {order.id}",
-                        },
-                        "unit_amount": payment.amount,
-                    },
-                    "quantity": 1,
-                }
-            ],
+            line_items=line_items,
             metadata={
                 "order_id": order.id,
                 "payment_id": payment.id,
@@ -658,6 +710,8 @@ class PaymentService:
             amount=0,
             currency="CNY",
             random_offset=0,
+            fee_rate=Decimal("0.0"),
+            fee_amount=0,
             exchange_rate=0,
             status="pending",
             expire_at=datetime.utcnow() + timedelta(minutes=30),
@@ -685,6 +739,8 @@ class PaymentService:
             amount=0,
             currency="CNY",
             random_offset=0,
+            fee_rate=Decimal("0.0"),
+            fee_amount=0,
             exchange_rate=0,
             status="pending",
             expire_at=datetime.utcnow() + timedelta(minutes=30),
@@ -712,6 +768,8 @@ class PaymentService:
             amount=0,
             currency="EUR",
             random_offset=0,
+            fee_rate=Decimal("0.0"),
+            fee_amount=0,
             exchange_rate=0,
             status="pending",
             expire_at=datetime.utcnow() + timedelta(minutes=30),
@@ -736,6 +794,8 @@ class PaymentService:
             amount=0,
             currency="USD",
             random_offset=0,
+            fee_rate=Decimal("0.0"),
+            fee_amount=0,
             exchange_rate=0,
             status="pending",
             expire_at=datetime.utcnow() + timedelta(minutes=30),

+ 21 - 10
app/services/settlement_service.py

@@ -75,25 +75,32 @@ class SettlementService:
             for p in p_res.scalars().all():
                 payments_by_order.setdefault(p.order_id, []).append(p)
 
-        def resolve_order_payment(o: VasOrder) -> tuple[int, str]:
+        def resolve_order_payment(o: VasOrder) -> tuple[int, str, int, int]:
             """
             按实际支付流水统计订单实收与币种
-            返回: (amount, currency)
+            核心规则:显式扣除通道结算手续费(fee_amount),确保分润基数仅为纯服务净额,避免平台倒贴网关手续费
+            返回: (net_amt, currency, gross_amt, fee_amt)
             """
             pays = payments_by_order.get(o.id, [])
             if pays:
                 pay_cur = pays[0].currency or o.base_currency or "CNY"
-                total_amt = sum(p.amount for p in pays if p.currency == pay_cur)
-                if total_amt == 0:
-                    total_amt = pays[0].amount
-                return total_amt, pay_cur
+                total_gross = sum(p.amount for p in pays if p.currency == pay_cur)
+                if total_gross == 0:
+                    total_gross = pays[0].amount
+                total_fee = sum((p.fee_amount or 0) for p in pays if p.currency == pay_cur)
+                net_amt = max(0, total_gross - total_fee)
+                return net_amt, pay_cur, total_gross, total_fee
             else:
-                return o.final_amount, (o.base_currency or "CNY")
+                return o.final_amount, (o.base_currency or "CNY"), o.final_amount, 0
 
         revenue_by_currency: Dict[str, int] = {}
+        fee_by_currency: Dict[str, int] = {}
+        gross_by_currency: Dict[str, int] = {}
         for o in orders:
-            amt, cur = resolve_order_payment(o)
-            revenue_by_currency[cur] = revenue_by_currency.get(cur, 0) + amt
+            net_amt, cur, gross_amt, fee_amt = resolve_order_payment(o)
+            revenue_by_currency[cur] = revenue_by_currency.get(cur, 0) + net_amt
+            fee_by_currency[cur] = fee_by_currency.get(cur, 0) + fee_amt
+            gross_by_currency[cur] = gross_by_currency.get(cur, 0) + gross_amt
 
         total_orders = len(orders)
         total_cost = sum(costs_summary.values())
@@ -210,7 +217,7 @@ class SettlementService:
         order_details: List[SettlementOrderDetailOut] = []
 
         for o in orders:
-            order_amt, order_cur = resolve_order_payment(o)
+            order_amt, order_cur, gross_amt, fee_amt = resolve_order_payment(o)
             order_cost = avg_cost_cny if order_cur == "CNY" else 0
             order_profit = max(0, order_amt - order_cost)
             dev_id = resolve_order_developer(o)
@@ -232,6 +239,8 @@ class SettlementService:
                     developer_name=dev_name,
                     order_amount=order_amt,
                     currency=order_cur,
+                    gross_amount=gross_amt,
+                    fee_amount=fee_amt,
                     original_amount=o.final_amount,
                     original_currency=o.base_currency or order_cur,
                     avg_cost=order_cost,
@@ -287,6 +296,8 @@ class SettlementService:
                 developer_name=dev_name,
                 order_amount=order_amt,
                 currency=order_cur,
+                gross_amount=gross_amt,
+                fee_amount=fee_amt,
                 original_amount=o.final_amount,
                 original_currency=o.base_currency or order_cur,
                 avg_cost=order_cost,

+ 47 - 0
scripts/migrate_payment_fee.py

@@ -0,0 +1,47 @@
+import asyncio
+from sqlalchemy import text
+from app.core.database import engine
+
+async def migrate():
+    async with engine.begin() as conn:
+        res = await conn.execute(text("""
+            SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
+            WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'vas_payment';
+        """))
+        cols = [r[0] for r in res.fetchall()]
+        print("Existing columns in vas_payment:", cols)
+
+        if "fee_rate" not in cols:
+            print("Adding fee_rate column...")
+            await conn.execute(text("ALTER TABLE vas_payment ADD COLUMN fee_rate DECIMAL(6,4) NOT NULL DEFAULT 0.0000 COMMENT '手续费率' AFTER random_offset;"))
+            print("Added fee_rate.")
+        else:
+            print("fee_rate column already exists.")
+
+        if "fee_amount" not in cols:
+            print("Adding fee_amount column...")
+            await conn.execute(text("ALTER TABLE vas_payment ADD COLUMN fee_amount INT NOT NULL DEFAULT 0 COMMENT '手续费金额' AFTER fee_rate;"))
+            print("Added fee_amount.")
+        else:
+            print("fee_amount column already exists.")
+
+        # Also initialize default provider config for fee_rate if null or empty
+        import json
+        print("Checking vas_payment_provider configs...")
+        for name, cfg in [
+            ('stripe', {'fee_rate': 0.035, 'fee_fixed': 30, 'fee_label': '3.5% + €0.30'}),
+            ('creem', {'fee_rate': 0.035, 'fee_fixed': 0, 'fee_label': '3.5%'}),
+            ('wechat', {'fee_rate': 0.0, 'fee_fixed': 0, 'fee_label': '免手续费'}),
+            ('alipay', {'fee_rate': 0.0, 'fee_fixed': 0, 'fee_label': '免手续费'}),
+        ]:
+            await conn.execute(text("""
+                UPDATE vas_payment_provider 
+                SET config = :cfg 
+                WHERE name = :name AND (config IS NULL OR config = 'null' OR config = '');
+            """), {'cfg': json.dumps(cfg), 'name': name})
+        print("Provider configs checked and updated.")
+
+    print("Migration finished successfully.")
+
+if __name__ == "__main__":
+    asyncio.run(migrate())