Parcourir la source

feat: 重建磁力金牛托管niu.py(D线带护栏)

- 对照D线F1/F2/F3:刷余额/当日报表+ROI→停计划止损(消耗阈值)→调ROI
  (目标档位+容差)→anchor回写yue/ciliroi→充值下单(金额×1000/esp-id:22/
  x-nonce改随机)→收银台→ksurl.cn二维码→轮询SUCCESS→money记账
- 护栏:ads.enabled默认false(开箱只读,资金写操作全跳过);充值仅下单出码,
  付款必须人工扫码(同原版F3③人工环节);sql20远程充值任务通道(A线C2)不建
- db补建money表(恢复README所述六表);config补ads默认块
- run_auto修复interval_sec=0被当假值回退300秒的睡死bug
- test_niu.py 12用例(默认只读零写调用/停计划阈值两侧/调ROI容差/
  充值触发三态/二维码链路/轮询记账/循环异常隔离)
wubinggen il y a 3 mois
Parent
commit
ee81317069

+ 29 - 2
白盒重建/config.example.json

@@ -1,9 +1,23 @@
 {
 {
   "db_path": "data.db",
   "db_path": "data.db",
   "ai": {
   "ai": {
-    "zhipu_api_key": "在此填你自己的智谱APIKey(开放平台 bigmodel.cn 申请)",
+    "zhipu_keys": ["在此填你自己的智谱APIKey(bigmodel.cn 申请),可多枚做轮换容错"],
+    "zhipu_api_key": "单key直接填这里;多key也可用竖线分隔 k1|k2|k3(与数组位合并去重)",
     "model": "cogview-3-flash",
     "model": "cogview-3-flash",
-    "pollinations_fallback": true
+    "image_size": "1024x1024",
+    "pollinations_fallback": true,
+    "key_cooldown_sec": 300
+  },
+  "caption": {
+    "font_file": "",
+    "font_size": 32,
+    "font_color": "white",
+    "box": true,
+    "box_color": "black",
+    "box_opacity": 0.5,
+    "border_w": 0,
+    "border_color": "black",
+    "shadow_color": ""
   },
   },
   "translate": {
   "translate": {
     "baidu_appid": "自己的百度翻译appid",
     "baidu_appid": "自己的百度翻译appid",
@@ -25,5 +39,18 @@
     "delay_sec": [30, 180],
     "delay_sec": [30, 180],
     "daily_limit_per_account": 5
     "daily_limit_per_account": 5
   },
   },
+  "ads": {
+    "enabled": false,
+    "interval_sec": 300,
+    "stop_enabled": true,
+    "stop_cost_threshold": 10.0,
+    "bid_enabled": true,
+    "roi_target": 0.0,
+    "roi_tolerance": 0.0,
+    "recharge_enabled": false,
+    "recharge_threshold": 0.0,
+    "recharge_amount": 0.0,
+    "include_not_live": false
+  },
   "proxy": { "enabled": false, "api_url": "" }
   "proxy": { "enabled": false, "api_url": "" }
 }
 }

+ 7 - 1
白盒重建/kuaishou_tool/config.py

@@ -15,7 +15,8 @@ DEFAULTS = {
         "产品主图": "产品主图", "上传主图": "上传主图", "置顶视频": "置顶视频",
         "产品主图": "产品主图", "上传主图": "上传主图", "置顶视频": "置顶视频",
         "实拍": "实拍", "output": "output", "自定义封面": "自定义封面",
         "实拍": "实拍", "output": "output", "自定义封面": "自定义封面",
     },
     },
-    "ai": {"zhipu_api_key": "", "model": "cogview-3-flash", "pollinations_fallback": True},
+    "ai": {"zhipu_keys": [], "zhipu_api_key": "", "model": "cogview-3-flash",
+           "pollinations_fallback": True, "key_cooldown_sec": 300},
     "translate": {"baidu_appid": "", "baidu_key": ""},
     "translate": {"baidu_appid": "", "baidu_key": ""},
     "collect": {
     "collect": {
         "poll_interval_sec": 300,
         "poll_interval_sec": 300,
@@ -23,6 +24,11 @@ DEFAULTS = {
                     "min_commission": 0.0, "max_price": 0.0, "ban_shops": []},
                     "min_commission": 0.0, "max_price": 0.0, "ban_shops": []},
     },
     },
     "publish": {"fragment_mb": 8, "delay_sec": [30, 180], "daily_limit_per_account": 5},
     "publish": {"fragment_mb": 8, "delay_sec": [30, 180], "daily_limit_per_account": 5},
