feat: implement collaboration module
- Backend (FastAPI): - Task comments with nested replies and soft delete - @mention parsing with 10-mention limit per comment - Notification system with read/unread tracking - Blocker management with project owner notification - WebSocket endpoint with JWT auth and keepalive - User search API for @mention autocomplete - Alembic migration for 4 new tables - Frontend (React + Vite): - Comments component with @mention autocomplete - NotificationBell with real-time WebSocket updates - BlockerDialog for task blocking workflow - NotificationContext for state management - OpenSpec: - 4 requirements with scenarios defined - add-collaboration change archived 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
183
backend/app/services/notification_service.py
Normal file
183
backend/app/services/notification_service.py
Normal file
@@ -0,0 +1,183 @@
|
||||
import uuid
|
||||
import re
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import User, Notification, Task, Comment, Mention
|
||||
|
||||
|
||||
class NotificationService:
|
||||
"""Service for creating and managing notifications."""
|
||||
|
||||
MAX_MENTIONS_PER_COMMENT = 10
|
||||
|
||||
@staticmethod
|
||||
def create_notification(
|
||||
db: Session,
|
||||
user_id: str,
|
||||
notification_type: str,
|
||||
reference_type: str,
|
||||
reference_id: str,
|
||||
title: str,
|
||||
message: Optional[str] = None,
|
||||
) -> Notification:
|
||||
"""Create a notification for a user."""
|
||||
notification = Notification(
|
||||
id=str(uuid.uuid4()),
|
||||
user_id=user_id,
|
||||
type=notification_type,
|
||||
reference_type=reference_type,
|
||||
reference_id=reference_id,
|
||||
title=title,
|
||||
message=message,
|
||||
)
|
||||
db.add(notification)
|
||||
return notification
|
||||
|
||||
@staticmethod
|
||||
def notify_task_assignment(
|
||||
db: Session,
|
||||
task: Task,
|
||||
assigned_by: User,
|
||||
) -> Optional[Notification]:
|
||||
"""Notify user when they are assigned to a task."""
|
||||
if not task.assignee_id or task.assignee_id == assigned_by.id:
|
||||
return None
|
||||
|
||||
return NotificationService.create_notification(
|
||||
db=db,
|
||||
user_id=task.assignee_id,
|
||||
notification_type="assignment",
|
||||
reference_type="task",
|
||||
reference_id=task.id,
|
||||
title=f"You've been assigned to: {task.title}",
|
||||
message=f"Assigned by {assigned_by.name}",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def notify_blocker(
|
||||
db: Session,
|
||||
task: Task,
|
||||
reported_by: User,
|
||||
reason: str,
|
||||
) -> List[Notification]:
|
||||
"""Notify project owner when a task is blocked."""
|
||||
notifications = []
|
||||
|
||||
# Notify project owner
|
||||
project = task.project
|
||||
if project and project.owner_id and project.owner_id != reported_by.id:
|
||||
notification = NotificationService.create_notification(
|
||||
db=db,
|
||||
user_id=project.owner_id,
|
||||
notification_type="blocker",
|
||||
reference_type="task",
|
||||
reference_id=task.id,
|
||||
title=f"Task blocked: {task.title}",
|
||||
message=f"Reported by {reported_by.name}: {reason[:100]}...",
|
||||
)
|
||||
notifications.append(notification)
|
||||
|
||||
return notifications
|
||||
|
||||
@staticmethod
|
||||
def notify_blocker_resolved(
|
||||
db: Session,
|
||||
task: Task,
|
||||
resolved_by: User,
|
||||
reporter_id: str,
|
||||
) -> Optional[Notification]:
|
||||
"""Notify the original reporter when a blocker is resolved."""
|
||||
if reporter_id == resolved_by.id:
|
||||
return None
|
||||
|
||||
return NotificationService.create_notification(
|
||||
db=db,
|
||||
user_id=reporter_id,
|
||||
notification_type="blocker_resolved",
|
||||
reference_type="task",
|
||||
reference_id=task.id,
|
||||
title=f"Blocker resolved: {task.title}",
|
||||
message=f"Resolved by {resolved_by.name}",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def count_mentions(content: str) -> int:
|
||||
"""Count the number of @mentions in content."""
|
||||
pattern = r'@([a-zA-Z0-9._-]+(?:@[a-zA-Z0-9.-]+)?)'
|
||||
matches = re.findall(pattern, content)
|
||||
return len(matches)
|
||||
|
||||
@staticmethod
|
||||
def parse_mentions(content: str) -> List[str]:
|
||||
"""Extract @mentions from comment content. Returns list of email usernames."""
|
||||
# Match @username patterns (alphanumeric and common email chars before @domain)
|
||||
pattern = r'@([a-zA-Z0-9._-]+(?:@[a-zA-Z0-9.-]+)?)'
|
||||
matches = re.findall(pattern, content)
|
||||
return matches[:NotificationService.MAX_MENTIONS_PER_COMMENT]
|
||||
|
||||
@staticmethod
|
||||
def process_mentions(
|
||||
db: Session,
|
||||
comment: Comment,
|
||||
task: Task,
|
||||
author: User,
|
||||
) -> List[Notification]:
|
||||
"""Process mentions in a comment and create notifications."""
|
||||
notifications = []
|
||||
mentioned_usernames = NotificationService.parse_mentions(comment.content)
|
||||
|
||||
if not mentioned_usernames:
|
||||
return notifications
|
||||
|
||||
# Find users by email or name
|
||||
for username in mentioned_usernames:
|
||||
# Try to find user by email first
|
||||
user = db.query(User).filter(
|
||||
(User.email.ilike(f"{username}%")) | (User.name.ilike(f"%{username}%"))
|
||||
).first()
|
||||
|
||||
if user and user.id != author.id:
|
||||
# Create mention record
|
||||
mention = Mention(
|
||||
id=str(uuid.uuid4()),
|
||||
comment_id=comment.id,
|
||||
mentioned_user_id=user.id,
|
||||
)
|
||||
db.add(mention)
|
||||
|
||||
# Create notification
|
||||
notification = NotificationService.create_notification(
|
||||
db=db,
|
||||
user_id=user.id,
|
||||
notification_type="mention",
|
||||
reference_type="comment",
|
||||
reference_id=comment.id,
|
||||
title=f"{author.name} mentioned you in: {task.title}",
|
||||
message=comment.content[:100] + ("..." if len(comment.content) > 100 else ""),
|
||||
)
|
||||
notifications.append(notification)
|
||||
|
||||
return notifications
|
||||
|
||||
@staticmethod
|
||||
def notify_comment_reply(
|
||||
db: Session,
|
||||
comment: Comment,
|
||||
task: Task,
|
||||
author: User,
|
||||
parent_author_id: str,
|
||||
) -> Optional[Notification]:
|
||||
"""Notify original commenter when someone replies."""
|
||||
if parent_author_id == author.id:
|
||||
return None
|
||||
|
||||
return NotificationService.create_notification(
|
||||
db=db,
|
||||
user_id=parent_author_id,
|
||||
notification_type="comment",
|
||||
reference_type="comment",
|
||||
reference_id=comment.id,
|
||||
title=f"{author.name} replied to your comment on: {task.title}",
|
||||
message=comment.content[:100] + ("..." if len(comment.content) > 100 else ""),
|
||||
)
|
||||
82
backend/app/services/websocket_manager.py
Normal file
82
backend/app/services/websocket_manager.py
Normal file
@@ -0,0 +1,82 @@
|
||||
import json
|
||||
import asyncio
|
||||
from typing import Dict, Set, Optional
|
||||
from fastapi import WebSocket
|
||||
from app.core.redis import get_redis_sync
|
||||
|
||||
|
||||
class ConnectionManager:
|
||||
"""Manager for WebSocket connections."""
|
||||
|
||||
def __init__(self):
|
||||
# user_id -> set of WebSocket connections
|
||||
self.active_connections: Dict[str, Set[WebSocket]] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
async def connect(self, websocket: WebSocket, user_id: str):
|
||||
"""Accept and track a new WebSocket connection."""
|
||||
await websocket.accept()
|
||||
async with self._lock:
|
||||
if user_id not in self.active_connections:
|
||||
self.active_connections[user_id] = set()
|
||||
self.active_connections[user_id].add(websocket)
|
||||
|
||||
async def disconnect(self, websocket: WebSocket, user_id: str):
|
||||
"""Remove a WebSocket connection."""
|
||||
async with self._lock:
|
||||
if user_id in self.active_connections:
|
||||
self.active_connections[user_id].discard(websocket)
|
||||
if not self.active_connections[user_id]:
|
||||
del self.active_connections[user_id]
|
||||
|
||||
async def send_personal_message(self, message: dict, user_id: str):
|
||||
"""Send a message to all connections of a specific user."""
|
||||
if user_id in self.active_connections:
|
||||
disconnected = set()
|
||||
for connection in self.active_connections[user_id]:
|
||||
try:
|
||||
await connection.send_json(message)
|
||||
except Exception:
|
||||
disconnected.add(connection)
|
||||
|
||||
# Clean up disconnected connections
|
||||
for conn in disconnected:
|
||||
await self.disconnect(conn, user_id)
|
||||
|
||||
async def broadcast(self, message: dict):
|
||||
"""Broadcast a message to all connected users."""
|
||||
for user_id in list(self.active_connections.keys()):
|
||||
await self.send_personal_message(message, user_id)
|
||||
|
||||
def is_connected(self, user_id: str) -> bool:
|
||||
"""Check if a user has any active connections."""
|
||||
return user_id in self.active_connections and len(self.active_connections[user_id]) > 0
|
||||
|
||||
|
||||
# Global connection manager instance
|
||||
manager = ConnectionManager()
|
||||
|
||||
|
||||
async def publish_notification(user_id: str, notification_data: dict):
|
||||
"""
|
||||
Publish a notification to a user via WebSocket.
|
||||
|
||||
This can be called from anywhere in the application to send
|
||||
real-time notifications to connected users.
|
||||
"""
|
||||
message = {
|
||||
"type": "notification",
|
||||
"data": notification_data,
|
||||
}
|
||||
await manager.send_personal_message(message, user_id)
|
||||
|
||||
|
||||
async def publish_notification_count_update(user_id: str, unread_count: int):
|
||||
"""
|
||||
Publish an unread count update to a user.
|
||||
"""
|
||||
message = {
|
||||
"type": "unread_count",
|
||||
"data": {"unread_count": unread_count},
|
||||
}
|
||||
await manager.send_personal_message(message, user_id)
|
||||
Reference in New Issue
Block a user