File size: 13,284 Bytes
2756f0f
 
 
 
 
 
 
 
fe40b87
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe40b87
 
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import uuid

import pytest
from sqlalchemy import select

from app.core.database import get_session_factory
from app.integrations.push import get_push_client
from app.modules.devices.models import Device
from tests.factories import METRICS, FakePush, create_team, join, make_account, make_session, upload


@pytest.fixture
def push(app):
    fake = FakePush(dead=["dead-token"])
    app.dependency_overrides[get_push_client] = lambda: fake
    yield fake
    app.dependency_overrides.pop(get_push_client, None)


@pytest.fixture
async def team(client):
    coach = await make_account("coach", name="Imran Baig")
    team = await create_team(client, coach)
    player = await make_account("player", name="Ahmed")
    await join(client, player, team["code"])
    return {"coach": coach, "player": player, "code": team["code"]}


BODY = {"cue": "Point your back pocket at the catcher.", "drill_id": "hit_13",
        "verdicts": {METRICS[0]: "agree", METRICS[1]: "change"}}


async def _devices(account_id) -> list[str]:
    async with get_session_factory()() as db:
        return list(await db.scalars(select(Device.push_token).where(Device.account_id == account_id)))


async def test_review_create_overwrite_and_push(client, team, push):
    for token in ("good-token", "dead-token"):
        response = await client.post("/v1/devices", headers=team["player"]["headers"],
                                     json={"platform": "ios", "push_token": token})
        assert response.status_code == 201
    session_id = await make_session(team["player"]["id"])

    response = await client.post(f"/v1/sessions/{session_id}/review", headers=team["coach"]["headers"], json=BODY)
    assert response.status_code == 201, response.text
    review = response.json()["review"]
    assert review["coach_id"] == str(team["coach"]["id"])
    assert review["coach_name"] == "Imran Baig"
    assert (review["cue"], review["drill_id"], review["verdicts"]) == (BODY["cue"], "hit_13", BODY["verdicts"])
    assert review["at"]
    [(tokens, data)] = push.calls
    assert sorted(tokens) == ["dead-token", "good-token"]
    assert data["type"] == "review.received" and data["session_id"] == str(session_id)  # legacy routing keys
    assert data["kind"] == "review" and data["notification_id"]
    assert await _devices(team["player"]["id"]) == ["good-token"]  # FCM-rejected token removed

    again = {"cue": "Stay tall.", "drill_id": "hit_01", "verdicts": {METRICS[0]: "later"}}
    response = await client.post(f"/v1/sessions/{session_id}/review", headers=team["coach"]["headers"], json=again)
    assert response.status_code == 200
    second = response.json()["review"]
    assert (second["cue"], second["drill_id"], second["verdicts"]) == ("Stay tall.", "hit_01", {METRICS[0]: "later"})
    assert second["at"] >= review["at"]
    assert len(push.calls) == 2

    queue = (await client.get("/v1/coach/queue", headers=team["coach"]["headers"])).json()
    assert queue["open"] == []
    assert [s["id"] for s in queue["reviewed_today"]] == [str(session_id)]


async def test_review_without_verdicts_and_pitching_drill(client, team, push):
    session_id = await make_session(team["player"]["id"], mode="p")
    response = await client.post(f"/v1/sessions/{session_id}/review", headers=team["coach"]["headers"],
                                 json={"cue": "Drive off the rubber.", "drill_id": "pit_01"})
    assert response.status_code == 201, response.text
    assert response.json()["review"]["verdicts"] == {}
    assert push.calls == []  # no devices registered


async def test_review_validation(client, team, push):
    session_id = await make_session(team["player"]["id"])
    url = f"/v1/sessions/{session_id}/review"
    cases = [
        ({**BODY, "drill_id": "pit_01"}, "drill_id"),          # pitching drill on a hitting session
        ({**BODY, "drill_id": "nope"}, "drill_id"),
        ({**BODY, "verdicts": {"not_a_metric": "agree"}}, "verdicts.not_a_metric"),
        ({**BODY, "verdicts": {METRICS[0]: "maybe"}}, None),
        ({**BODY, "cue": "   "}, "cue"),
        ({**BODY, "cue": "x" * 201}, "cue"),
        ({**BODY, "extra": True}, "extra"),
    ]
    for body, field in cases:
        response = await client.post(url, headers=team["coach"]["headers"], json=body)
        assert response.status_code == 400, body
        error = response.json()["error"]
        assert error["code"] == "VALIDATION"
        if field:
            assert field in error["fields"], error
    assert push.calls == []