+    "ads": {"enabled": False, "interval_sec": 300,
+            "stop_enabled": True, "stop_cost_threshold": 10.0,
+            "bid_enabled": True, "roi_target": 0.0, "roi_tolerance": 0.0,
+            "recharge_enabled": False, "recharge_threshold": 0.0,
+            "recharge_amount": 0.0, "include_not_live": False},
     "proxy": {"enabled": False, "api_url": ""},
     "proxy": {"enabled": False, "api_url": ""},
     "ffmpeg": "ffmpeg",
     "ffmpeg": "ffmpeg",
 }
 }

+ 5 - 0
白盒重建/kuaishou_tool/db.py

@@ -55,6 +55,11 @@ CREATE TABLE IF NOT EXISTS ips (
     uid TEXT, userName TEXT, ip TEXT, port TEXT,
     uid TEXT, userName TEXT, ip TEXT, port TEXT,
     user TEXT, password TEXT, usefulTime TEXT
     user TEXT, password TEXT, usefulTime TEXT
 );
 );
+CREATE TABLE IF NOT EXISTS money (
+    id INTEGER PRIMARY KEY AUTOINCREMENT,
+    userName TEXT, amounts REAL,
+    createdTime TEXT DEFAULT ''
+);
 CREATE UNIQUE INDEX IF NOT EXISTS onlyUid ON anchor (uid);
 CREATE UNIQUE INDEX IF NOT EXISTS onlyUid ON anchor (uid);
 CREATE UNIQUE INDEX IF NOT EXISTS onlyIP ON ips (ip);
 CREATE UNIQUE INDEX IF NOT EXISTS onlyIP ON ips (ip);
 CREATE UNIQUE INDEX IF NOT EXISTS onlyVideo ON publishvideo (videoId);
 CREATE UNIQUE INDEX IF NOT EXISTS onlyVideo ON publishvideo (videoId);

+ 283 - 0
白盒重建/kuaishou_tool/niu.py

