File size: 10,748 Bytes
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import csv
import io
import uuid
from datetime import UTC, datetime, timedelta

import httpx
from sqlalchemy import update

from app.core.database import get_session_factory
from app.modules.academy.models import GroupPlayer, PlayerGroup
from app.modules.accounts.models import Account
from app.modules.settings.models import ConsentEvent, UserSettings
from tests.factories import create_team, join, make_account, make_session

DAY = 60 * 24


async def _team(client, n_players=0):
    coach = await make_account("coach", name="Imran Baig")
    team = await create_team(client, coach)
    players = []
    for i in range(n_players):
        p = await make_account("player", name=f"Player {i}")
        await join(client, p, team["code"])
        players.append(p)
    return coach, team, players


async def _db(*statements):
    async with get_session_factory()() as db:
        for s in statements:
            await db.execute(s)
        await db.commit()


async def test_dashboard_reconciles(client):
    coach, _, (a, b, c, d) = await _team(client, 4)
    # a: improving 60 -> 85 (green). b: 70 -> 50 (red). c: single 65 (yellow). d: never filmed.
    await make_session(a["id"], score=60, minutes_ago=3 * 60)
    await make_session(a["id"], score=85, minutes_ago=60)
    await make_session(b["id"], score=70, minutes_ago=3 * 60)
    await make_session(b["id"], score=50, minutes_ago=60)
    s_c = await make_session(c["id"], score=65, minutes_ago=30)
    await make_session(c["id"], analyzed=False, minutes_ago=5)  # pending: not counted
    await make_session(a["id"], score=99, deleted=True, minutes_ago=5)  # deleted: not counted
    old = await make_session(d["id"], score=90, minutes_ago=9 * DAY)  # analysed 9 days ago, in another week
    month = datetime.now(UTC).strftime("%Y-%m")
    r = await client.post(f"/v1/sessions/{s_c}/review", headers=coach["headers"],
                          json={"cue": "x", "drill_id": "hit_13", "verdicts": {}})
    assert r.status_code in (200, 201), r.text

    response = await client.get("/v1/academy/dashboard", headers=coach["headers"])
    assert response.status_code == 200, response.text
    dash = response.json()["dashboard"]
    assert dash["month"] == month
    assert dash["currency"] is None and dash["earnings_minor"] is None
    assert dash["paying_players"] is None and dash["per_player_minor"] is None
    assert dash["earnings_bars"] == [] and dash["unavailable_reason"] == "Revenue ledger not configured"
    assert dash["new_this_month"] == 4
    assert dash["pending_requests"] == 0
    assert dash["not_filmed_7d"] == 1  # d's session is 9 days old
    assert dash["coaches"][0]["id"] == str(coach["id"]) and dash["coaches"][0]["reviews"] == 1
    assert dash["avg_review_hours"] is not None and dash["avg_review_hours"] >= 0
    assert dash["as_of"]
    # old can fall in the previous month near a month start; assert only month-independent parts conditionally
    in_month = datetime.now(UTC) - timedelta(days=9) >= datetime.now(UTC).replace(day=1, hour=0, minute=0)
    assert dash["active_players"] == (4 if in_month else 3)
    assert dash["analyses_this_week"] == 5
    assert dash["improving_pct"] == 50  # a improved, b declined
    assert dash["cards"] == {"g": 1 if not in_month else 2, "y": 1, "r": 1}
    assert old


async def test_dashboard_other_month_and_bad_month(client):
    coach, _, [p] = await _team(client, 1)
    await make_session(p["id"], score=70)
    response = await client.get("/v1/academy/dashboard?month=2020-01", headers=coach["headers"])
    dash = response.json()["dashboard"]
    assert dash["month"] == "2020-01" and dash["active_players"] == 0 and dash["improving_pct"] is None
    assert dash["cards"] == {"g": 0, "y": 0, "r": 0}
    for bad in ("2026-13", "2026-1", "abc", "2026-10-01"):
        r = await client.get(f"/v1/academy/dashboard?month={bad}", headers=coach["headers"])
        assert r.status_code == 400, bad
        assert r.json()["error"]["code"] == "VALIDATION"


async def test_dashboard_empty_team_is_truthful(client):
    coach, _, _ = await _team(client)
    dash = (await client.get("/v1/academy/dashboard", headers=coach["headers"])).json()["dashboard"]
    assert (dash["active_players"], dash["new_this_month"], dash["analyses_this_week"], dash["not_filmed_7d"]) == (
        0, 0, 0, 0)
    assert dash["improving_pct"] is None and dash["avg_review_hours"] is None
    assert dash["cards"] == {"g": 0, "y": 0, "r": 0}


async def test_non_admins_are_forbidden(client):
    player = await make_account("player")
    coach_no_team = await make_account("coach")
    for who in (player, coach_no_team):
        for method, path in (("GET", "/v1/academy/dashboard"), ("GET", "/v1/academy/earnings"),
                             ("GET", "/v1/academy/corp"), ("GET", "/v1/academy/consent")):
            r = await client.request(method, path, headers=who["headers"])
            assert r.status_code == 403, (path, r.text)
        r = await client.post("/v1/academy/consent/export", headers=who["headers"], json={"format": "csv"})
        assert r.status_code == 403
    assert (await client.get("/v1/academy/dashboard")).status_code == 401