async def test_review_forbidden(client, team, push):
    coach = team["coach"]
    other_coach = await make_account("coach")
    await create_team(client, other_coach, name="Other Team")
    session_id = await make_session(team["player"]["id"])

    not_self = await make_session(team["player"]["id"], is_self=False)
    pending = await make_session(team["player"]["id"], analyzed=False)
    stranger = await make_account("player")
    stranger_session = await make_session(stranger["id"])
    lone_coach = await make_account("coach")

    for headers, sid in [(other_coach["headers"], session_id), (lone_coach["headers"], session_id),
                         (coach["headers"], not_self), (coach["headers"], pending),
                         (coach["headers"], stranger_session), (team["player"]["headers"], session_id)]:
        response = await client.post(f"/v1/sessions/{sid}/review", headers=headers, json=BODY)
        assert response.status_code == 403, response.text
        assert response.json()["error"]["code"] == "FORBIDDEN"

    # A player who left the team can no longer be reviewed by the old coach.
    await client.delete("/v1/me/team", headers=team["player"]["headers"])
    response = await client.post(f"/v1/sessions/{session_id}/review", headers=coach["headers"], json=BODY)
    assert response.status_code == 403
    assert (await client.post(f"/v1/sessions/{session_id}/review", json=BODY)).status_code == 401
    assert push.calls == []


async def test_review_not_found(client, team, push):
    deleted = await make_session(team["player"]["id"], deleted=True)
    for sid in (deleted, uuid.uuid4()):
        response = await client.post(f"/v1/sessions/{sid}/review", headers=team["coach"]["headers"], json=BODY)
        assert response.status_code == 404
        assert response.json()["error"]["code"] == "NOT_FOUND"


# ---------- thread, voice note, authorization (coaching workflow) ----------

async def _audio(client, headers, *, put=True, seconds=12, content_type="audio/mp4") -> str:
    import httpx

    data = b"\x00\x00\x00\x18ftypM4A " + b"\x00" * 40
    response = await client.post("/v1/uploads", headers=headers, json={
        "kind": "audio", "content_type": content_type, "size_bytes": len(data), "duration_sec": seconds})
    assert response.status_code == 201, response.text
    target = response.json()
    if put:
        async with httpx.AsyncClient() as s3:
            assert (await s3.put(target["url"], content=data, headers=target["headers"])).status_code == 200
    return target["upload_id"]


async def _notifications(account_id) -> list:
    from app.modules.notifications.models import Notification

    async with get_session_factory()() as db:
        return list(await db.scalars(select(Notification).where(Notification.recipient_id == account_id)
                                     .order_by(Notification.created_at)))


async def test_review_creates_one_thread_and_notification(client, team, push):
    session_id = await make_session(team["player"]["id"])
    url = f"/v1/sessions/{session_id}/review"
    first = await client.post(url, headers=team["coach"]["headers"], json=BODY)
    assert first.status_code == 201, first.text
    thread_id = first.json()["thread_id"]
    assert first.json()["review"]["voice_note"] is None

    player = team["player"]["headers"]
    thread = (await client.get(f"/v1/sessions/{session_id}/thread", headers=player)).json()["thread"]
    assert thread["id"] == thread_id and thread["status"] == "reviewed"
    assert thread["unread_for_player"] is True and thread["unread_for_coach"] is False
    [message] = thread["messages"]
    assert message["kind"] == "review" and message["from"] == "coach" and message["cue"] == BODY["cue"]
    assert message["drill_id"] == "hit_13" and message["drill_name"]
    assert {f["metric_id"]: f["verdict"] for f in message["findings"]} == BODY["verdicts"]
    assert message["audio"] is None and message["assignment_id"] is None

    [note] = await _notifications(team["player"]["id"])
    assert note.kind == "review" and note.target == {"thread_id": thread_id, "session_id": str(session_id)}

    # Read, then re-review: same thread and message row, unread again, one more notification.
    read = await client.post(f"/v1/threads/{thread_id}/read", headers=player, json={"last_message_id": message["id"]})
    assert read.status_code == 204
    assert (await client.get(f"/v1/threads/{thread_id}", headers=player)).json()["thread"]["unread_for_player"] is False
    again = await client.post(url, headers=team["coach"]["headers"], json={**BODY, "cue": "Stay tall."})
    assert again.status_code == 200 and again.json()["thread_id"] == thread_id
    thread = (await client.get(f"/v1/threads/{thread_id}", headers=player)).json()["thread"]
    assert thread["unread_for_player"] is True
    assert [m["id"] for m in thread["messages"]] == [message["id"]]
    assert thread["messages"][0]["cue"] == "Stay tall."
    assert len(await _notifications(team["player"]["id"])) == 2


