123
This commit is contained in:
121
api.py
121
api.py
@@ -1,49 +1,136 @@
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
import logging
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
|
|
||||||
from config import ClockifyConfig, config
|
from config import ClockifyConfig, RedmineConfig, config
|
||||||
|
from classes import Activity, Tag
|
||||||
|
from enums import ActivityType
|
||||||
from exceptions import InvalidToken
|
from exceptions import InvalidToken
|
||||||
from utils import time_to_hour
|
from utils import time_to_hour
|
||||||
|
|
||||||
|
|
||||||
class ClockifyAPI(ClockifyConfig):
|
WORKSPACE_ID = config.CLOCKIFY_WORKSPACE_ID
|
||||||
def __init__(self, token):
|
USER_ID = config.CLOCKIFY_USER_ID
|
||||||
self._check_token(token)
|
|
||||||
self.token = token
|
|
||||||
|
|
||||||
def get_activities(self, **kwargs):
|
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"time_entry": {
|
||||||
|
"issue_id": 28882,
|
||||||
|
"hours": 0.55,
|
||||||
|
"activity_id": 9,
|
||||||
|
"comments": "Дейлик"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class ClockifyAPI(ClockifyConfig):
|
||||||
|
def __init__(self, token: str):
|
||||||
|
self.token = self._check_token(token)
|
||||||
|
|
||||||
|
def get_activities(self, **kwargs) -> list[Activity]:
|
||||||
"""
|
"""
|
||||||
start: datetime - Начальная дата (обязательно)
|
start: datetime - Начальная дата (обязательно)
|
||||||
end: datetime - Конечная дата (обязательно)
|
end: datetime - Конечная дата (обязательно)
|
||||||
page: int - Номер страницы
|
page: int - Номер страницы
|
||||||
page-size: int - Размер страницы (по умолчанию 50)
|
page-size: int - Размер страницы (по умолчанию 50)
|
||||||
"""
|
"""
|
||||||
activities = requests.get(self.base_url + self.time_entries.format(**kwargs), params=kwargs, headers={"X-API-KEY": self.token}).json()
|
time_entries_url = self.time_entries_url.format(workspace_id=WORKSPACE_ID, user_id=USER_ID)
|
||||||
|
activities = requests.get(self.base_url + time_entries_url, params=kwargs, headers={"X-API-KEY": self.token}).json()
|
||||||
|
logging.info(f"Получено задач: {len(activities)}")
|
||||||
time_worked_out_total = 0
|
time_worked_out_total = 0
|
||||||
|
|
||||||
|
result = []
|
||||||
for activity in tqdm(activities, desc="Парсинг задач"):
|
for activity in tqdm(activities, desc="Парсинг задач"):
|
||||||
for tag in activity["tagIds"]:
|
for tag_id in activity["tagIds"]:
|
||||||
start = datetime.strptime(activity["timeInterval"]["start"], config.DATETIME_FORMAT)
|
start = datetime.strptime(activity["timeInterval"]["start"], config.DATETIME_FORMAT)
|
||||||
end = datetime.strptime(activity["timeInterval"]["end"] or str(datetime.now(timezone.utc).strftime(config.DATETIME_FORMAT)), config.DATETIME_FORMAT)
|
end = datetime.strptime(activity["timeInterval"]["end"] or str(datetime.now(timezone.utc).strftime(config.DATETIME_FORMAT)), config.DATETIME_FORMAT)
|
||||||
time_worked_out_total += time_to_hour(end - start)
|
time_worked_out_total += time_to_hour(end - start)
|
||||||
|
tag = [tag for tag in self.get_tags(workspace_id=WORKSPACE_ID) if tag.id == tag_id][0]
|
||||||
print(f"Получено задач: {len(activities)}")
|
task_id, task_title = tag.title.split(" - ")
|
||||||
print(f"Отработано часов: {time_worked_out_total}")
|
result.append(
|
||||||
return activities
|
Activity(
|
||||||
|
task_id=task_id,
|
||||||
|
task_title=task_title,
|
||||||
|
description=activity["description"],
|
||||||
|
time_spent=time_to_hour(end - start),
|
||||||
|
date=end
|
||||||
|
)
|
||||||
|
)
|
||||||
|
logging.info(f"Сохранено задач: {len(result)}")
|
||||||
|
logging.info(f"Отработано часов: {time_worked_out_total}")
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
def get_tags(self, **kwargs):
|
def get_tags(self, **kwargs) -> list[Tag]:
|
||||||
"""
|
"""
|
||||||
workspace_id: str - required
|
workspace_id: str - required
|
||||||
name: str - optional
|
name: str - optional
|
||||||
archived: bool - optional
|
archived: bool - optional
|
||||||
"""
|
"""
|
||||||
tags = requests.get(self.base_url + self.tags.format(**kwargs), params=kwargs, headers={"X-API-KEY": self.token}).json()
|
tags = requests.get(self.base_url + self.tags_url.format(**kwargs), params=kwargs, headers={"X-API-KEY": self.token}).json()
|
||||||
return {tag["id"]: tag["name"] for tag in tags}
|
return [Tag(
|
||||||
|
id=tag["id"],
|
||||||
|
title=tag["name"]
|
||||||
|
) for tag in tags]
|
||||||
|
|
||||||
|
def _check_token(self, token: str) -> str:
|
||||||
|
resp = requests.get(self.base_url + self.config.user_url, headers={"X-API-KEY": token})
|
||||||
|
if not resp.ok:
|
||||||
|
logging.error(resp.json())
|
||||||
|
raise InvalidToken
|
||||||
|
resp = resp.json()
|
||||||
|
logging.debug({"id": resp["id"], "email": resp["email"], "name": resp["name"]})
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
class RedmineAPI(RedmineConfig):
|
||||||
|
def __init__(self, token):
|
||||||
|
self.token = self._check_token(token)
|
||||||
|
|
||||||
|
def track_activities(self, activities: list[Activity]):
|
||||||
|
if len(activities) == 0:
|
||||||
|
logging.info("Нет задач для занесения трудочасов")
|
||||||
|
return
|
||||||
|
tracked = 0
|
||||||
|
for activity in tqdm(activities, desc="Занесение трудочасов"):
|
||||||
|
if not activity.is_tracked:
|
||||||
|
try:
|
||||||
|
resp = requests.post(
|
||||||
|
self.base_url + self.time_entries_url,
|
||||||
|
headers={"X-Redmine-Api-Key": self.token},
|
||||||
|
data={
|
||||||
|
"time_entry": {
|
||||||
|
"issue_id": activity.task_id,
|
||||||
|
"hours": activity.time_spent,
|
||||||
|
"activity_id": ActivityType.DEVELOPMENT,
|
||||||
|
"comments": activity.description,
|
||||||
|
"spent_on": activity.date.strftime(self.datetime_format)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if resp.ok:
|
||||||
|
activity.is_tracked = True
|
||||||
|
tracked += 1
|
||||||
|
logging.debug(activity)
|
||||||
|
else:
|
||||||
|
logging.error(activity, "Не была затрекана")
|
||||||
|
logging.error(resp.json(), resp)
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(e)
|
||||||
|
continue
|
||||||
|
if len(activities) == tracked:
|
||||||
|
logging.info(f"Все задачи были успешно занесены в Redmine: {tracked}")
|
||||||
|
|
||||||
|
|
||||||
def _check_token(self, token):
|
def _check_token(self, token):
|
||||||
resp = requests.get(self.base_url + self.user_url, headers={"X-API-KEY": token})
|
resp = requests.get(self.base_url + self.my_account_url, headers={"X-Redmine-Api-Key": token})
|
||||||
print(resp)
|
|
||||||
if not resp.ok:
|
if not resp.ok:
|
||||||
|
logging.error("Invalid Token for RedmineAPI")
|
||||||
raise InvalidToken
|
raise InvalidToken
|
||||||
|
resp = resp.json()['user']
|
||||||
|
logging.debug({"login": resp["login"], "email": resp["mail"], "full_name": f"{resp["firstname"]} {resp["lastname"]}"})
|
||||||
|
return token
|
||||||
|
|||||||
27
classes.py
Normal file
27
classes.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Activity:
|
||||||
|
task_id: int
|
||||||
|
task_title: str
|
||||||
|
description: str
|
||||||
|
time_spent: float
|
||||||
|
date: datetime = datetime.now()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_tracked(self):
|
||||||
|
return self.description.startswith("*")
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return f'{self.date}: {self.description.strip("*")} для задачи "{self.task_title}"' + (" - ЗАТРЕКАНА" if self.is_tracked else "")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Tag:
|
||||||
|
id: str
|
||||||
|
title: str
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.title
|
||||||
25
config.py
25
config.py
@@ -11,14 +11,25 @@ class Config(BaseSettings):
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
class RedmineConfig(BaseSettings):
|
class RedmineConfig:
|
||||||
BASE_API_URL: str = "https://redmine.sbps.ru"
|
@property
|
||||||
|
def base_url(self):
|
||||||
|
return "https://redmine.sbps.ru"
|
||||||
|
|
||||||
TIME_ENTRIES: str = "/time_entries.json"
|
@property
|
||||||
|
def time_entries_url(self):
|
||||||
|
return "/time_entries.json"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def my_account_url(self):
|
||||||
|
return "/my/account.json"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def datetime_format(self):
|
||||||
|
return "%Y-%m-%d"
|
||||||
|
|
||||||
|
|
||||||
class ClockifyConfig(BaseSettings):
|
class ClockifyConfig:
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def base_url(self):
|
def base_url(self):
|
||||||
return "https://api.clockify.me/api/v1"
|
return "https://api.clockify.me/api/v1"
|
||||||
@@ -35,5 +46,9 @@ class ClockifyConfig(BaseSettings):
|
|||||||
def user_url(self):
|
def user_url(self):
|
||||||
return "/user"
|
return "/user"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def datetime_format(self):
|
||||||
|
return "%Y-%m-%dT%H:%M:%SZ"
|
||||||
|
|
||||||
|
|
||||||
config = Config()
|
config = Config()
|
||||||
|
|||||||
9
enums.py
Normal file
9
enums.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
|
||||||
|
class ActivityType(Enum):
|
||||||
|
DEVELOPMENT = 9
|
||||||
|
BUSINESS_ANALYZE = 8
|
||||||
|
CODE_REVIEW = 57
|
||||||
|
CONSULTATIONS = 58
|
||||||
|
SUPPORT = 60
|
||||||
24
main.py
24
main.py
@@ -1,11 +1,31 @@
|
|||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
from api import ClockifyAPI
|
from api import ClockifyAPI, RedmineAPI
|
||||||
from config import config
|
from config import config
|
||||||
|
from utils import today_start, today_end
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
ClockifyAPI(config.CLOCKIFY_TOKEN)
|
clock = ClockifyAPI(config.CLOCKIFY_TOKEN)
|
||||||
|
for activity in clock.get_activities(
|
||||||
|
start=today_start(),
|
||||||
|
end=today_end()
|
||||||
|
):
|
||||||
|
print(activity)
|
||||||
|
# red = RedmineAPI(config.REDMINE_TOKEN)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format=('%(asctime)s, '
|
||||||
|
'%(levelname)s, '
|
||||||
|
'%(funcName)s, '
|
||||||
|
'%(message)s'
|
||||||
|
),
|
||||||
|
encoding='UTF-8',
|
||||||
|
handlers=[logging.FileHandler(__file__ + '.log'),
|
||||||
|
logging.StreamHandler(sys.stdout)]
|
||||||
|
)
|
||||||
main()
|
main()
|
||||||
|
|||||||
2
utils.py
2
utils.py
@@ -1,6 +1,6 @@
|
|||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
import config
|
from config import config
|
||||||
|
|
||||||
def time_to_hour(time: timedelta) -> float:
|
def time_to_hour(time: timedelta) -> float:
|
||||||
return time.total_seconds() / 3600
|
return time.total_seconds() / 3600
|
||||||
|
|||||||
Reference in New Issue
Block a user