File size: 8,838 Bytes
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2c68f
fe40b87
ae2c68f
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2c68f
fe40b87
 
 
 
 
 
 
 
ae2c68f
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2c68f
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2c68f
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
"""Academy reporting: dashboard (N37), earnings (N38), corporate (N39) and consent records (N49-N50).

Metric definitions (an academy is a team; players are accounts with role=player on it; all windows are UTC):
- active_players: distinct team players with >=1 analysed, non-deleted session whose analyzed_at is in the month.
- new_this_month: players whose account created_at is in the month (players have no join timestamp yet).
- improving_pct: among players with >=2 scored sessions analysed in the month, the share whose latest score is
  above their earliest, rounded to a whole percent; null when no player has >=2.
- analyses_this_week: analysed, non-deleted sessions with analyzed_at in the last 7 days (not month-bound).
- avg_review_hours: mean of (review.updated_at - session.created_at) in hours for reviews updated in the month;
  null when there are none. A re-sent review overwrites the row, so this is the latest send, not the first.
- cards: latest scored session per player up to the end of the month; the swing report carries no band field,
  so thresholds apply to overall_score: g >= 80, y 60-79, r < 60. Unscored players are excluded.
- coaches: the owner plus active members; reviews = reviews updated in the month on team players' sessions.
- not_filmed_7d: team players with no non-deleted session created in the last 7 days (never-filmed included).
- Money has no ledger: every amount is null/empty with unavailable_reason. Players' coach_can_see_sessions does not
  limit these academy-level aggregates.
"""

import csv
import io
import re
import uuid
from datetime import UTC, datetime, timedelta

from sqlalchemy.ext.asyncio import AsyncSession

from app.common.academy_access import Staff
from app.common.labels import FOCUS_LABEL, tone_counts
from app.core.errors import Conflict, Forbidden, NotFound, ValidationFailed
from app.core.pagination import Cursor, paginate
from app.integrations.storage import StorageClient
from app.modules.reporting.repository import ReportingRepository
from app.modules.reporting.schemas import (
    Cards,
    CoachActivity,
    ConsentExportRequest,
    ConsentItem,
    ConsentPage,
    Dashboard,
    DashboardResponse,
    Earnings,
    EarningsResponse,
    ExportOut,
    ExportResponse,
)

REVENUE_UNAVAILABLE = "Revenue ledger not configured"
EXPORT_MAX_ROWS = 5000
_MONTH = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$")
_FORMULA_PREFIX = ("=", "+", "-", "@", "\t", "\r")


def month_bounds(month: str | None) -> tuple[str, datetime, datetime]:
    if month is None:
        now = datetime.now(UTC)
        year, mon = now.year, now.month
    else:
        match = _MONTH.match(month)
        if match is None:
            raise ValidationFailed(fields={"month": "Use YYYY-MM."})
        year, mon = int(match[1]), int(match[2])
    start = datetime(year, mon, 1, tzinfo=UTC)
    end = datetime(year + (mon == 12), mon % 12 + 1, 1, tzinfo=UTC)
    return f"{year:04d}-{mon:02d}", start, end


def _safe_cell(value: object) -> str:
    text = "" if value is None else str(value)
    return "'" + text if text.startswith(_FORMULA_PREFIX) else text


def _day(value: datetime) -> str:
    return f"{value.day} {value:%b %Y}"