async def test_review_voice_note_attach_keep_remove(client, team, push):
    coach = team["coach"]["headers"]
    session_id = await make_session(team["player"]["id"])
    url = f"/v1/sessions/{session_id}/review"
    upload_id = await _audio(client, coach)

    response = await client.post(url, headers=coach, json={**BODY, "voice_note_upload_id": upload_id,
                                                           "voice_note_seconds": 12})
    assert response.status_code == 201, response.text
    note = response.json()["review"]["voice_note"]
    assert note["upload_id"] == upload_id and note["seconds"] == 12 and note["url"] and note["expires_at"]

    # The player sees it on the session read and as the review message audio; no separate voice bubble.
    player = team["player"]["headers"]
    session = (await client.get(f"/v1/sessions/{session_id}", headers=player)).json()["session"]
    assert session["review"]["voice_note"]["upload_id"] == upload_id
    thread = (await client.get(f"/v1/sessions/{session_id}/thread", headers=player)).json()["thread"]
    [message] = thread["messages"]
    assert message["audio"]["upload_id"] == upload_id and message["voice_seconds"] == 12

    kept = await client.post(url, headers=coach, json={**BODY, "cue": "New cue."})
    assert kept.json()["review"]["voice_note"]["upload_id"] == upload_id
    removed = await client.post(url, headers=coach, json={**BODY, "voice_note_upload_id": None})
    assert removed.json()["review"]["voice_note"] is None
    thread = (await client.get(f"/v1/sessions/{session_id}/thread", headers=player)).json()["thread"]
    assert thread["messages"][0]["audio"] is None


async def test_review_voice_note_errors(client, team, push):
    coach = team["coach"]["headers"]
    session_id = await make_session(team["player"]["id"])
    url = f"/v1/sessions/{session_id}/review"
    pending = await _audio(client, coach, put=False)
    response = await client.post(url, headers=coach, json={**BODY, "voice_note_upload_id": pending,
                                                           "voice_note_seconds": 5})
    assert response.status_code == 409 and response.json()["error"]["code"] == "UPLOAD_NOT_READY"

    others = await _audio(client, team["player"]["headers"])
    response = await client.post(url, headers=coach, json={**BODY, "voice_note_upload_id": others,
                                                           "voice_note_seconds": 5})
    assert response.status_code == 422 and response.json()["error"]["code"] == "INVALID_UPLOAD"
    thumb = await upload(client, coach, "thumbnail")
    response = await client.post(url, headers=coach, json={**BODY, "voice_note_upload_id": thumb,
                                                           "voice_note_seconds": 5})
    assert response.status_code == 422
    good = await _audio(client, coach)
    response = await client.post(url, headers=coach, json={**BODY, "voice_note_upload_id": good})
    assert response.status_code == 400 and "voice_note_seconds" in response.json()["error"]["fields"]
    # Nothing was written by the failed attempts.
    assert (await client.get(f"/v1/sessions/{session_id}/thread", headers=team["player"]["headers"])
            ).status_code == 404


async def test_review_respects_sharing_and_permission(client, team, push):
    from app.modules.settings.models import UserSettings

    session_id = await make_session(team["player"]["id"])
    async with get_session_factory()() as db:
        db.add(UserSettings(account_id=team["player"]["id"], coach_can_see_sessions=False))
        await db.commit()
    response = await client.post(f"/v1/sessions/{session_id}/review", headers=team["coach"]["headers"], json=BODY)
    assert response.status_code == 403