@@ -0,0 +1,283 @@
+# -*- coding: utf-8 -*-
+"""磁力金牛广告托管模块(D线白盒重建·带护栏)。
+
+对照 伪码\\D_磁力金牛资金线.md:
+- F1 全自动托管主循环 @0x411E6B:刷余额(owner/info) → 当日报表(report/search
+  + chartReportWithRelativeRatio) → 自动停计划(消耗阈值止损,batch/putStatus)
+  → 自动调ROI(目标档位偏离,campaign/update/bid) → anchor 回写 yue/ciliroi
+  → 余额低于阈值触发充值下单
+- F2 支付成功记账 @0x41A6AB:insert into money(userName,amounts)
+- F3 充值下单+轮询 @0x5C770F:wallet/recharge(金额×1000) → kuaishoupay 收银台
+  → ksurl.cn 转二维码 → 轮询 order_state==SUCCESS
+
+与原工具的差异(护栏,刻意):
+- sql20.php 远程任务通道(A线C2)**不建**:充值/调价决策只来自本地 cfg;
+- 充值只做「下单+出码+轮询」,付款须人工扫码确认(原工具 F3③ 同款人工环节);
+- cfg['ads']['enabled'] 默认 False:关着时本模块只读(刷余额/报表/回写展示列),
+  任何资金写操作(停计划/调ROI/充值下单)都不会执行,且各有独立子开关;
+- 每次资金相关动作记 warning 日志(含金额/计划id/ROI 目标值)。
+"""
+import logging
+import random
+import time
+from urllib.parse import quote
+
+from . import config, db
+from .httpclient import KSClient
+
+logger = logging.getLogger('kuaishou_tool.niu')
+
+# ── 端点(D线 §1/§2,C线F2 esp 线同族) ──────────────────────────────
+NIU_BASE = 'https://niu.e.kuaishou.com'
+OWNER_INFO_URL = NIU_BASE + '/rest/esp/owner/info'
+REPORT_URL = NIU_BASE + '/rest/esp/control-panel/report/search'
+CHART_URL = NIU_BASE + '/rest/esp/control-panel/report/chartReportWithRelativeRatio'
+STOP_URL = NIU_BASE + '/rest/esp/promotion/management/campaign/update/batch/putStatus'
+BID_URL = NIU_BASE + '/rest/esp/promotion/hosting/campaign/update/bid'
+RECHARGE_URL = NIU_BASE + '/rest/n/gateway/wallet/recharge'
+CASHIER_URL = 'https://www.kuaishoupay.com/pay/order/pc/trade/cashier'
+ORDER_QUERY_URL = 'https://www.kuaishoupay.com/pay/order/pc/trade/query'
+QR_MAKE_URL = 'https://ksurl.cn/createqrcode'
+
+# ── 托管参数默认值(全部可经 cfg['ads'] 覆盖) ───────────────────────
+ADS_DEFAULTS = {
+    'enabled': False,             # 总开关:False = 只读,不做任何资金写操作
+    'interval_sec': 300,          # 托管循环间隔
+    'stop_enabled': True,         # 写①:自动停计划(消耗阈值止损,D线F1③)
+    'stop_cost_threshold': 10.0,  #   消耗阈值(元;原工具默认10,「消耗大于或等于10元自动停止直播计划」)
+    'bid_enabled': True,          # 写②:自动调ROI(目标档位偏离,D线F1④)
+    'roi_target': 0.0,            #   目标ROI(0=不调;对应原「目标ROI1~6」档位取一)
+    'roi_tolerance': 0.0,         #   容差:|今日ROI-目标|<=容差 不动
+    'recharge_enabled': False,    # 写③:充值下单(付款仍须人工扫码)
+    'recharge_threshold': 0.0,    #   余额低于此值(元)触发;0=不触发
+    'recharge_amount': 0.0,       #   单次充值金额(元)
+    'include_not_live': False,    #   未开播账号是否参与(原工具「未开播用户参与充值」勾选项)
+}
+
+
+class NiuError(Exception):
+    """金牛接口调用失败。"""
+
+
+def _row_get(row, key, default=''):
+    """兼容 sqlite3.Row 与 dict 的按键取值。"""
+    try:
+        return row[key]
+    except (KeyError, IndexError, TypeError):
+        return default
+
+
+def _niu_headers(account_id=''):
+    """esp 线请求头(C线F2:ACCOUNT-ID/App-Key/requestSource/esp-platform)。"""
+    h = {'requestSource': 'PC', 'App-Key': 'ad.adUkmConfig.adEsp',
+         'esp-platform': 'pc', 'esp-entrySrc': '204',
+         'Accept': 'application/json,*/*', 'Content-Type': 'application/json'}
+    if account_id:
+        h['ACCOUNT-ID'] = str(account_id)
+    return h
+
+
+def _json_of(resp):
+    try:
+        return resp.json()
+    except Exception:
+        return None
+
+
+def _ok(resp):
+    j = _json_of(resp)
+    return isinstance(j, dict) and not (j.get('error_msg') or j.get('errorMsg'))
+
+
+# ═══════════════ 只读侧:余额 / 报表(D线F1①②) ═══════════════
+
+def owner_info(client):
+    """账户信息(F1①):data.userEspAccount.balance / data.liveStatus。"""
+    j = _json_of(client.get(OWNER_INFO_URL, headers=_niu_headers())) or {}
+    data = j.get('data') if isinstance(j.get('data'), dict) else {}
+    acc = data.get('userEspAccount') if isinstance(data.get('userEspAccount'), dict) else {}
+    return {'balance': float(acc.get('balance') or 0),
+            'live': str(data.get('liveStatus') or ''), 'raw': j}
+
+
+def report_today(client, day=None):
+    """当日报表(F1②):data.sum.costTotal + data.data[].targetId/bidDetail。"""
+    day = day or time.strftime('%Y-%m-%d')
+    body = {'searchParam': {'sceneOrientedTypes': [21],      # 21=直播(24=商品,另一份调用体)
+                            'startTime': day, 'endTime': day,
+                            'frozen': 0, 'searchLevel': 1}}
+    j = _json_of(client.post(REPORT_URL, json_body=body,
+                             headers=_niu_headers())) or {}
+    data = j.get('data') if isinstance(j.get('data'), dict) else {}
+    rows = data.get('data') if isinstance(data.get('data'), list) else []
+    total = data.get('sum') if isinstance(data.get('sum'), dict) else {}
+    return {'cost': float(total.get('costTotal') or 0),
+            'campaigns': [{'id': r.get('targetId'), 'bid': r.get('bidDetail')}
+                          for r in rows if isinstance(r, dict)],
+            'raw': j}
+
+
+def chart_today(client, day=None):
+    """今日ROI/GMV(F1②:chartReportWithRelativeRatio;返回字段名报告未还原,
+    取 data.roi/data.gmv 常见形态,联调时按实际响应校正)。"""
+    day = day or time.strftime('%Y-%m-%d')
+    body = {'searchParam': {'sceneOrientedTypes': [21],
+                            'startTime': day, 'endTime': day}}
+    j = _json_of(client.post(CHART_URL, json_body=body,
+                             headers=_niu_headers())) or {}
+    data = j.get('data') if isinstance(j.get('data'), dict) else {}
+    return {'roi': float(data.get('roi') or 0), 'gmv': float(data.get('gmv') or 0),
+            'raw': j}
+
+
+# ═══════════════ 写侧①②:停计划 / 调ROI(D线F1③④/F8) ═══════════════
+
+def stop_campaigns(client, campaign_ids):
+    """批量停计划(batch/putStatus,body campaignIdList)。返回是否成功。"""
+    r = client.post(STOP_URL, json_body={'campaignIdList': [str(i) for i in campaign_ids]},
+                    headers=_niu_headers())
+    return _ok(r)
+
+
+def update_roi(client, campaign_id, roi_ratio):
+    """调计划ROI(campaign/update/bid,D线F8 body:roiRatio/speed;
+    programCreative 完整结构报告未还原,白盒含 campaignId 便于服务端定位,
+    联调时按实际接口校正)。"""
+    body = {'campaignId': str(campaign_id), 'programCreative': {},
+            'roiRatio': f'{float(roi_ratio):g}', 'speed': 1}
+    r = client.post(BID_URL, json_body=body, headers=_niu_headers())
+    return _ok(r)
+
+
+# ═══════════════ 写侧③:充值下单→收银台→二维码→轮询(D线F3) ═══════════════
+
+def create_recharge_order(client, account_id, amount_yuan):
+    """充值建单(F3①):rechargeAmount=元×1000(D线注:金额=输入值×1000),
+    esp-id:22;x-nonce 原工具为写死常量,白盒改为每次随机。"""
+    body = {'walletType': 1, 'rechargeAmount': int(round(float(amount_yuan) * 1000)),
+            'tradeType': 2, 'payWay': 3, 'payChannel': 0}
+    h = _niu_headers(account_id)
+    h['esp-id'] = '22'
+    h['x-nonce'] = '%.16f' % random.random()
+    j = _json_of(client.post(RECHARGE_URL, json_body=body, headers=h)) or {}
+    data = j.get('data') if isinstance(j.get('data'), dict) else {}
+    if not data.get('payCode'):
+        raise NiuError('充值建单失败:' + str(j.get('error_msg') or j)[:200])
+    return {'pay_code': str(data.get('payCode')),
+            'merchant_id': str(data.get('merchantCode') or ''),
+            'trace_id': str(j.get('traceId') or ''), 'raw': j}
+
+
+def cashier_qrcode(client, order):
+    """收银台→支付二维码(F3②③):POST cashier(merchant_id/out_order_no=traceId)
+    → qrcode_url;再经 ksurl.cn 转二维码图(付款仍须人工扫码)。"""
+    form = {'merchant_id': order['merchant_id'], 'out_order_no': order['trace_id']}
+    h = {'Content-Type': 'application/x-www-form-urlencoded',
+         'Origin': NIU_BASE, 'Referer': NIU_BASE + '/', 'Sec-Fetch-Site': 'cross-site'}
+    j = _json_of(client.post(CASHIER_URL, data=form, headers=h)) or {}
+    pay_url = str(j.get('qrcode_url') or '')
+    if not pay_url:
+        raise NiuError('收银台未返回支付链接:' + str(j)[:200])
+    qr = (QR_MAKE_URL + '?contentType=URL&toShortUrl=false&content='
+          + quote(pay_url, safe=''))
+    return {'pay_url': pay_url, 'qr_image': qr,
+            'interval': int(j.get('qrcode_interval') or 3), 'raw': j}
+
+
+def poll_order(client, order, timeout_sec=300, interval_sec=None):
+    """轮询订单状态(F3④):order_state==SUCCESS 即支付完成。返回是否成功。"""
+    form = {'merchant_id': order['merchant_id'], 'out_order_no': order['trace_id']}
+    h = {'Content-Type': 'application/x-www-form-urlencoded',
+         'Origin': 'https://www.kuaishoupay.com'}
+    interval = interval_sec or 3
+    end = time.time() + timeout_sec
+    while time.time() < end:
+        j = _json_of(client.post(ORDER_QUERY_URL, data=form, headers=h)) or {}
+        if str(j.get('order_state')) == 'SUCCESS':
+            return True
+        time.sleep(interval)
+    return False
+
+
+def record_money(user_name, amount):
+    """充值记账(F2:insert into money)。"""
+    db.exe('INSERT INTO money (userName, amounts, createdTime) VALUES (?,?,?)',
+           (str(user_name), float(amount), db.now()))
+
+
+# ═══════════════ 托管决策与循环(D线F1 的白盒版) ═══════════════
+
+def auto_manage(cfg, anchor_row, client=None, account_id='') -> dict:
+    """单账号一次托管决策(F1 循环体的单账号粒度)。
+
+    只读侧永远执行:余额/报表/ROI → 回写 anchor.yue/ciliroi(展示列);
+    写侧(停计划/调ROI/充值下单)仅在 cfg['ads']['enabled'] 且各子开关开启时
+    执行;充值只下单出码,付款须人工扫码。返回决策摘要 dict。
+    """
+    ads = dict(ADS_DEFAULTS)
+    ads.update(cfg.get('ads') or {})
+    uid = str(_row_get(anchor_row, 'uid', ''))
+    if client is None:
+        cookie = _row_get(anchor_row, 'cookie3', '') or _row_get(anchor_row, 'cookie1', '')
+        client = KSClient(cookie=cookie, did=_row_get(anchor_row, 'did', ''))
+    res = {'uid': uid, 'balance': None, 'stopped': [], 'adjusted': [], 'recharge': None}
+
+    info = owner_info(client)
+    rep = report_today(client)
+    chart = chart_today(client)
+    res['balance'] = info['balance']
+    db.exe('UPDATE anchor SET yue=?, ciliroi=? WHERE uid=?',
+           (f"{info['balance']:.2f}", f"{chart['roi']:.4f}", uid))
+    cids = [c['id'] for c in rep['campaigns'] if c['id']]
+
+    # 写①:自动停计划(消耗阈值止损)
+    if ads['enabled'] and ads['stop_enabled'] and cids \
+            and rep['cost'] >= float(ads['stop_cost_threshold']):
+        if stop_campaigns(client, cids):
+            res['stopped'] = list(cids)
+            logger.warning('自动停计划: uid=%s 消耗%.2f≥阈值%.2f 停止%s',
+                           uid, rep['cost'], ads['stop_cost_threshold'], cids)
+    # 写②:自动调ROI(目标档位偏离)
+    target = float(ads['roi_target'] or 0)
+    tol = float(ads['roi_tolerance'] or 0)
+    if ads['enabled'] and ads['bid_enabled'] and target > 0 and cids \
+            and abs(chart['roi'] - target) > tol:
+        for cid in cids:
+            if update_roi(client, cid, target):
+                res['adjusted'].append(cid)
+        logger.warning('自动调ROI: uid=%s 今日%.4f→目标%.4f 计划%s',
+                       uid, chart['roi'], target, res['adjusted'])
+    # 写③:充值下单(人工扫码付款)
+    if ads['enabled'] and ads['recharge_enabled'] \
+            and float(ads['recharge_threshold'] or 0) > 0 \
+            and float(ads['recharge_amount'] or 0) > 0 \
+            and info['balance'] < float(ads['recharge_threshold']) \
+            and (info['live'] == '直播中' or ads['include_not_live']):
+        order = create_recharge_order(client, account_id or uid,
+                                      float(ads['recharge_amount']))
+        q = cashier_qrcode(client, order)
+        res['recharge'] = {'amount': float(ads['recharge_amount']),
+                           'pay_code': order['pay_code'], 'qr_image': q['qr_image']}
+        logger.warning('充值下单: uid=%s 余额%.2f<%.2f 订单%.2f元 人工扫码付款: %s',
+                       uid, info['balance'], ads['recharge_threshold'],
+                       ads['recharge_amount'], q['qr_image'])
+    return res
+
+
+def run_auto(cfg, max_rounds=None, interval_sec=None):
+    """托管主循环(F1 的白盒版):遍历 anchor 逐账号 auto_manage。
+    单账号异常不中断循环;默认只读(enabled=False 时写侧全部跳过)。"""
+    ads = dict(ADS_DEFAULTS)
+    ads.update(cfg.get('ads') or {})
+    interval = (interval_sec if interval_sec is not None
+                else int(ads.get('interval_sec') or 300))
+    rounds = 0
+    while max_rounds is None or rounds < max_rounds:
+        rounds += 1
+        for row in db.query('SELECT * FROM anchor ORDER BY id'):
+            try:
+                auto_manage(cfg, row)
+            except Exception as e:
+                logger.warning('托管异常 uid=%s: %s', _row_get(row, 'uid', ''), e)
+        if max_rounds is None or rounds < max_rounds:
+            time.sleep(interval)