async def test_earnings_all_null(client):
    coach, _, _ = await _team(client)
    r = await client.get("/v1/academy/earnings?month=2026-10", headers=coach["headers"])
    assert r.status_code == 200
    e = r.json()["earnings"]
    assert e["month"] == "2026-10" and e["payouts"] == [] and e["next_cursor"] is None
    for key in ("currency", "month_minor", "players", "per_player_minor", "ytd_minor", "projected_minor"):
        assert e[key] is None
    assert e["unavailable_reason"] == "Revenue ledger not configured"
    assert (await client.get("/v1/academy/earnings?month=nope", headers=coach["headers"])).status_code == 400


async def test_corp_forbidden_even_for_admin(client):
    coach, _, _ = await _team(client)
    r = await client.get("/v1/academy/corp", headers=coach["headers"])
    assert r.status_code == 403 and r.json()["error"]["code"] == "FORBIDDEN"


async def _consent(account_id, action, version="1.0", ago=timedelta(0)):
    async with get_session_factory()() as db:
        db.add(ConsentEvent(account_id=account_id, category="analysis", action=action, policy_version=version,
                            created_at=datetime.now(UTC) - ago))
        await db.commit()


async def test_consent_list_and_totals(client):
    coach, team, (a, b, c) = await _team(client, 3)
    await _consent(a["id"], "accepted", ago=timedelta(days=2))
    await _consent(b["id"], "accepted", ago=timedelta(days=3))
    await _consent(b["id"], "withdrawn", ago=timedelta(days=1))
    async with get_session_factory()() as db:
        db.add(UserSettings(account_id=a["id"], help_improve_ai=True))
        group = PlayerGroup(team_id=uuid.UUID(team["id"]), name="14U", focus="Both")
        db.add(group)
        await db.flush()
        db.add(GroupPlayer(group_id=group.id, player_id=a["id"]))
        await db.commit()
        group_id = str(group.id)

    r = await client.get("/v1/academy/consent", headers=coach["headers"])
    assert r.status_code == 200, r.text
    body = r.json()
    assert (body["accepted"], body["ai_opt_in"]) == (1, 1)
    by_name = {i["name"]: i for i in body["items"]}
    assert len(by_name) == 3
    pa, pb, pc = by_name["Player 0"], by_name["Player 1"], by_name["Player 2"]
    assert pa["note"].startswith("Accepted ") and pa["group"] == "14U" and pa["group_ids"] == [group_id]
    assert pa["help_improve_ai"] is True and pa["version"] == "1.0" and pa["withdrawn_at"] is None
    assert pb["note"].startswith("Withdrawn ") and pb["withdrawn_at"] and pb["accepted_at"]
    assert pc["note"] == "Not yet accepted" and pc["version"] is None and pc["group"] == "" and pc["group_ids"] == []

    # totals cover the full scope, not the page
    page = (await client.get("/v1/academy/consent?limit=2", headers=coach["headers"])).json()
    assert len(page["items"]) == 2 and page["next_cursor"] and (page["accepted"], page["ai_opt_in"]) == (1, 1)
    rest = (await client.get(f"/v1/academy/consent?limit=2&cursor={page['next_cursor']}",
                             headers=coach["headers"])).json()
    assert len(rest["items"]) == 1 and rest["next_cursor"] is None

    filtered = (await client.get(f"/v1/academy/consent?group_id={group_id}", headers=coach["headers"])).json()
    assert [i["name"] for i in filtered["items"]] == ["Player 0"] and filtered["accepted"] == 1
    other = await client.get(f"/v1/academy/consent?group_id={uuid.uuid4()}", headers=coach["headers"])
    assert other.status_code == 404


async def test_consent_empty_team(client):
    coach, _, _ = await _team(client)
    body = (await client.get("/v1/academy/consent", headers=coach["headers"])).json()
    assert body == {"items": [], "next_cursor": None, "accepted": 0, "ai_opt_in": 0}


async def test_consent_export_csv_escapes_formulas(client):
    coach, team, (a, b) = await _team(client, 2)
    await _db(update(Account).where(Account.id == a["id"]).values(name="=HYPERLINK(\"x\")"),
              update(Account).where(Account.id == b["id"]).values(name="+cmd|' /C calc'!A0"))
    await _consent(a["id"], "accepted")
    headers = {**coach["headers"], "Idempotency-Key": "k1"}
    r = await client.post("/v1/academy/consent/export", headers=headers, json={"format": "csv"})
    assert r.status_code == 201, r.text
    export = r.json()["export"]
    assert export["status"] == "ready" and export["filename"].startswith("consent-") and export["id"]
    async with httpx.AsyncClient() as s3:
        got = await s3.get(export["url"])
    assert got.status_code == 200
    rows = list(csv.reader(io.StringIO(got.text)))
    assert rows[0][:4] == ["player_id", "name", "group", "status"]
    names = {row[1] for row in rows[1:]}
    assert names == {"'=HYPERLINK(\"x\")", "'+cmd|' /C calc'!A0"}
    assert {row[3] for row in rows[1:]} == {"accepted", "none"}
    # replay with the same key returns the same export
    again = await client.post("/v1/academy/consent/export", headers=headers, json={"format": "csv"})
    assert again.status_code == 201 and again.json()["export"]["id"] == export["id"]
    # unsupported format
    bad = await client.post("/v1/academy/consent/export", headers=coach["headers"], json={"format": "xlsx"})
    assert bad.status_code in (400, 422)


async def test_consent_export_too_large(client, monkeypatch):
    coach, _, _ = await _team(client, 2)
    monkeypatch.setattr("app.modules.reporting.service.EXPORT_MAX_ROWS", 1)
    r = await client.post("/v1/academy/consent/export", headers=coach["headers"], json={"format": "csv"})
    assert r.status_code == 409 and r.json()["error"]["code"] == "EXPORT_TOO_LARGE"