-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyandex_api.py
More file actions
1796 lines (1424 loc) · 56.2 KB
/
yandex_api.py
File metadata and controls
1796 lines (1424 loc) · 56.2 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import datetime
import json
import logging
import re
import urllib.parse
from configparser import ConfigParser
from typing import Any
# Project-Specific Modules
import db_module as db
from db_module import Task
import utils
from utils import perform_http_request
from common_utils import normalize_department_name
import gandiva_api as gapi
class YandexConfig:
"""Encapsulate Yandex-related configuration and API tokens."""
def __init__(self, config: ConfigParser):
chars = '"\''
section = str('Yandex')
self.x_cloud_org_id = config.get(
section, 'x_cloud_org_id').strip(chars)
self.oauth_token = config.get(section, 'oauth_token').strip(chars)
self.oauth_refresh_token = str()
self.client_id = config.get(section, 'client_id').strip(chars)
self.client_secret = config.get(section, 'client_secret').strip(chars)
self.robot_id = config.get(section, 'robot_id').strip(chars)
self.disk_oauth_token = config.get(
section, 'disk_oauth_token').strip(chars)
self.path_to_excel = config.get(section, 'path_to_excel').strip(chars)
section = str('YandexCustomFieldIds')
self.fid_gandiva = config.get(section, 'gandiva').strip(chars)
self.fid_initiator = config.get(section, 'initiator').strip(chars)
self.fid_initiator_department = (config.get(section, 'initiator_department')
.strip(chars))
self.fid_analyst = config.get(section, 'analyst').strip(chars)
self.fid_gandiva_task_id = config.get(
section, 'gandiva_task_id').strip(chars)
self.fid_nd = config.get(section, 'nd').strip(chars)
self.fid_date_created_in_g = config.get(
section, 'date_created_in_g').strip(chars)
# OAuth URLs
self.oauth_token_url = "https://oauth.yandex.ru/token"
self.info_token_url = "https://login.yandex.ru/info"
# API URLs
self.gandiva_task_url = 'https://gandiva.s-stroy.ru/Request/Edit/'
self.api_host = "https://api.tracker.yandex.net"
# Headers
self.headers = {
"X-Cloud-Org-Id": self.x_cloud_org_id,
"Authorization": f"OAuth {self.oauth_token}"
}
self.disk_headers = {
"Authorization": f"OAuth {self.disk_oauth_token}"
}
yc = YandexConfig(utils.ConfigObject)
def get_query_in_progress(queue: str) -> str:
"""
Get a query to filter tasks in Yandex Tracker that are in progress.
Args:
queue (str): The queue to filter tasks from.
Returns:
str: The query string.
"""
query = (
'Resolution: empty() "Status Type": !cancelled "Status Type": '
f'!done Queue: {queue} "Sort by": Updated DESC')
return query
def get_query_all(queue: str) -> str:
query = f'Queue: {queue} "Sort by": Updated DESC'
return query
# Authorization block
async def refresh_access_token(refresh_token: str | None = None) -> str | None:
if refresh_token is None:
refresh_token = yc.oauth_refresh_token
body: dict[str, str] = {
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": yc.client_id,
"client_secret": yc.client_secret,
}
body_url_encoded: str = urllib.parse.urlencode(body)
headers: dict[str, str] = {
'Content-Type': 'application/x-www-form-urlencoded',
}
response: dict[str, Any] | Any = await perform_http_request(
"POST", yc.oauth_token_url, headers=headers, body=body_url_encoded)
if response is None:
logging.error("Failed to refresh access token.")
return
access_token: str | None = response.get('access_token')
new_refresh_token: str | None = response.get('refresh_token')
if not (access_token and new_refresh_token):
logging.error("Failed to retrieve access token.")
return
yc.oauth_token = access_token
yc.oauth_refresh_token = new_refresh_token
return access_token
async def check_access_token(access_token: str) -> None:
account_info = await get_account_info(access_token)
if isinstance(account_info, dict) and account_info:
logging.info(f"Authorized user: {account_info['login']}")
return
new_access_token = await refresh_access_token()
if new_access_token is None:
logging.error("Failed to refresh access token.")
return
return await check_access_token(new_access_token)
async def get_access_token_via_captcha() -> str | None:
captcha_code = input(
"Code (get from https://oauth.yandex.ru/authorize?"
f"response_type=code&client_id={yc.client_id}): "
)
body = {
"grant_type": "authorization_code",
"code": captcha_code,
"client_id": yc.client_id,
"client_secret": yc.client_secret,
}
json_body = json.dumps(body)
response_json = await perform_http_request("POST", yc.oauth_token_url, body=json_body)
if response_json and isinstance(response_json, dict):
logging.info("Successfully retrieved access token.")
return response_json.get("access_token")
logging.error("Failed to retrieve access token. Please try again.")
return
# Utils specific to Yandex
async def g_to_y_fields(
g_task: dict[str, Any],
edit: bool,
to_get_followers: bool = False,
) -> dict[str, Any] | None:
"""
Converts a Gandiva task into a Yandex Tracker task payload.
This function is used when creating a new task in Yandex Tracker
or when editing an existing one.
It takes a Gandiva task, a boolean indicating whether the task is
being created or edited, and a boolean indicating whether to get followers for the task,
and returns a dictionary containing the fields for the Yandex Tracker task.
The returned dictionary contains the following fields:
- summary: a string containing the task summary.
- description: a string containing the task description.
- assignee: a string containing the Yandex Tracker ID of the assignee.
- followers: a list of strings containing the Yandex Tracker IDs of the followers.
- initiator_id: an integer containing the ID of the initiator in Gandiva.
- initiator_name: a string containing the name of the initiator.
- initiator_department: a string containing the department of the initiator.
- yandex_start_date: a string containing the start date of the task in the format %Y-%m-%d.
- nd: a string containing the number of days until the deadline.
- g_task_id: a string containing the ID of the task in Gandiva.
- gandiva: a string containing the URL of the task in Gandiva.
- date_created_in_g: a string containing the date and time of creation of the
task in Gandiva in the format %Y-%m-%dT%H:%M:%S.%f%z.
The function returns None if the task is invalid (e.g. if the initiator is missing).
:param g_task: a dictionary containing the fields of the Gandiva task.
:param edit: a boolean indicating whether the task is being created or edited.
:param to_get_followers: a boolean indicating whether to get followers for the task.
:return: a dictionary containing the fields for the Yandex
Tracker task, or None if the task is invalid.
"""
g_task_id = str(g_task["Id"])
initiator: dict[str, str] | None = g_task.get("Initiator")
if not isinstance(initiator, dict):
logging.error(f"Initiator is empty in task {g_task_id}!")
return
initiator_first_name = initiator.get("FirstName")
initiator_second_name = initiator.get("LastName")
if not initiator_first_name or not initiator_second_name:
logging.error(f"Initiator is empty in task {g_task_id}!")
return
initiator_name = f"{initiator_first_name} {initiator_second_name}"
description = utils.html_to_yandex_format(g_task["Description"])
initiator_id = g_task["Initiator"]["Id"]
initiator_department = await gapi.get_department_by_user_id(g_user_id=initiator_id)
nd = await get_nd_by_department(initiator_department)
y_assignee_id = await get_y_assignee_id(g_task.get("Contractor"))
y_start_date = get_date_convert(g_task, "RequiredStartDate")
y_date_created_in_g = get_date_convert(g_task, "CreateDate")
if not edit:
return create_add_task_payload(
g_task_id,
initiator_name,
description,
y_assignee_id,
initiator_id,
initiator_department,
y_start_date,
nd,
y_date_created_in_g,
)
followers = await get_followers(g_task_id, to_get_followers)
return create_edit_task_payload(
g_task_id,
initiator_name,
description,
initiator_id,
initiator_department,
y_start_date,
y_assignee_id,
followers,
nd,
y_date_created_in_g,
)
async def get_nd_by_department(
department_name: str | None
) -> str | None:
if not department_name:
return
db_session = db.get_db_session()
return db.get_nd_by_department_name(session=db_session, department_name=department_name)
async def get_y_assignee_id(
g_assignee: dict[str, Any] | None
) -> str | None:
"""Retrieve Yandex assignee ID from Gandiva assignee."""
if not g_assignee:
return
g_assignee_id = g_assignee.get('Id')
if not g_assignee_id:
return
g_assignee_id = str(g_assignee_id)
db_session = db.get_db_session()
assignee = db.get_user_by_gandiva_id(
session=db_session, g_user_id=g_assignee_id)
return str(assignee.yandex_user_id) if assignee else None
async def get_followers(
g_task_id: str, to_get_followers: bool
) -> list[str]:
if not to_get_followers:
return []
g_task_detailed = await gapi.get_task(g_task_id)
if isinstance(g_task_detailed, dict):
observers = utils.extract_observers_from_detailed_task(g_task_detailed)
db_session = db.get_db_session()
return db.convert_gandiva_observers_to_yandex_followers(
session=db_session, gandiva_observers=observers
)
return []
def create_add_task_payload(
g_task_id: str,
initiator_name: str,
description: str,
y_assignee_id: str | None,
initiator_id: str,
initiator_department: str | None,
y_start_date: str | None,
nd: str | None,
y_date_created_in_g: str | None
) -> dict[str, str | None]:
return {
'gandiva_task_id': g_task_id,
'initiator_name': initiator_name,
'description': description,
'assignee_id_yandex': y_assignee_id,
'task_type': "improvement",
'initiator_id': initiator_id,
'initiator_department': initiator_department,
'yandex_start_date': y_start_date,
'nd': nd,
'date_created_in_g': y_date_created_in_g
}
def create_edit_task_payload(
g_task_id: str,
initiator_name: str,
description: str,
initiator_id: str,
initiator_department: str | None,
y_start_date: str | None,
y_assignee_id: str | None,
followers: list[str],
nd: str | None,
y_date_created_in_g: str | None) -> dict[str, str | list[str] | None]:
return {
'gandiva_task_id': g_task_id,
'initiator_name': initiator_name,
'description': description,
'initiator_id': initiator_id,
'initiator_department': initiator_department,
'yandex_start_date': y_start_date,
'assignee_id_yandex': y_assignee_id,
'followers': followers,
'nd': nd,
'date_created_in_g': y_date_created_in_g
}
def get_date_convert(
g_task: dict[str, Any],
key: str
) -> str | None:
g_start_date = g_task.get(key)
y_start_date: str | None = None
if g_start_date:
y_start_date = utils.convert_gandiva_to_yandex_date(g_start_date)
return y_start_date
# Functions
async def get_account_info(
access_token: str
) -> dict[str, Any] | None:
"""
Gets Yandex account info by providing the access_token.
"""
body: dict[str, str] = {
"oauth_token": access_token,
"format": "json",
}
json_body = json.dumps(body)
response = await perform_http_request(
'POST', yc.info_token_url, headers=yc.headers, body=json_body
)
if not (response and isinstance(response, dict)):
return
return response
async def get_page_of_tasks(
queue: str | None = None, keys: str | list[str] | None = None,
_filter: dict[str, Any] | None = None, query: str | None = None,
order: str | None = None, expand: str | None = None,
login: str | None = None, page_number: int = 1, per_page: int = 5000
) -> list[dict[str, Any]] | None:
body: dict[str, Any] = {}
if query:
body["query"] = query
elif queue:
body["filter"] = {"queue": queue}
if login:
body["filter"]["assignee"] = login
if _filter:
body["filter"].update(_filter)
elif keys:
body["keys"] = keys
elif _filter:
body["filter"] = _filter
if login:
body["filter"]["assignee"] = login
elif login:
body["filter"] = {"assignee": login}
if "filter" in body and order:
body["order"] = order
body_json = json.dumps(body)
url = f"{yc.api_host}/v2/issues/_search?perPage={per_page}"
if page_number > 1:
url += f"&page={page_number}"
if expand:
url += f"&expand={expand}"
response = await perform_http_request('POST', url, headers=yc.headers, body=body_json)
if response is None:
logging.error(
f"Failed to get page of tasks with query: {body} and page number: {page_number}."
)
return
if not isinstance(response, list):
logging.error(f"Got type: {type(response)}; list expected")
return
logging.debug(f"Page of tasks fetched.")
return response
async def get_tasks_count(
queue: str | None = None, filter: dict[str, Any] | None = None,
query: str | None = None, assignee: str | None = None
) -> int | None:
body: dict[str, Any] = {}
if query:
body["query"] = query
elif queue:
body["filter"] = {"queue": queue}
if assignee:
body["filter"]["assignee"] = assignee
if filter:
body["filter"].update(filter)
elif filter:
body["filter"] = filter
if assignee:
body["filter"]["assignee"] = assignee
elif assignee:
body["filter"] = {"assignee": assignee}
url = f"{yc.api_host}/v2/issues/_count"
response = await perform_http_request('POST', url, headers=yc.headers, body=json.dumps(body))
if not (response and isinstance(response, int)):
logging.error(f"Tasks with query: {body} were not found.")
return
return response
async def get_tasks(
queue: str | None = None,
keys: str | list[str] | None = None,
_filter: dict[str, Any] | None = None,
query: str | None = None,
order: str | None = None,
expand: str | None = None,
login: str | None = None
) -> list[dict[str, Any]]:
if not queue and not query:
raise ValueError("Queue or query must be specified.")
per_page = 2000
all_y_tasks: list[dict[str, Any]] = []
page_number = 1
while True:
y_tasks = await get_page_of_tasks(
queue=queue, keys=keys, _filter=_filter, query=query,
order=order, expand=expand, login=login, page_number=page_number,
per_page=per_page)
if y_tasks is None:
raise ValueError("y_tasks is None, list expected.")
all_y_tasks.extend(y_tasks)
if len(y_tasks) < per_page:
break
page_number += 1
return all_y_tasks
async def get_tasks_by_gandiva_ids(g_ids: list[str]) -> dict[str, Any] | None:
"""Get tasks by their Gandiva IDs"""
body: dict[str, Any] = {
"filter": {yc.fid_gandiva_task_id: g_ids}
}
body_json: str = json.dumps(body)
url: str = f"{yc.api_host}/v2/issues/_search?perPage=5000"
response = await perform_http_request(
'POST', url, headers=yc.headers, body=body_json
)
if not (response and isinstance(response, dict)):
logging.error(f"Failed to get tasks with Gandiva IDs: {g_ids}")
return
return response
async def get_page_of_users(
page: int = 1,
per_page: int = 100
) -> list[dict[str, Any]] | None:
"""Returns page of users """
url = f"{yc.api_host}/v2/users?perPage={per_page}&page={page}"
response = await perform_http_request("GET", url, headers=yc.headers)
if not (response and isinstance(response, list)):
logging.error(f"Failed to get users.")
return
return response
async def get_all_users(per_page: int = 100) -> list[dict[str, Any]]:
"""
Retrieves all users from the Yandex Tracker instance.
:param per_page: The number of users to retrieve per page.
:return: A list of dictionaries representing the users.
"""
all_users: list[dict[str, Any]] = []
page = 1
while True:
users = await get_page_of_users(page=page, per_page=per_page)
if users is None:
break
all_users.extend(users)
if len(users) < per_page:
break
page += 1
return all_users
async def get_task(y_task_id: str) -> dict[str, Any] | None:
"""Returns task (dictionary type) """
url = f"{yc.api_host}/v2/issues/{y_task_id}"
response = await perform_http_request("GET", url, headers=yc.headers)
if not (response and isinstance(response, dict)):
logging.error(f"Failed to get task {y_task_id}.")
return
return response
async def add_task(
g_task_id: str,
initiator_name: str,
queue: str,
description: str = "Без описания",
y_assignee: str | None = None,
task_type: str | None = None,
initiator_department: str | None = None,
start: str | None = None,
nd: str | None = None,
y_step: int | None = None,
date_created_in_g: str | None = None
) -> dict[str, Any] | None | Task:
db_session = db.get_db_session()
if task_in_db := db.get_task_by_gandiva_id(db_session, g_task_id=g_task_id):
return task_in_db
task_summary = f"{g_task_id}. {description[:50]}..."
body = {
"summary": task_summary,
"description": description,
"queue": queue,
yc.fid_initiator: initiator_name,
yc.fid_gandiva: yc.gandiva_task_url + g_task_id,
yc.fid_gandiva_task_id: g_task_id,
}
if y_assignee:
body["assignee"] = y_assignee
if task_type:
body["type"] = task_type
if initiator_department:
body[yc.fid_initiator_department] = initiator_department
analyst = db.get_user_id_by_department(
session=db_session, department_name=initiator_department)
if analyst:
body[yc.fid_analyst] = analyst
if y_step in [0, 1, 2]:
body["assignee"] = analyst
if nd:
body[yc.fid_nd] = nd
if date_created_in_g:
body[yc.fid_date_created_in_g] = date_created_in_g
if start:
body["start"] = start
body_json = json.dumps(body)
url = f"{yc.api_host}/v2/issues"
response = await perform_http_request('POST', url, headers=yc.headers, body=body_json)
if not (response and isinstance(response, dict)):
logging.error(f"Failed to add task {g_task_id}")
return
task_id_yandex = response.get('key')
if not task_id_yandex:
logging.error(
f"Failed to retrieve task key from response for task {g_task_id}")
return
db.add_or_update_task(session=db_session,
g_task_id=g_task_id, y_task_id=task_id_yandex)
return response
async def add_tasks(
g_tasks: list[dict[str, Any]],
queue: str,
non_closed_ya_task_ids: dict[str, str]
) -> int:
logging.info("Adding tasks...")
added_task_count = 0
for g_task in g_tasks:
g_task_id = str(g_task['Id'])
if g_task_id in non_closed_ya_task_ids:
logging.debug(f"Task {g_task_id} already exists.")
db.add_or_update_task(
session=db.get_db_session(),
g_task_id=g_task_id,
y_task_id=non_closed_ya_task_ids[g_task_id]
)
continue
fields = await g_to_y_fields(g_task, edit=False)
if not isinstance(fields, dict):
logging.error("Fields is None, dict expected!")
return 0
initiator_name = fields.get('initiator_name')
if not initiator_name:
continue
new_description = await description_with_attachments(
g_task_id, str(fields.get('description'))
) or str(fields.get('description'))
y_status = utils.g_to_y_status(str(g_task['Status']))
if not y_status:
continue
y_step = utils.y_status_to_id(y_status)
if not y_step:
continue
result = await add_task(
g_task_id,
initiator_name,
initiator_department=fields.get('initiator_department'),
description=new_description,
queue=queue,
y_assignee=fields.get('assignee_id_yandex'),
task_type=fields.get('task_type'),
start=fields.get('yandex_start_date'),
nd=fields.get('nd'),
y_step=y_step,
date_created_in_g=fields.get('date_created_in_g')
)
if isinstance(result, dict):
logging.info(f"Added task {g_task_id}")
added_task_count += 1
logging.info(f"Total tasks added: {added_task_count}")
return added_task_count
def edit_field_if_empty(
y_task: dict[str, Any], field_id: str, new_value: str | None
) -> str | None:
"""
Helper function to determine if a field needs to be updated based on it being empty or not.
:param y_task: The task object from Yandex.
:param field_id: The field ID to check in the Yandex task.
:param new_value: The new value that might need to be applied.
:return: The new value if it needs to be updated, None otherwise.
"""
if new_value and not y_task.get(field_id):
return new_value
return
def edit_field_if_different_content(
y_task: dict[str, Any], field_id: str, new_value: str
) -> str | None:
"""
Helper function to determine if a field needs to be updated based on it being empty or not.
:param y_task: The task object from Yandex.
:param field_id: The field ID to check in the Yandex task.
:param new_value: The new value that might need to be applied.
:return: The new value if it needs to be updated, None otherwise.
"""
if y_task.get(field_id) and new_value != y_task.get(field_id):
return new_value
return
async def update_task_if_needed(
y_task: dict[str, Any],
g_task_id: str,
initiator_name: str,
initiator_department: str | None,
description: str | None,
y_start_date: str | None,
y_assignee: str | None,
followers: list[str] | None,
nd: str | None,
y_step: int,
g_contractor_id: str | None,
y_date_created_in_g: str | None,
initiator_id: str
) -> bool:
"""
Check which fields need to be updated and call edit_task if any updates are necessary.
"""
y_task_id: str = y_task.get('key', '')
initiator_department = normalize_department_name(
initiator_department) if initiator_department else None
# Determine fields to edit
edit_followers = determine_followers(y_task, followers)
edit_assignee = determine_assignee(y_task, y_step, y_assignee)
edit_description = determine_description(y_task, description)
gandiva: str = yc.gandiva_task_url + g_task_id
# Gather fields for updating
edit_initiator_name = edit_field_if_empty(
y_task, yc.fid_initiator, initiator_name)
edit_initiator_department = edit_field_if_empty(
y_task, yc.fid_initiator_department, initiator_department)
edit_yandex_start_date = edit_field_if_empty(y_task, 'start', y_start_date)
edit_gandiva_task_id = edit_field_if_empty(
y_task, yc.fid_gandiva_task_id, g_task_id)
edit_gandiva = edit_field_if_empty(y_task, yc.fid_gandiva, gandiva)
edit_nd = edit_field_if_empty(y_task, yc.fid_nd, nd)
y_date_created_in_g = edit_field_if_empty(
y_task, yc.fid_date_created_in_g, y_date_created_in_g)
assignee_id = None
assignee: dict[str, Any] | None = y_task.get('assignee') or {}
if isinstance(assignee, dict) and 'id' in assignee:
assignee_id = str(assignee.get('id'))
db_session = db.get_db_session()
update_analyst_and_assignee(
y_task,
initiator_department,
y_step,
g_contractor_id,
assignee_id,
initiator_id,
db_session
)
if not any((
edit_initiator_name,
edit_initiator_department,
edit_description,
edit_yandex_start_date,
edit_assignee,
edit_followers,
edit_gandiva_task_id,
edit_gandiva,
edit_nd,
y_date_created_in_g
)):
logging.debug(f"Task {g_task_id} is already up-to-date.")
return False
response_json = await edit_task(
y_task_id=y_task_id,
initiator_name=edit_initiator_name,
initiator_department=edit_initiator_department,
description=edit_description,
start=edit_yandex_start_date,
analyst=None, # Placeholder for analyst update logic
y_assignee_id=edit_assignee,
followers=edit_followers,
g_task_id=edit_gandiva_task_id,
gandiva=edit_gandiva,
nd=edit_nd,
date_created_in_g=y_date_created_in_g
)
return response_json is not None
def determine_followers(
y_task: dict[str, Any],
new_followers: list[str] | None
) -> list[str] | None:
"""Determine if followers need to be updated."""
if not new_followers:
return
current_followers = y_task.get('followers', [])
return new_followers if len(current_followers) < len(new_followers) else None
def determine_assignee(y_task: dict[str, Any], y_step: int, new_assignee: str | None) -> str | None:
"""Determine if the assignee needs to be updated."""
current_assignee = y_task.get('assignee', {}).get('id')
return new_assignee if y_step not in [0, 1, 2] and current_assignee != new_assignee else None
def determine_description(y_task: dict[str, Any], new_description: str | None) -> str | None:
"""Determine if the description needs to be updated."""
return edit_field_if_different_content(y_task, 'description', new_description) if new_description else None
def update_analyst_and_assignee(
y_task: dict[str, Any],
initiator_department: str | None,
y_status_id: int,
g_contractor_id: str | None,
current_y_assignee: str | None,
g_initiator_id: str,
db_session: db.Session,
) -> tuple[str | None, str | None]:
"""
Update the analyst and assignee based on the initiator's department and conditions.
Returns:
Tuple of (new_analyst_id, new_assignee_id) that should be updated.
"""
y_initiator = db.get_user_by_gandiva_id(
session=db_session, g_user_id=g_initiator_id)
cur_y_analyst = y_task.get(yc.fid_analyst, {}).get('id')
y_initiator_id = str(y_initiator.yandex_user_id) if y_initiator else None
new_analyst_id: str | None = None
new_y_contractor_id: str | None = None
if not y_initiator_id:
return new_analyst_id, new_y_contractor_id
if not db.is_user_analyst(session=db_session, yandex_user_id=y_initiator_id):
new_analyst_id = assign_new_analyst(
db_session, initiator_department, cur_y_analyst, g_contractor_id
)
new_statuses_id = [0, 1, 2]
if new_analyst_id and y_status_id in new_statuses_id and current_y_assignee != new_analyst_id:
new_y_contractor_id = new_analyst_id
else:
if cur_y_analyst != y_initiator_id:
new_analyst_id = y_initiator_id
return new_analyst_id, new_y_contractor_id
def assign_new_analyst(
db_session: db.Session,
initiator_department: str | None,
current_y_analyst_id: str | None,
g_contractor_id: str | None
) -> str | None:
"""Determine the new analyst ID based on the initiator's department and current conditions."""
if initiator_department:
analyst = db.get_user_id_by_department(
session=db_session, department_name=initiator_department
)
if not analyst:
return
if utils.EXCEL_UPDATED_IN_YANDEX_DISK:
content_is_different = current_y_analyst_id != analyst
if content_is_different:
return analyst
if (
not current_y_analyst_id
and g_contractor_id in [None, gapi.gc.waiting_analyst_id]
):
return analyst
return
def create_y_tasks_dict(
y_tasks: list[dict[str, Any]],
use_summaries: bool
) -> dict[str, dict[str, Any]]:
"""
Creates a dictionary to map Yandex task unique IDs to their corresponding task objects.
If `use_summaries` is True, it maps based on task IDs scraped from summaries.
If `use_summaries` is False, it maps based on gandiva task id field.
:param y_tasks: List of Yandex task objects.
:param use_summaries: Whether to use task summaries to map task IDs.
:return: Dictionary with task IDs as keys and Yandex task objects as values.
"""
y_tasks_dict: dict[str, dict[str, Any]] = {}
fid: str = yc.fid_gandiva_task_id
if not use_summaries:
y_tasks_dict = {yt[fid]: yt for yt in y_tasks if yt.get(fid)}
return y_tasks_dict
for task in y_tasks:
summary: str = task.get('summary', '')
match = re.match(r'^(\d+)', summary)
if match:
task_id: str = match.group(1) # Get the matched task ID
y_tasks_dict[task_id] = task # Map task_id to task object
return y_tasks_dict
async def edit_tasks(
g_tasks: list[dict[str, Any]],
y_tasks: list[dict[str, Any]],
to_get_followers: bool,
use_summaries: bool = False,
edit_descriptions: bool = True) -> None:
"""
Edits tasks in Yandex Tracker based on the data from Gandiva.
Only updates tasks that are outdated.
"""
logging.info(f"Editing tasks...")
y_tasks_dict: dict[str, dict[str, Any]] = create_y_tasks_dict(
y_tasks=y_tasks, use_summaries=use_summaries)
edited_task_count: int = 0
for g_task in g_tasks:
g_task_id: str = str(g_task['Id'])
y_task: dict[str, Any] | None = y_tasks_dict.get(g_task_id)
if not y_task:
continue
fields: dict[str, Any] | None = await g_to_y_fields(g_task, edit=True, to_get_followers=to_get_followers)
if not isinstance(fields, dict):
logging.error("Fields is None, dict expected!")
return
initiator_name: str | None = fields.get('initiator_name')
if not initiator_name:
logging.error("Initiator name is None, str expected!")
continue
initiator_id: str | None = fields.get('initiator_id')
if not initiator_id:
logging.error("Initiator ID is None, str expected!")
continue
initiator_department: str | None = fields.get('initiator_department')
description: str | None = fields.get('description')
y_start_date: str | None = fields.get('yandex_start_date')
y_assignee_id: str | None = fields.get('assignee_id_yandex')
followers: list[str] | None = fields.get('followers')
nd: str | None = fields.get('nd')
y_date_created_in_g: str | None = fields.get('date_created_in_g')
g_status: str = str(g_task['Status'])
y_status: str | None = utils.g_to_y_status(g_status)
if not y_status:
continue
y_step = utils.y_status_to_id(y_status)
if y_step is None:
logging.error(f"Invalid Yandex task status: {y_status}")
continue