class ReportingService:
    def __init__(self, db: AsyncSession, storage: StorageClient):
        self.db = db
        self.storage = storage
        self.repo = ReportingRepository(db)

    async def dashboard(self, staff: Staff, month: str | None) -> DashboardResponse:
        staff.require("earnings")
        label, start, end = month_bounds(month)
        team = staff.team_id
        now = datetime.now(UTC)
        repo = self.repo
        denominator, improved = await repo.improving(team, start, end)
        scores = await repo.latest_scores(team, end)
        reviews = await repo.reviews_by_coach(team, start, end)
        coaches = [CoachActivity(id=cid, name=name, coaches=FOCUS_LABEL.get(focus, "Both"), reviews=reviews.get(cid, 0))
                   for cid, name, focus in await repo.coach_rows(team)]
        return DashboardResponse(dashboard=Dashboard(
            month=label,
            active_players=await repo.active_players(team, start, end),
            new_this_month=await repo.new_players(team, start, end),
            improving_pct=round(100 * improved / denominator) if denominator else None,
            analyses_this_week=await repo.analyses_since(team, now - timedelta(days=7)),
            avg_review_hours=await repo.avg_review_hours(team, start, end),
            cards=Cards(**tone_counts(scores)),
            coaches=coaches,
            pending_requests=await repo.pending_requests(team),
            not_filmed_7d=await repo.not_filmed_since(team, now - timedelta(days=7)),
            unavailable_reason=REVENUE_UNAVAILABLE,
            as_of=now,
        ))

    async def earnings(self, staff: Staff, month: str | None) -> EarningsResponse:
        staff.require("earnings")
        label, _, _ = month_bounds(month)
        return EarningsResponse(earnings=Earnings(month=label, as_of=datetime.now(UTC),
                                                  unavailable_reason=REVENUE_UNAVAILABLE))

    async def corporate(self, staff: Staff) -> None:
        # No corporate grant exists (capabilities.corporate_view is false for everyone).
        raise Forbidden("Corporate reporting needs an organization grant.")

    async def _scope(self, staff: Staff, group_id: uuid.UUID | None) -> None:
        if group_id is not None and not await self.repo.group_in_team(staff.team_id, group_id):
            raise NotFound("Group not found.")

    @staticmethod
    def _item(row) -> ConsentItem:
        accepted = row["accepted"]
        withdrawn_at = None if accepted else row["last_withdrawn"]
        if accepted:
            note = f"Accepted {_day(row['last_accepted'])}"
        elif withdrawn_at is not None:
            note = f"Withdrawn {_day(withdrawn_at)}"
        else:
            note = "Not yet accepted"
        return ConsentItem(
            player_id=row["player_id"], name=row["name"], group=row["group"] or "",
            group_ids=row["group_ids"] or [], note=note, version=row["version"],
            accepted_at=row["last_accepted"], withdrawn_at=withdrawn_at, help_improve_ai=row["help_improve_ai"])

    async def consent(self, staff: Staff, group_id: uuid.UUID | None, limit: int, cursor: Cursor | None
                      ) -> ConsentPage:
        await self._scope(staff, group_id)
        accepted, ai_opt_in = await self.repo.consent_totals(staff.team_id, group_id)
        rows = await self.repo.consent_rows(staff.team_id, group_id, limit + 1, cursor)
        page, next_cursor = paginate(rows, limit, lambda r: (r["created_at"], r["player_id"]))
        return ConsentPage(items=[self._item(r) for r in page], next_cursor=next_cursor,
                           accepted=accepted, ai_opt_in=ai_opt_in)

    async def export_consent(self, staff: Staff, body: ConsentExportRequest) -> ExportResponse:
        await self._scope(staff, body.group_id)
        rows = await self.repo.consent_rows(staff.team_id, body.group_id, EXPORT_MAX_ROWS + 1)
        if len(rows) > EXPORT_MAX_ROWS:
            raise Conflict(f"More than {EXPORT_MAX_ROWS} records; narrow the export by group.",
                           code="EXPORT_TOO_LARGE")
        buffer = io.StringIO()
        writer = csv.writer(buffer)
        writer.writerow(["player_id", "name", "group", "status", "version", "accepted_at", "withdrawn_at",
                         "help_improve_ai"])
        for row in rows:
            item = self._item(row)
            status = "accepted" if row["accepted"] else ("withdrawn" if item.withdrawn_at else "none")
            writer.writerow([_safe_cell(v) for v in (
                item.player_id, item.name, item.group, status, item.version or "",
                item.accepted_at.isoformat() if item.accepted_at else "",
                item.withdrawn_at.isoformat() if item.withdrawn_at else "",
                "true" if item.help_improve_ai else "false")])

        now = datetime.now(UTC)
        export_id = uuid.uuid4()
        key = f"exports/{staff.team_id}/{export_id}.csv"
        await self.storage.put_bytes(key, buffer.getvalue().encode(), "text/csv")
        expires_at = now + timedelta(seconds=self.storage.download_ttl)
        filename = f"consent-{now:%Y-%m-%d}.csv"
        job = await self.repo.add_export(id=export_id, requester_id=staff.id, team_id=staff.team_id,
                                         scope="consent", status="ready", object_key=key, filename=filename,
                                         expires_at=expires_at)
        return ExportResponse(export=ExportOut(id=job.id, status="ready", url=self.storage.presign_get(key),
                                               expires_at=expires_at, filename=filename))