Много изменений в бд

This commit is contained in:
2025-05-30 12:19:25 +03:00
parent 21b202f090
commit f21acb23ab
6 changed files with 173 additions and 65 deletions

View File

@@ -5,7 +5,7 @@ from colorama import Fore
import requests
from tqdm import tqdm
from config import ClockifyConfig, config
from config import ClockifyConfig, config, db
from classes import Activity, Tag, VetroProject
from exceptions import InvalidToken
from utils import parse_task_id, time_to_hour
@@ -51,6 +51,9 @@ class ClockifyAPI(ClockifyConfig):
except ValueError:
logger.info(f'{activity["timeInterval"]["start"]}: {activity["description"]} - Неправильный формат тега {tag}')
continue
author = db.get_user_by("clockify_user_id", activity["userId"])
result.append(
Activity(
id=activity["id"],
@@ -62,7 +65,8 @@ class ClockifyAPI(ClockifyConfig):
time_spent=time_to_hour((end if end else datetime.utcnow()) - start),
date_start=start,
date_end=end,
is_tracked=activity["billable"]
is_tracked=activity["billable"],
author_id=author["id"]
)
)
logger.info(f"Сохранено задач: {len(result)}")
@@ -135,16 +139,27 @@ class ClockifyAPI(ClockifyConfig):
resp = resp.json()
logger.debug({"id": resp["id"], "email": resp["email"], "name": resp["name"]})
return token
def getenvs(self):
"""Получает нужные USER_ID и WORKSPACE_ID с сервера Clockify"""
def get_user(self):
"""Получает нужные данные пользователя с сервера Clockify"""
resp = requests.get(self.base_url + self.user_url, headers={"X-API-KEY": self.token})
if not resp.ok:
logger.error(resp.json())
raise requests.exceptions.RequestException(Fore.RED + "Ошибка запроса." + Fore.RESET)
json = resp.json()
return {
"id": json['id'],
"workspace_id": json['activeWorkspace'],
"email": json["email"],
"username": json["name"]
}
def getenvs(self):
"""Получает нужные USER_ID и WORKSPACE_ID с сервера Clockify"""
user = self.get_user()
with open(config.ENV_TXT, "w") as file:
try:
file.write(f"USER_ID={resp.json()['id']}\nWORKSPACE_ID={resp.json()['activeWorkspace']}")
file.write(f"USER_ID={user['id']}\nWORKSPACE_ID={user['workspace_id']}")
logger.info(f"{Fore.GREEN}Необходимые переменные были сохранены в файл {config.ENV_TXT}{Fore.RESET}")
except Exception as e:
logger.error(f"{Fore.RED}Не удалось сохранить необходимые переменные.{Fore.RESET}")

View File

@@ -23,7 +23,8 @@ class RedmineAPI(RedmineConfig):
"""
def __init__(self, token):
super().__init__()
self.token = self._check_token(token)
self.token = token
self._check_token()
def track_activities(self, activities: list[Activity]) -> list[Activity]:
"""Заносит трудочасы на сервер Redmine"""
@@ -75,12 +76,21 @@ class RedmineAPI(RedmineConfig):
if act.get("active")
]
def _check_token(self, token):
"""Проверяет токен"""
resp = requests.get(self.base_url + self.my_account_url, headers={"X-Redmine-Api-Key": token})
def get_user(self):
"""Проверяет токен и возвращает данные юзера"""
resp = requests.get(self.base_url + self.my_account_url, headers={"X-Redmine-Api-Key": self.token})
if not resp.ok:
logger.error("Invalid Token for RedmineAPI")
raise InvalidToken
resp = resp.json()['user']
logger.debug({"login": resp["login"], "email": resp["mail"], "full_name": f'{resp["firstname"]} {resp["lastname"]}'})
return token
json = resp.json()["user"]
return {
"id": json["id"],
"first_name": json["firstname"],
"last_name": json["lastname"],
"email": json["mail"],
"username": json["login"]
}
def _check_token(self):
user = self.get_user()
logging.debug(user)