File size: 8,378 Bytes
fa152ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Common utilities.
"""

import asyncio
import base64
import re
from typing import Callable, TypeVar

import httpx

from cbh.api.account.dto import AccountType
from cbh.api.account.models import AccountModel
from cbh.api.common.dto import (
    LeaderboardStatisticsPosition,
    Scores,
    OrderType,
    SkillStatistics,
    IDNamePicture,
)
from cbh.api.common.schemas import SkillsStatisticsResponse
from cbh.core.config import settings

T = TypeVar("T")


def calculate_avg_scores(reports: list) -> Scores:
    if not reports:
        return Scores(
            communication=0,
            activeListening=0,
            conversation=0,
            objection=0,
            empathy=0,
            final=0,
        )
    return Scores(
        communication=round(sum(report.scores.communication for report in reports) / len(reports)),
        activeListening=round(
            sum(report.scores.activeListening for report in reports) / len(reports)
        ),
        conversation=round(sum(report.scores.conversation for report in reports) / len(reports)),
        objection=round(sum(report.scores.objection for report in reports) / len(reports)),
        empathy=round(sum(report.scores.empathy for report in reports) / len(reports)),
        final=round(sum(report.scores.final for report in reports) / len(reports)),
    )


def form_user_stats(session_reports: list) -> dict[str, dict]:
    user_stats = {}
    for report in session_reports:
        user_id = report.account.id
        if user_id not in user_stats:
            user_stats[user_id] = {
                "account": report.account,
                "reports": [],
                "attempts": 0,
            }
        user_stats[user_id]["reports"].append(report)
        user_stats[user_id]["attempts"] += 1
    return user_stats


def leaderboard_sort_key(item: tuple, reverse: bool = False) -> tuple:
    user_data, score = item
    if reverse:
        return -score, user_data["attempts"], user_data["account"].name.lower()

    return score, -user_data["attempts"], user_data["account"].name.lower()


def build_leaderboard(
    session_reports: list,
    position_builder: Callable[[dict, Scores], T],
    order: OrderType | None = None,
) -> list[T]:
    user_stats = form_user_stats(session_reports)
    user_scores = [
        (user_data, calculate_avg_scores(user_data["reports"]).final)
        for user_data in user_stats.values()
    ]

    is_descending = order is None or order == OrderType.DESCENDING
    sorted_users = sorted(
        user_scores, key=lambda item: leaderboard_sort_key(item, reverse=is_descending)
    )

    leaderboard = []
    for user_data, _ in sorted_users:
        avg_scores = calculate_avg_scores(user_data["reports"])
        leaderboard.append(position_builder(user_data, avg_scores))

    return leaderboard


def build_leaderboard_simple(
    session_reports: list,
    pageSize: int | None = None,
    pageIndex: int | None = None,
    order: OrderType | None = None,
) -> list[LeaderboardStatisticsPosition]:
    def position_builder(user_data: dict, avg_scores: Scores) -> LeaderboardStatisticsPosition:
        return LeaderboardStatisticsPosition(
            account=IDNamePicture(
                id=user_data["account"].id,
                name=user_data["account"].name,
                pictureUrl=user_data["account"].pictureUrl,
            ),
            scores=avg_scores,
        )

    leaderboard = build_leaderboard(session_reports, position_builder, order)
    return paginate_list(leaderboard, pageSize, pageIndex)


def paginate_list(
    items: list[T], page_size: int | None = None, page_index: int | None = None
) -> list[T]:
    if page_size is None or page_index is None:
        return items
    return items[page_index * page_size : (page_index + 1) * page_size]


def form_additional_scenario_filter(account: AccountModel, allow_demo: bool = False):
    from cbh.api.scenario.dto import AssigneesType, ScenarioStatus

    filter_ = {"owner.organization.id": account.organization.id}
    if account.accountType == AccountType.USER:
        filter_.update(
            {
                "$or": [
                    {"assignees": {"$size": 0}},
                    {
                        "assignees": {
                            "$elemMatch": {
                                "type": AssigneesType.USER.value,
                                "account.id": account.id,
                            }
                        }
                    },
                    {
                        "assignees": {
                            "$elemMatch": {
                                "type": AssigneesType.TEAM.value,
                                "team.members": {"$elemMatch": {"id": account.id}},
                            }
                        }
                    },
                ],
                "isTemplate": False,
                "status": ScenarioStatus.ACTIVE.value,
            }
        )
    if not allow_demo or account.accountType != AccountType.USER:
        filter_.update(
            {
                "isDemo": False,
            }
        )
    return filter_


async def convert_document_to_text(file: bytes, filename: str) -> str:
    if filename.endswith(".txt"):
        return file.decode("utf-8", errors="ignore")
    filename = re.sub(r"[^\w\s.-]", "", filename)
    base64_file = base64.b64encode(file).decode("utf-8")
    headers = {"Content-Type": "application/json"}
    data = {
        "apikey": settings.CONVERTIO_API_KEY,
        "input": "base64",
        "file": base64_file,
        "filename": filename,
        "outputformat": "txt",
    }
    async with httpx.AsyncClient(timeout=httpx.Timeout(timeout=120)) as client:
        response = await client.post("https://api.convertio.co/convert", json=data, headers=headers)
        response = response.json()
        if response["code"] == 200:
            conversion_id = response["data"]["id"]
            status = ""
            attempt = 0
            while status != "finish":
                if attempt > 50:
                    raise Exception("Please, try again")
                get_status_response = await client.get(
                    f"https://api.convertio.co/convert/{conversion_id}/status"
                )
                get_status_response = get_status_response.json()
                if get_status_response["code"] != 200:
                    raise Exception("Please, try again")
                else:
                    status = get_status_response["data"]["step"]
                    await asyncio.sleep(1)
                attempt += 1
            file_url = get_status_response["data"]["output"]["url"]
            response = await client.get(file_url)
            response.raise_for_status()
            return response.content.decode("utf-8", errors="ignore")
        else:
            return ""


def calculate_skills_statistics(session_reports: list) -> SkillsStatisticsResponse:
    """
    Calculate team skills statistics.
    """
    if not session_reports:
        empty_skill = SkillStatistics(score=0, bestAccount=None)
        return SkillsStatisticsResponse(
            communication=empty_skill,
            activeListening=empty_skill,
            conversation=empty_skill,
            objection=empty_skill,
            empathy=empty_skill,
            final=0,
        )
    avg_scores = calculate_avg_scores(session_reports)
    skills = ["communication", "activeListening", "conversation", "objection", "empathy"]

    skill_stats = {}
    for skill in skills:
        best_report = sorted(
            session_reports,
            key=lambda r, s=skill: (getattr(r.scores, s), r.datetimeInserted.timestamp()),
            reverse=True,
        )[0]
        skill_stats[skill] = SkillStatistics(
            score=getattr(avg_scores, skill),
            bestAccount=IDNamePicture(
                id=best_report.account.id,
                name=best_report.account.name,
                pictureUrl=best_report.account.pictureUrl,
            ),
        )

    return SkillsStatisticsResponse(
        communication=skill_stats["communication"],
        activeListening=skill_stats["activeListening"],
        conversation=skill_stats["conversation"],
        objection=skill_stats["objection"],
        empathy=skill_stats["empathy"],
        final=avg_scores.final,
    )