-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathservices.py
More file actions
276 lines (235 loc) · 9.69 KB
/
services.py
File metadata and controls
276 lines (235 loc) · 9.69 KB
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import logging
from collections import OrderedDict
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
from partner_programs.models import PartnerProgramUserProfile
from project_rates.models import Criteria, ProjectScore
logger = logging.getLogger()
class ProjectScoreDataPreparer:
"""
Data preparer about project_rates by experts.
"""
USER_ERROR_FIELDS = {
"Фамилия": "ОШИБКА",
"Имя": "ОШИБКА",
"Отчество": "ОШИБКА",
"Email": "ОШИБКА",
"Регион_РФ": "ОШИБКА",
"Учебное_заведение": "ОШИБКА",
"Название_учебного_заведения": "ОШИБКА",
"Класс_курс": "ОШИБКА",
}
EXPERT_ERROR_FIELDS = {"Фамилия эксперта": "ОШИБКА"}
def __init__(
self,
user_profiles: dict[int, PartnerProgramUserProfile],
scores: dict[int, list[ProjectScore]],
project_id: int,
program_id: int,
):
self._project_id = project_id
self._user_profiles = user_profiles
self._scores = scores
self._program_id = program_id
def get_project_user_info(self) -> dict[str, str]:
try:
user_program_profile: PartnerProgramUserProfile = self._user_profiles.get(
self._project_id
)
user_program_profile_json: dict = (
user_program_profile.partner_program_data if user_program_profile else {}
)
user_info: dict[str, str] = {
"Фамилия": (
user_program_profile.user.last_name if user_program_profile else ""
),
"Имя": (
user_program_profile.user.first_name if user_program_profile else ""
),
"Отчество": (
user_program_profile.user.patronymic if user_program_profile else ""
),
"Email": (
user_program_profile_json.get("email")
if user_program_profile_json.get("email")
else user_program_profile.user.email
),
"Регион_РФ": user_program_profile_json.get("region", ""),
"Учебное_заведение": user_program_profile_json.get("education_type", ""),
"Название_учебного_заведения": user_program_profile_json.get(
"institution_name", ""
),
"Класс_курс": user_program_profile_json.get("class_course", ""),
}
return user_info
except Exception as e:
logger.error(
f"Prepare export rates data about user error: {str(e)}", exc_info=True
)
return self.USER_ERROR_FIELDS
def get_project_expert_info(self) -> dict[str, str]:
try:
project_scores: list[ProjectScore] = self._scores.get(self._project_id, [])
first_score = project_scores[0] if project_scores else None
expert_last_name: dict[str, str] = {
"Фамилия эксперта": first_score.user.last_name if first_score else ""
}
return expert_last_name
except Exception as e:
logger.error(
f"Prepare export rates data about expert error: {str(e)}", exc_info=True
)
return self.EXPERT_ERROR_FIELDS
def get_project_scores_info(self) -> dict[str, str]:
try:
project_scores_dict = {}
project_scores: list[ProjectScore] = self._scores.get(self._project_id, [])
score_info_with_out_comment: dict[str, str] = {
score.criteria.name: score.value
for score in project_scores
if score.criteria.name != "Комментарий"
}
project_scores_dict.update(score_info_with_out_comment)
comment = next(
(
score
for score in project_scores
if score.criteria.name == "Комментарий"
),
None,
)
if comment is not None:
project_scores_dict["Комментарий"] = comment.value
return project_scores_dict
except Exception as e:
logger.error(
f"Prepare export rates data about project_scores error: {str(e)}",
exc_info=True,
)
return {
criteria.name: "ОШИБКА"
for criteria in Criteria.objects.filter(
partner_program__id=self._program_id
)
}
BASE_COLUMNS = [
("row_number", "№ п/п"),
("project_name", "Название проекта"),
("project_description", "Описание проекта"),
("project_region", "Регион проекта"),
("project_presentation", "Ссылка на презентацию"),
("team_size", "Количество человек в команде"),
("team_members", "Состав команды"),
("leader_full_name", "Имя фамилия лидера"),
]
EXCEL_CELL_MAX = 32767 # лимит символов в ячейке Excel
def sanitize_excel_value(value):
"""
Приводит значение к безопасному для openpyxl виду:
- None -> ""
- для строк: вычищает запрещённые символы, нормализует переносы строк,
и обрезает до лимита Excel (32767).
- для чисел/булевых оставляет как есть.
"""
if value is None:
return ""
if isinstance(value, (int, float, bool)):
return value
text = str(value)
text = text.replace("\r\n", "\n").replace("\r", "\n")
text = ILLEGAL_CHARACTERS_RE.sub(" ", text)
if len(text) > EXCEL_CELL_MAX:
text = text[: EXCEL_CELL_MAX - 3] + "..."
return text
def _leader_full_name(user):
if not user:
return ""
if hasattr(user, "get_full_name") and callable(user.get_full_name):
full = user.get_full_name()
if full:
return full
first = getattr(user, "first_name", "") or ""
last = getattr(user, "last_name", "") or ""
return (first + " " + last).strip() or getattr(user, "username", "") or str(user.pk)
def _calc_team_size(project):
prefetched_collaborators = getattr(project, "_prefetched_collaborators", None)
if prefetched_collaborators is not None:
return 1 + len(prefetched_collaborators)
try:
if hasattr(project, "get_collaborators_user_list"):
return 1 + len(project.get_collaborators_user_list())
if hasattr(project, "collaborator_set"):
return 1 + project.collaborator_set.count()
except Exception:
pass
return 1
def _team_members(project) -> str:
members: list[str] = []
seen_ids: set[int | None] = set()
leader = getattr(project, "leader", None)
if leader:
leader_name = _leader_full_name(leader)
if leader_name:
members.append(leader_name)
seen_ids.add(getattr(leader, "id", None))
collaborators = getattr(project, "_prefetched_collaborators", None)
if collaborators is None:
collaborators = (
project.collaborator_set.select_related("user").all()
if hasattr(project, "collaborator_set")
else []
)
for collaborator in collaborators:
user = getattr(collaborator, "user", None)
if not user:
continue
user_id = getattr(user, "id", None)
if user_id in seen_ids:
continue
name = _leader_full_name(user)
if not name:
continue
members.append(name)
seen_ids.add(user_id)
return "\n".join(members)
def build_program_field_columns(program) -> list[tuple[str, str]]:
program_fields = program.fields.all().order_by("pk")
return [
(f"name:{program_field.name}", program_field.label)
for program_field in program_fields
]
def row_dict_for_link(
program_project_link,
extra_field_keys_order: list[str],
row_number: int,
) -> OrderedDict:
"""
program_project_link: PartnerProgramProject
extra_field_keys_order: список псевдоключей "name:<field.name>" в нужном порядке
row_number: порядковый номер строки в Excel (начиная с 1)
"""
project = program_project_link.project
row = OrderedDict()
row["row_number"] = row_number
row["project_name"] = project.name or ""
row["project_description"] = project.description or ""
row["project_region"] = project.region or ""
row["project_presentation"] = project.presentation_address or ""
row["team_size"] = _calc_team_size(project)
row["team_members"] = _team_members(project)
row["leader_full_name"] = _leader_full_name(getattr(project, "leader", None))
values_map: dict[str, str] = {}
prefetched_values = getattr(program_project_link, "_prefetched_field_values", None)
field_values_iterable = (
prefetched_values
if prefetched_values is not None
else program_project_link.field_values.all()
)
for field_value in field_values_iterable:
if (
field_value.field.partner_program_id
== program_project_link.partner_program_id
):
values_map[f"name:{field_value.field.name}"] = field_value.get_value()
for field_key in extra_field_keys_order:
row[field_key] = values_map.get(field_key, "")
return row