From c919d19ad2b860633557c9a935db2627159889d3 Mon Sep 17 00:00:00 2001 From: Mirko Stamm Date: Tue, 20 Oct 2026 14:44:59 +0100 Subject: [PATCH] feat(notifications): human-readable assigned_task messages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace raw database ids in assignment notifications with a natural sentence carrying the task title, the project name and the actor: Fuiste asignado a la tarea «{task_title}» en el proyecto «{project_title}» por {actor_username}. - Both assignment sites (task create and reassignment) build the message at the source, since the offline persistence path stores only the message string. - Thread the authenticated actor from the router into TaskService.create; the update path resolves the username from the actor id it already receives. - Do not notify the actor about their own assignment. - Fill related_entity_id (task id) so online clients can deep-link later. - Name resolution is best-effort: any lookup failure falls back to the previous id-based message and never fails the task mutation. - Contract unchanged: notification_type stays assigned_task, no DB migration. --- api/v1/routers/task.py | 6 +- core/event_ws.py | 8 +- repositories/project_repositories.py | 7 + services/project_services.py | 13 ++ services/task_services.py | 74 ++++++++- .../test_notification_messages.py | 157 ++++++++++++++++++ 6 files changed, 257 insertions(+), 8 deletions(-) create mode 100644 test/test_services/test_notification_messages.py diff --git a/api/v1/routers/task.py b/api/v1/routers/task.py index 6948495..eb8d351 100644 --- a/api/v1/routers/task.py +++ b/api/v1/routers/task.py @@ -99,7 +99,11 @@ async def create_task( auth_data: dict = Depends(require_permission(permissions=["admin"])), task_serv: TaskService = Depends(get_task_service), ): - return await task_serv.create(new_task, project_id) + user = auth_data["user"] + + return await task_serv.create( + new_task, project_id, actor_user_id=user.user_id, actor_username=user.username + ) @router.patch( diff --git a/core/event_ws.py b/core/event_ws.py index 490c827..3bff33a 100644 --- a/core/event_ws.py +++ b/core/event_ws.py @@ -5,10 +5,14 @@ ) -def format_notification(notification_type: str, message: str): +def format_notification( + notification_type: str, message: str, related_entity_id: int | None = None +): # Crea la notificacion outgoin_payload = OutgoingNotificationPayload( - notification_type=notification_type, message=message + notification_type=notification_type, + message=message, + related_entity_id=related_entity_id, ).model_dump() # Crea el evento diff --git a/repositories/project_repositories.py b/repositories/project_repositories.py index 778aa2a..8959416 100644 --- a/repositories/project_repositories.py +++ b/repositories/project_repositories.py @@ -26,6 +26,13 @@ def get_project_by_id(self, group_id: int, project_id: int): except SQLAlchemyError as e: raise DatabaseError(e, "get_project_by_id") + def get_project_by_project_id(self, project_id: int): + try: + stmt = select(Project).where(Project.project_id == project_id) + return self.session.exec(stmt).first() + except SQLAlchemyError as e: + raise DatabaseError(e, "get_project_by_project_id") + def get_user_in_project(self, project_id: int, user_id: int): try: stmt = select(project_user).where( diff --git a/services/project_services.py b/services/project_services.py index 3019794..029199e 100644 --- a/services/project_services.py +++ b/services/project_services.py @@ -41,6 +41,19 @@ def found_project_or_404(self, group_id: int, project_id: int): return founded_project + def get_project_title_or_none(self, project_id: int) -> str | None: + """Best-effort project title lookup. + + Returns None instead of raising so notification building never fails a + task mutation when the project cannot be resolved. + """ + try: + project = self.project_repo.get_project_by_project_id(project_id) + except Exception: + return None + + return project.title if project else None + def found_user_in_project_or_404(self, user_id: int, project_id: int): user = self.project_repo.get_user_in_project(project_id, user_id) diff --git a/services/task_services.py b/services/task_services.py index 5a4a52e..5c1f755 100644 --- a/services/task_services.py +++ b/services/task_services.py @@ -69,7 +69,49 @@ async def get_all_task_for_project( except DatabaseError: raise - async def create(self, task: CreateTask, project_id: int): + def _resolve_username(self, user_id: int | None) -> str | None: + """Best-effort username lookup for notification text (never raises).""" + if not user_id: + return None + try: + return self.user_ser.get_user_or_404(user_id).username + except Exception: + return None + + def _build_assigned_task_message( + self, + task_title: str | None, + project_id: int, + project_title: str | None, + actor_username: str | None, + task_id: int, + ) -> str: + """Build the human-readable assignment message, with a safe fallback. + + A notification is best-effort: if names cannot be resolved we fall back + to the id-based text instead of failing the task mutation. + """ + try: + if not task_title or not project_title: + return f"You were assigned to the task {task_id} in the project {project_id}" + + message = ( + f"Fuiste asignado a la tarea «{task_title}» " + f"en el proyecto «{project_title}»" + ) + if actor_username: + message += f" por {actor_username}" + return f"{message}." + except Exception: + return f"You were assigned to the task {task_id} in the project {project_id}" + + async def create( + self, + task: CreateTask, + project_id: int, + actor_user_id: int | None = None, + actor_username: str | None = None, + ): try: if task.assigned_user_id: self.user_ser.get_user_or_404(task.assigned_user_id) @@ -82,10 +124,21 @@ async def create(self, task: CreateTask, project_id: int): logger.info("task_created", project_id=project_id, task_id=new_task.task_id) - if task.assigned_user_id: + # Do not notify the actor about their own assignment. + if task.assigned_user_id and task.assigned_user_id != actor_user_id: + project_title = self.proj_ser.get_project_title_or_none(project_id) + message = self._build_assigned_task_message( + task_title=new_task.title, + project_id=project_id, + project_title=project_title, + actor_username=actor_username, + task_id=new_task.task_id, + ) + outgoing_event_json = format_notification( notification_type="assigned_task", - message=f"You are assigned to the task {new_task.task_id} in project {project_id}", + message=message, + related_entity_id=new_task.task_id, ) # Envia el evento @@ -212,10 +265,21 @@ async def update_task( task = self.task_repo.get_task_by_id(task_id, project_id) - if update_task.assigned_user_id: + # Do not notify the actor about their own assignment. + if update_task.assigned_user_id and update_task.assigned_user_id != user_id: + project_title = self.proj_ser.get_project_title_or_none(project_id) + message = self._build_assigned_task_message( + task_title=task.title, + project_id=project_id, + project_title=project_title, + actor_username=self._resolve_username(user_id), + task_id=task_id, + ) + outgoing_event_json = format_notification( notification_type="assigned_task", - message=f"You were assigned to the task {task_id} in the project {project_id}", + message=message, + related_entity_id=task_id, ) await manager.send_to_user( message=outgoing_event_json, user_id=update_task.assigned_user_id diff --git a/test/test_services/test_notification_messages.py b/test/test_services/test_notification_messages.py new file mode 100644 index 0000000..20ccc2d --- /dev/null +++ b/test/test_services/test_notification_messages.py @@ -0,0 +1,157 @@ +import json + +import pytest + +from models.schemas import CreateTask, UpdateTask +from services.task_services import TaskService + + +def _build_service(mocker): + task_repo = mocker.Mock() + user_ser = mocker.Mock() + proj_ser = mocker.Mock() + service = TaskService(task_repo, user_ser, proj_ser) + return service, task_repo, user_ser, proj_ser + + +def _captured_message(send_to_user_mock, call_index=-1): + raw = send_to_user_mock.call_args_list[call_index].kwargs["message"] + return json.loads(raw)["payload"]["message"] + + +def _captured_event(send_to_user_mock, call_index=-1): + raw = send_to_user_mock.call_args_list[call_index].kwargs["message"] + return json.loads(raw) + + +@pytest.mark.asyncio +async def test_create_assigned_notification_is_human_readable(mocker): + service, task_repo, user_ser, proj_ser = _build_service(mocker) + send = mocker.patch( + "services.task_services.manager.send_to_user", new_callable=mocker.AsyncMock + ) + + new_task = mocker.Mock() + new_task.task_id = 9 + new_task.title = "Fix login" + task_repo.create.return_value = new_task + proj_ser.get_project_title_or_none.return_value = "Tasks API" + + payload = CreateTask(title="Fix login", assigned_user_id=2) + + await service.create( + payload, project_id=3, actor_user_id=1, actor_username="mirko" + ) + + assert _captured_message(send) == ( + "Fuiste asignado a la tarea «Fix login» en el proyecto «Tasks API» por mirko." + ) + assert _captured_event(send)["payload"]["related_entity_id"] == 9 + + +@pytest.mark.asyncio +async def test_create_self_assignment_sends_no_notification(mocker): + service, task_repo, user_ser, proj_ser = _build_service(mocker) + send = mocker.patch( + "services.task_services.manager.send_to_user", new_callable=mocker.AsyncMock + ) + + new_task = mocker.Mock() + new_task.task_id = 9 + new_task.title = "Fix login" + task_repo.create.return_value = new_task + + payload = CreateTask(title="Fix login", assigned_user_id=1) + + await service.create(payload, project_id=3, actor_user_id=1, actor_username="mirko") + + send.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_create_falls_back_to_id_message_when_title_missing(mocker): + service, task_repo, user_ser, proj_ser = _build_service(mocker) + send = mocker.patch( + "services.task_services.manager.send_to_user", new_callable=mocker.AsyncMock + ) + + new_task = mocker.Mock() + new_task.task_id = 9 + new_task.title = "Fix login" + task_repo.create.return_value = new_task + proj_ser.get_project_title_or_none.return_value = None + + payload = CreateTask(title="Fix login", assigned_user_id=2) + + await service.create(payload, project_id=3, actor_user_id=1, actor_username="mirko") + + assert _captured_message(send) == ( + "You were assigned to the task 9 in the project 3" + ) + + +@pytest.mark.asyncio +async def test_assigned_notification_omits_actor_when_unavailable(mocker): + service, task_repo, user_ser, proj_ser = _build_service(mocker) + send = mocker.patch( + "services.task_services.manager.send_to_user", new_callable=mocker.AsyncMock + ) + + new_task = mocker.Mock() + new_task.task_id = 9 + new_task.title = "Fix login" + task_repo.create.return_value = new_task + proj_ser.get_project_title_or_none.return_value = "Tasks API" + + payload = CreateTask(title="Fix login", assigned_user_id=2) + + await service.create(payload, project_id=3, actor_user_id=1, actor_username=None) + + assert _captured_message(send) == ( + "Fuiste asignado a la tarea «Fix login» en el proyecto «Tasks API»." + ) + + +@pytest.mark.asyncio +async def test_update_reassignment_notification_is_human_readable(mocker): + service, task_repo, user_ser, proj_ser = _build_service(mocker) + send = mocker.patch( + "services.task_services.manager.send_to_user", new_callable=mocker.AsyncMock + ) + + task = mocker.Mock() + task.title = "Fix login" + task_repo.get_task_by_id.return_value = task + proj_ser.get_project_title_or_none.return_value = "Tasks API" + user_ser.get_user_or_404.return_value = mocker.Mock(username="mirko") + + payload = UpdateTask(assigned_user_id=2) + + await service.update_task( + task_id=9, project_id=3, update_task=payload, permission="admin", user_id=1 + ) + + assert _captured_message(send) == ( + "Fuiste asignado a la tarea «Fix login» en el proyecto «Tasks API» por mirko." + ) + assert _captured_event(send)["payload"]["related_entity_id"] == 9 + + +@pytest.mark.asyncio +async def test_update_self_assignment_sends_no_notification(mocker): + service, task_repo, user_ser, proj_ser = _build_service(mocker) + send = mocker.patch( + "services.task_services.manager.send_to_user", new_callable=mocker.AsyncMock + ) + + task = mocker.Mock() + task.title = "Fix login" + task_repo.get_task_by_id.return_value = task + + payload = UpdateTask(assigned_user_id=1) + + await service.update_task( + task_id=9, project_id=3, update_task=payload, permission="admin", user_id=1 + ) + + send.assert_not_awaited()