+ 262 - 0
白盒重建/tests/test_niu.py

@@ -0,0 +1,262 @@
+# -*- coding: utf-8 -*-
+"""niu.py 单元测试(D线磁力金牛托管·带护栏):HTTP 全部打桩,绝不真实联网。
+
+覆盖:只读报表解析 / 默认只读(写侧零调用) / 停计划止损 / 调ROI /
+充值下单(金额×1000/esp-id/收银台/二维码) / 订单轮询+money 记账 /
+托管循环异常隔离。纯 pytest 风格(对齐 test_media)。
+"""
+import copy
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT))
+
+from kuaishou_tool import config, db, niu  # noqa: E402
+
+
+class FakeResp:
+    def __init__(self, js=None, status=200):
+        self._js, self.status_code = js, status
+
+    def json(self):
+        if self._js is None:
+            raise ValueError('无 JSON')
+        return self._js
+
+
+class FakeKS:
+    """KSClient 替身:按 URL 子串脚本化响应,记录全部调用。"""
+
+    def __init__(self, script=None):
+        self.script = script or {}
+        self.calls = []          # (method, url, body, headers)
+
+    def get(self, url, params=None, headers=None, **kw):
+        self.calls.append(('GET', url, params, headers))
+        return self._resp(url)
+
+    def post(self, url, params=None, json_body=None, data=None, headers=None, **kw):
+        self.calls.append(('POST', url, json_body if json_body is not None else data,
+                           headers))
+        return self._resp(url)
+
+    def _resp(self, url):
+        for key, r in self.script.items():
+            if key in url:
+                return r
+        return FakeResp(js={})
+
+    def by(self, frag):
+        return [c for c in self.calls if frag in c[1]]
+
+
+def _script(balance=100.0, live='直播中', cost=5.0, roi=1.0,
+            campaigns=('c1', 'c2'), pay_code='PC123'):
+    return {
+        'owner/info': FakeResp(js={'data': {'userEspAccount': {'balance': balance},
+                                            'liveStatus': live}}),
+        'report/search': FakeResp(js={'data': {
+            'data': [{'targetId': c, 'bidDetail': '1.0'} for c in campaigns],
+            'sum': {'costTotal': cost}}}),
+        'chartReport': FakeResp(js={'data': {'roi': roi, 'gmv': 250.0}}),
+        'wallet/recharge': FakeResp(js={'data': {'payCode': pay_code,
+                                                 'merchantCode': 'MC77'},
+                                        'traceId': 'TR999'}),
+        'cashier': FakeResp(js={'qrcode_url': 'https://pay.example/x',
+                                'qrcode_interval': 2}),
+        'trade/query': FakeResp(js={'order_state': 'SUCCESS'}),
+        'putStatus': FakeResp(js={'result': 1}),
+        'update/bid': FakeResp(js={'result': 1}),
+    }
+
+
+@pytest.fixture()
+def cfg():
+    c = copy.deepcopy(config.DEFAULTS)
+    c['dirs'] = {k: 'Z:/no_' + k for k in c['dirs']}   # 本模块不落盘,占位即可
+    return c
+
+
+@pytest.fixture(autouse=True)
+def _tmp_db(cfg, tmp_path):
+    old = db._CONN
+    db._CONN = None
+    cfg['db_path'] = str(tmp_path / 'data.db')
+    db.conn(cfg)
+    yield
+    try:
+        db._CONN.close()
+    except Exception:
+        pass
+    db._CONN = old
+
+
+ANCHOR = {'uid': 'U1', 'userName': '号A', 'cookie1': 'ck=1', 'cookie3': '',
+          'did': ''}
+
+
+def _anchor_row():
+    db.exe("INSERT INTO anchor (uid, userName, cookie1, rizhi) "
+           "VALUES ('U1','号A','ck=1','等待投递')")
+    return db.query("SELECT * FROM anchor WHERE uid='U1'")[0]
+
+
+# ---- 只读侧 ----
+
+def test_owner_info_parsing():
+    fc = FakeKS(_script(balance=88.5, live='未开播'))
+    info = niu.owner_info(fc)
+    assert info['balance'] == 88.5 and info['live'] == '未开播'
+
+
+def test_report_parsing():
+    fc = FakeKS(_script(cost=12.5, campaigns=('c9',)))
+    rep = niu.report_today(fc)
+    assert rep['cost'] == 12.5
+    assert [c['id'] for c in rep['campaigns']] == ['c9']
+
+
+def test_auto_manage_readonly_by_default(cfg):
+    """enabled 缺省 False:只刷余额/报表并回写展示列,写侧零调用。"""
+    row = _anchor_row()
+    fc = FakeKS(_script())
+    res = niu.auto_manage(cfg, row, client=fc)
+    assert res['balance'] == 100.0 and res['stopped'] == [] and res['adjusted'] == []
+    assert res['recharge'] is None
+    assert not fc.by('putStatus') and not fc.by('update/bid')
+    assert not fc.by('wallet/recharge') and not fc.by('cashier')
+    a = db.query("SELECT yue, ciliroi FROM anchor WHERE uid='U1'")[0]
+    assert a['yue'] == '100.00' and a['ciliroi'] == '1.0000'   # 展示列已回写
+
+
+# ---- 写侧①:停计划 ----
+
+def test_auto_manage_stop_on_cost_threshold(cfg):
+    """消耗≥阈值 → 批量停计划(body campaignIdList)。"""
+    cfg['ads'] = {'enabled': True, 'stop_cost_threshold': 10.0}
+    row = _anchor_row()
+    fc = FakeKS(_script(cost=12.0))
+    res = niu.auto_manage(cfg, row, client=fc)
+    assert res['stopped'] == ['c1', 'c2']
+    body = fc.by('putStatus')[0][2]
+    assert body['campaignIdList'] == ['c1', 'c2']
+
+
+def test_auto_manage_no_stop_below_threshold(cfg):
+    cfg['ads'] = {'enabled': True, 'stop_cost_threshold': 10.0}
+    row = _anchor_row()
+    fc = FakeKS(_script(cost=9.9))
+    res = niu.auto_manage(cfg, row, client=fc)
+    assert res['stopped'] == [] and not fc.by('putStatus')
+
+
+# ---- 写侧②:调ROI ----
+
+def test_auto_manage_adjust_roi(cfg):
+    """今日ROI偏离目标 → update/bid(roiRatio=目标值)。"""
+    cfg['ads'] = {'enabled': True, 'roi_target': 1.5, 'roi_tolerance': 0.1,
+                  'stop_cost_threshold': 999}      # 关停计划分支
+    row = _anchor_row()
+    fc = FakeKS(_script(cost=1.0, roi=1.0))
+    res = niu.auto_manage(cfg, row, client=fc)
+    assert res['adjusted'] == ['c1', 'c2']
+    assert not fc.by('putStatus')
+    bodies = [c[2] for c in fc.by('update/bid')]
+    assert all(b['roiRatio'] == '1.5' for b in bodies)
+
+
+def test_auto_manage_roi_within_tolerance(cfg):
+    """|今日-目标|<=容差 → 不调。"""
+    cfg['ads'] = {'enabled': True, 'roi_target': 1.5, 'roi_tolerance': 0.5,
+                  'stop_cost_threshold': 999}
+    row = _anchor_row()
+    fc = FakeKS(_script(cost=1.0, roi=1.2))
+    res = niu.auto_manage(cfg, row, client=fc)
+    assert res['adjusted'] == [] and not fc.by('update/bid')
+
+
+# ---- 写侧③:充值下单(人工扫码) ----
+
+def test_recharge_order_and_qrcode():
+    """F3:建单(金额×1000/esp-id:22/x-nonce 随机)→ 收银台 → 二维码图。"""
+    fc = FakeKS(_script())
+    order = niu.create_recharge_order(fc, 'ACC1', 100)
+    assert order['pay_code'] == 'PC123'
+    assert order['merchant_id'] == 'MC77' and order['trace_id'] == 'TR999'
+    m, url, body, h = fc.by('wallet/recharge')[0]
+    assert body == {'walletType': 1, 'rechargeAmount': 100000,   # 100元×1000
+                    'tradeType': 2, 'payWay': 3, 'payChannel': 0}
+    assert h['esp-id'] == '22' and h['ACCOUNT-ID'] == 'ACC1'
+    assert h['x-nonce'] and h['x-nonce'] != '0.4072864651480086'  # 原版写死常量,白盒随机
+    q = niu.cashier_qrcode(fc, order)
+    assert q['pay_url'] == 'https://pay.example/x' and q['interval'] == 2
+    assert q['qr_image'].startswith('https://ksurl.cn/createqrcode?contentType=URL')
+    assert 'https%3A%2F%2Fpay.example%2Fx' in q['qr_image']       # 收银台链接已编码
+    m2, url2, form, _ = fc.by('cashier')[0]
+    assert form == {'merchant_id': 'MC77', 'out_order_no': 'TR999'}
+
+
+def test_auto_manage_recharge_trigger_and_guardrails(cfg):
+    """余额<阈值且直播中 → 下单出码;未开播默认不触发(include_not_live 开关)。"""
+    cfg['ads'] = {'enabled': True, 'stop_cost_threshold': 999, 'roi_target': 0,
+                  'recharge_enabled': True, 'recharge_threshold': 50.0,
+                  'recharge_amount': 200.0}
+    row = _anchor_row()
+    fc = FakeKS(_script(balance=10.0, live='直播中', cost=1.0))
+    res = niu.auto_manage(cfg, row, client=fc, account_id='ACC9')
+    assert res['recharge'] and res['recharge']['amount'] == 200.0
+    assert res['recharge']['qr_image'].startswith('https://ksurl.cn/createqrcode')
+    assert fc.by('wallet/recharge')[0][2]['rechargeAmount'] == 200000
+    # 未开播 + include_not_live=False → 不下单(原工具勾选项语义)
+    fc2 = FakeKS(_script(balance=10.0, live='未开播', cost=1.0))
+    res2 = niu.auto_manage(cfg, row, client=fc2, account_id='ACC9')
+    assert res2['recharge'] is None and not fc2.by('wallet/recharge')
+    # 余额充足 → 不下单
+    fc3 = FakeKS(_script(balance=99.0, live='直播中', cost=1.0))
+    res3 = niu.auto_manage(cfg, row, client=fc3, account_id='ACC9')
+    assert res3['recharge'] is None and not fc3.by('wallet/recharge')
+
+
+def test_poll_order_and_record_money(cfg):
+    """F3④/F2:轮询 SUCCESS → money 表记账。"""
+    fc = FakeKS(_script())
+    order = niu.create_recharge_order(fc, 'ACC1', 66)
+    assert niu.poll_order(fc, order, timeout_sec=1, interval_sec=0) is True
+    assert fc.by('trade/query')[0][2] == {'merchant_id': 'MC77',
+                                          'out_order_no': 'TR999'}
+    niu.record_money('号A', 66)
+    row = db.query('SELECT userName, amounts FROM money')[0]
+    assert row['userName'] == '号A' and row['amounts'] == 66.0
+
+
+def test_poll_order_timeout():
+    fc = FakeKS({'trade/query': FakeResp(js={'order_state': 'WAIT'})})
+    assert niu.poll_order(fc, {'merchant_id': 'm', 'trace_id': 't'},
+                          timeout_sec=0.3, interval_sec=0.1) is False
+
+
+# ---- 托管循环 ----
+
+def test_run_auto_round_isolation(cfg):
+    """循环内单账号异常不中断;max_rounds 限制轮数。"""
+    cfg['ads'] = {'enabled': False, 'interval_sec': 0}
+    db.exe("INSERT INTO anchor (uid, userName, cookie1) VALUES ('U1','a','ck')")
+    db.exe("INSERT INTO anchor (uid, userName, cookie1) VALUES ('U2','b','ck')")
+    boom, ok = {'n': 0}, FakeKS(_script())
+
+    def fake_manage(c, row, client=None, account_id=''):
+        if row['uid'] == 'U1':
+            raise RuntimeError('模拟账号异常')
+        boom['n'] += 1
+        return {}
+
+    orig = niu.auto_manage
+    niu.auto_manage = fake_manage
+    try:
+        niu.run_auto(cfg, max_rounds=2, interval_sec=0)
+    finally:
+        niu.auto_manage = orig
+    assert boom['n'] == 2                       # U2 每轮都跑,U1 异常被吞