Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion api/v1/routers/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
8 changes: 6 additions & 2 deletions core/event_ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions repositories/project_repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
13 changes: 13 additions & 0 deletions services/project_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
74 changes: 69 additions & 5 deletions services/task_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
157 changes: 157 additions & 0 deletions test/test_services/test_notification_messages.py
Original file line number Diff line number Diff line change
@@ -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()
Loading