#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""权限实测：临时实例 + 注入会话，真 HTTP 打 /api/sandept，断言内容（非仅状态码）。"""
import importlib, threading, time, sys, json, urllib.request
SDIR = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/脚本'
sys.path.insert(0, SDIR)
svc = importlib.import_module('销售工作台服务')

TOK = {'chenxizi': 'probe-cxz', 'liuziyan': 'probe-lzy', 'admin': 'probe-adm'}
ids = {
    'chenxizi': {'name': '陈溪子', 'role': 'sales', 'dept': '诊断原料销售拓展部', 'line': 'da', 'email': 'cxz@biori.com'},
    'liuziyan': {'name': '刘子研', 'role': 'sales', 'dept': '诊断原料大客户销售部', 'line': 'da', 'email': 'lzy@biori.com'},
    'admin':    {'name': '超级管理员', 'role': 'admin', 'dept': '诊断原料销售部', 'line': 'da', 'email': 'admin'},
}
for k, t in TOK.items():
    svc.AUTH_SESSIONS[t] = dict(ids[k], expire_at=time.time() + 900)

srv = svc.ThreadingHTTPServer(('127.0.0.1', 8799), svc.Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
time.sleep(0.9)
BASE = 'http://127.0.0.1:8799'

def call(who, path):
    req = urllib.request.Request(BASE + path, headers={'Authorization': 'Bearer ' + TOK[who]})
    with urllib.request.urlopen(req, timeout=20) as r:
        return r.status, json.loads(r.read().decode('utf-8'))

def cust_amt(data, name):
    return round(sum(c.get('amt') or 0 for c in (data.get('customers') or [])
                     if c.get('cust') == name), 2)

YAW = '深圳市雅为世纪科技有限公司'
ok = True
try:
    for who in ('chenxizi', 'liuziyan', 'admin'):
        st, j = call(who, '/api/sandept')
        d = j['data']
        cs = d.get('customers') or []
        yaw_rows = [c for c in cs if c.get('cust') == YAW]
        tot_own = round(sum(c.get('amt') or 0 for c in cs), 2)
        sprows = {r['sp']: round(r.get('amt') or 0, 2) for r in (d.get('salespersons') or []) if r['sp'] in ('刘子研', '陈溪子')}
        sptot = {r['sp']: round(sum(x.get('amt') or 0 for x in (d.get('salespersons') or []) if x['sp'] == r['sp']), 2) for r in (d.get('salespersons') or []) if r['sp'] in ('刘子研', '陈溪子')}
        print(f'--- {who} ({ids[who]["name"]}, role={ids[who]["role"]}) scope={j.get("scope")} ---')
        print(f'    customers 行数={len(cs)}  本人归集额={tot_own}  salespersons姓名集={sorted(set(r["sp"] for r in (d.get("salespersons") or [])))}')
        print(f'    雅为世纪行数={len(yaw_rows)} 金额={cust_amt(d, YAW)}  归属={sorted(set(c.get("sales") for c in yaw_rows))}')
        print(f'    刘子研/陈溪子 salespersons 额={sptot}')
        if who == 'chenxizi':
            assert cust_amt(d, YAW) == 9.79 and len(yaw_rows) == 6, '陈溪子 应看到雅为世纪 6 行 9.79 万'
            assert all(c.get('sales') == '陈溪子' for c in yaw_rows)
            assert tot_own == 476.95, f'陈溪子 归集额 {tot_own} != 476.95'
        if who == 'liuziyan':
            assert len(yaw_rows) == 0, '刘子研 不应看到雅为世纪'
            assert tot_own == 642.40, f'刘子研 归集额 {tot_own} != 642.40'
            assert sptot.get('刘子研') == 644.11, f'刘子研 salespersons {sptot} != 644.11'
        if who == 'admin':
            assert len(cs) == 2137 and cust_amt(d, YAW) == 9.79
    print('\nPERMISSION PROBE: ALL PASSED')
except AssertionError as e:
    ok = False
    print('PROBE FAIL:', e)
finally:
    srv.shutdown()
    for t in TOK.values():
        svc.AUTH_SESSIONS.pop(t, None)
sys.exit(0 if ok else 1)
