Убрал лишние поля у класса. Выделил важные сообщения разными цветами

This commit is contained in:
2025-05-22 16:57:03 +03:00
parent 409c0651d5
commit eb69a29486
5 changed files with 27 additions and 24 deletions

View File

@@ -42,7 +42,7 @@ class ClockifyAPI(ClockifyConfig):
time_worked_out_total += time_to_hour((end if end else datetime.utcnow()) - start) time_worked_out_total += time_to_hour((end if end else datetime.utcnow()) - start)
tag = [tag for tag in self.get_tags() if tag.id == tag_id][0] tag = [tag for tag in self.get_tags() if tag.id == tag_id][0]
try: try:
task_id, task_title = tag.title.split(" - ") task_id, _ = tag.title.split(" - ")
except ValueError: except ValueError:
logger.info(f'{activity["timeInterval"]["start"]}: {activity["description"]} - Неправильный формат тега {tag}') logger.info(f'{activity["timeInterval"]["start"]}: {activity["description"]} - Неправильный формат тега {tag}')
continue continue
@@ -51,10 +51,8 @@ class ClockifyAPI(ClockifyConfig):
id=activity["id"], id=activity["id"],
tag_id=tag_id, tag_id=tag_id,
task_id=task_id, task_id=task_id,
task_title=task_title,
project_id=activity["projectId"], project_id=activity["projectId"],
vetro_project_id=activity["taskId"], vetro_project_id=activity["taskId"],
vetro_project_title=config.VETRO_PROJECTS.get(activity.get("taskId")),
description=activity["description"], description=activity["description"],
time_spent=time_to_hour((end if end else datetime.utcnow()) - start), time_spent=time_to_hour((end if end else datetime.utcnow()) - start),
date_start=start, date_start=start,
@@ -109,10 +107,10 @@ class ClockifyAPI(ClockifyConfig):
) )
if resp.ok: if resp.ok:
logger.debug(resp.json()) logger.debug(resp.json())
logger.info(f"{activity} {Fore.GREEN} помечена как затреканная{Fore.RESET}") logger.info(f"{Fore.GREEN} {activity} помечена как затреканная{Fore.RESET}")
else: else:
logger.debug(resp.json()) logger.debug(resp.json())
logger.error(f"{activity} {Fore.RED} не помечена как затреканная{Fore.RESET}") logger.error(f"{Fore.RED} {activity} не помечена как затреканная{Fore.RESET}")
except Exception as e: except Exception as e:
logger.error(e) logger.error(e)
return return

View File

@@ -1,5 +1,6 @@
import logging import logging
from colorama import Fore
import requests import requests
from tqdm import tqdm from tqdm import tqdm
@@ -46,7 +47,7 @@ class RedmineAPI(RedmineConfig):
tracked.append(activity) tracked.append(activity)
logger.debug(activity) logger.debug(activity)
else: else:
logger.error(f"{activity} Не была затрекана") logger.error(Fore.RED + f"{activity} Не была затрекана" + Fore.RED)
logger.error(f"{resp.json()['errors']} {resp.status_code}") logger.error(f"{resp.json()['errors']} {resp.status_code}")
except Exception as e: except Exception as e:
logger.error(e) logger.error(e)

View File

@@ -8,9 +8,7 @@ from enums import ClockifyProjects, VetroProjects
class Activity: class Activity:
id: str id: str
vetro_project_id: VetroProjects vetro_project_id: VetroProjects
vetro_project_title: str
task_id: int task_id: int
task_title: str
tag_id: str tag_id: str
description: str description: str
project_id: ClockifyProjects project_id: ClockifyProjects
@@ -20,7 +18,7 @@ class Activity:
is_tracked: bool = False is_tracked: bool = False
def __str__(self): def __str__(self):
return f'{self.date_start + timedelta(hours=3)}|{self.vetro_project_title}|{self.description} для задачи "{self.task_title}"' return f'{self.date_start + timedelta(hours=3)}|{self.description} для задачи #{self.task_id}'
@dataclass @dataclass

