def compare_talent_metrics(
filters: dict,
group_by: list,
) -> dict:
"""Рассчитывает сравнительные показатели талантов."""
if not isinstance(filters, dict):
raise ValueError("Некорректные фильтры.")
if "talent_category" in filters:
raise ValueError(
"Нельзя ограничивать категории при сравнении талантов."
)
if not isinstance(group_by, list):
raise ValueError("Некорректная группировка.")
if any(
field not in ("department", "position")
for field in group_by
):
raise ValueError("Недопустимое поле группировки.")
# Используем существующую проверку фильтров.
query_dataset("employees", filters, group_by)
rows = [
row for row in EMPLOYEES
if all(
row[field] == value
for field, value in filters.items()
)
]
def calculate(items):
total = len(items)
hipo = sum(
row["talent_category"] == "HiPo"
for row in items
)
hipro = sum(
row["talent_category"] == "HiPro"
for row in items
)
return {
"employee_count": total,
"hipo_count": hipo,
"hipro_count": hipro,
"talent_count": hipo + hipro,
"hipo_share_percent": (
round(hipo / total * 100, 2)
if total else None
),
"hipro_share_percent": (
round(hipro / total * 100, 2)
if total else None
),
"talent_share_percent": (
round((hipo + hipro) / total * 100, 2)
if total else None
),
"hipro_to_hipo_ratio": (
round(hipro / hipo, 2)
if hipo else None
),
"hipro_minus_hipo_count": hipro - hipo,
"share_gap_pp": (
round((hipro - hipo) / total * 100, 2)
if total else None
),
}
overall = calculate(rows)
groups = {}
for row in rows:
key = tuple(row[field] for field in group_by)
groups.setdefault(key, []).append(row)
results = []
if group_by:
for key, items in sorted(groups.items()):
metrics = calculate(items)
item = dict(zip(group_by, key))
item.update(metrics)
for category in ("hipo", "hipro", "talent"):
count_field = f"{category}_count"
item[f"{category}_deviation_pp"] = round(
(
metrics[count_field] / len(items)
- overall[count_field] / len(rows)
) * 100,
2,
)
results.append(item)
return {
"dataset_id": "employees",
"source": "synthetic",
"filters": filters,
"group_by": group_by,
"overall": overall,
"groups": results,
"share_base": "employee_count_in_each_group",
"deviation_base": "overall_filtered_population",
"undefined_value": None,
}
TOOLS["compare_talent_metrics"] = {
"description": (
"Рассчитать и сравнить показатели HiPo и HiPro: "
"численность, доли, суммарную долю талантов, "
"соотношение HiPro к HiPo, разницу долей "
"и отклонения от среднего уровня выбранной "
"совокупности сотрудников. "
"Подходит для сравнительного анализа подразделений "
"и должностей. Все показатели рассчитываются "
"программно. Доли рассчитываются внутри каждой "
"группы. Отклонения выражены в процентных пунктах. "
"Null означает, что показатель не определён."
),
"parameters": {
"filters": {
"type": "object",
"description": (
"Точные значения фильтров department "
"и position. Пустой объект — все сотрудники. "
"Фильтрация по talent_category запрещена."
),
},
"group_by": {
"type": "array",
"items": {"type": "string"},
"description": (
"Группировка по department, position "
"или обоим полям. Пустой список — "
"только общие показатели."
),
},
},
"handler": compare_talent_metrics,
}