View File

@@ -48,8 +48,8 @@ class Database:
) )
) )
self.con.commit() self.con.commit()
except Exception as e: except Exception:
logger.debug(e) pass
if not is_updated: if not is_updated:
logging.info("База данных устарела. Рекомендуем обновить с помощью флага -i [--init-db]") logging.info("База данных устарела. Рекомендуем обновить с помощью флага -i [--init-db]")
@@ -72,8 +72,8 @@ class Database:
) )
) )
self.con.commit() self.con.commit()
except Exception as e: except Exception:
logger.debug(e) pass
def insert_tags(self, tags: list[Tag]): def insert_tags(self, tags: list[Tag]):
@@ -82,8 +82,8 @@ class Database:
try: try:
cur.execute("INSERT INTO tags VALUES(?, ?)",(tag.id,tag.title)) cur.execute("INSERT INTO tags VALUES(?, ?)",(tag.id,tag.title))
self.con.commit() self.con.commit()
except Exception as e: except Exception:
logger.debug(e) pass
def insert_vetro_projects(self, vetro_projects: list[VetroProject]): def insert_vetro_projects(self, vetro_projects: list[VetroProject]):
@@ -92,8 +92,8 @@ class Database:
try: try:
cur.execute("INSERT INTO vetro_projects VALUES(?, ?)", (vetro_project.id, vetro_project.title)) cur.execute("INSERT INTO vetro_projects VALUES(?, ?)", (vetro_project.id, vetro_project.title))
self.con.commit() self.con.commit()
except Exception as e: except Exception:
logger.debug(e) pass
def insert_activity_types(self, activity_types: list[ActivityType]): def insert_activity_types(self, activity_types: list[ActivityType]):
cur = self.con.cursor() cur = self.con.cursor()
@@ -101,5 +101,5 @@ class Database:
try: try:
cur.execute("INSERT INTO activity_types VALUES(?, ?)", (activity_type.id, activity_type.title)) cur.execute("INSERT INTO activity_types VALUES(?, ?)", (activity_type.id, activity_type.title))
self.con.commit() self.con.commit()
except Exception as e: except Exception:
logger.debug(e) pass

View File

@@ -11,6 +11,8 @@ logging.basicConfig(
) )
from colorama import Fore # noqa: E402
from api import ClockifyAPI, RedmineAPI # noqa: E402 from api import ClockifyAPI, RedmineAPI # noqa: E402
from config import arg_parser, config, db # noqa: E402 from config import arg_parser, config, db # noqa: E402
from utils import format_date, str_to_date, today_start, today_end # noqa: E402 from utils import format_date, str_to_date, today_start, today_end # noqa: E402
@@ -48,10 +50,15 @@ def main():
red = RedmineAPI(config.REDMINE_TOKEN) red = RedmineAPI(config.REDMINE_TOKEN)
if args.init_db: if args.init_db:
logger.info("Обновление базы данных...") logger.info(Fore.YELLOW + "Обновление базы данных..." + Fore.RESET)
db.insert_tags(clock.get_tags()) try:
db.insert_vetro_projects(clock.get_vetro_projects()) db.insert_tags(clock.get_tags())
db.insert_activity_types(red.get_time_entry_activities()) db.insert_vetro_projects(clock.get_vetro_projects())
db.insert_activity_types(red.get_time_entry_activities())
except Exception as e:
logger.error(Fore.RED + f"Ошибка при обновлении базы данных: {e}" + Fore.RESET)
else:
logger.info(Fore.GREEN + "База данных теперь актуальна." + Fore.RESET)
activities = clock.get_activities( activities = clock.get_activities(
**{ **{
@@ -71,6 +78,5 @@ def main():
except Exception as e: except Exception as e:
logger.error(e) logger.error(e)
if __name__ == "__main__": if __name__ == "__main__":
main() main()