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:
3
backend/app/api/blockers/__init__.py
Normal file
3
backend/app/api/blockers/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
from app.api.blockers.router import router
|
||||||
|
|
||||||
|
__all__ = ["router"]
|
||||||
200
backend/app/api/blockers/router.py
Normal file
200
backend/app/api/blockers/router.py
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.core.database import get_db
|
||||||
|
from app.models import User, Task, Blocker
|
||||||
|
from app.schemas.blocker import (
|
||||||
|
BlockerCreate, BlockerResolve, BlockerResponse, BlockerListResponse, BlockerUserInfo
|
||||||
|
)
|
||||||
|
from app.middleware.auth import get_current_user, check_task_access, check_task_edit_access
|
||||||
|
from app.services.notification_service import NotificationService
|
||||||
|
|
||||||
|
router = APIRouter(tags=["blockers"])
|
||||||
|
|
||||||
|
|
||||||
|
def blocker_to_response(blocker: Blocker) -> BlockerResponse:
|
||||||
|
"""Convert Blocker model to BlockerResponse."""
|
||||||
|
return BlockerResponse(
|
||||||
|
id=blocker.id,
|
||||||
|
task_id=blocker.task_id,
|
||||||
|
reason=blocker.reason,
|
||||||
|
resolution_note=blocker.resolution_note,
|
||||||
|
created_at=blocker.created_at,
|
||||||
|
resolved_at=blocker.resolved_at,
|
||||||
|
reporter=BlockerUserInfo(
|
||||||
|
id=blocker.reporter.id,
|
||||||
|
name=blocker.reporter.name,
|
||||||
|
email=blocker.reporter.email,
|
||||||
|
),
|
||||||
|
resolver=BlockerUserInfo(
|
||||||
|
id=blocker.resolver.id,
|
||||||
|
name=blocker.resolver.name,
|
||||||
|
email=blocker.resolver.email,
|
||||||
|
) if blocker.resolver else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/tasks/{task_id}/blockers", response_model=BlockerResponse, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_blocker(
|
||||||
|
task_id: str,
|
||||||
|
blocker_data: BlockerCreate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""Mark a task as blocked with a reason."""
|
||||||
|
task = db.query(Task).filter(Task.id == task_id).first()
|
||||||
|
|
||||||
|
if not task:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Task not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not check_task_edit_access(current_user, task, task.project):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Permission denied",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check if task is already blocked with an unresolved blocker
|
||||||
|
existing_blocker = db.query(Blocker).filter(
|
||||||
|
Blocker.task_id == task_id,
|
||||||
|
Blocker.resolved_at == None,
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if existing_blocker:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Task already has an unresolved blocker",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create blocker record
|
||||||
|
blocker = Blocker(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
task_id=task_id,
|
||||||
|
reported_by=current_user.id,
|
||||||
|
reason=blocker_data.reason,
|
||||||
|
)
|
||||||
|
db.add(blocker)
|
||||||
|
|
||||||
|
# Update task blocker_flag
|
||||||
|
task.blocker_flag = True
|
||||||
|
|
||||||
|
# Notify project owner
|
||||||
|
NotificationService.notify_blocker(db, task, current_user, blocker_data.reason)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(blocker)
|
||||||
|
|
||||||
|
return blocker_to_response(blocker)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/blockers/{blocker_id}/resolve", response_model=BlockerResponse)
|
||||||
|
async def resolve_blocker(
|
||||||
|
blocker_id: str,
|
||||||
|
resolve_data: BlockerResolve,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""Resolve a blocker with a resolution note."""
|
||||||
|
blocker = db.query(Blocker).filter(Blocker.id == blocker_id).first()
|
||||||
|
|
||||||
|
if not blocker:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Blocker not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
if blocker.resolved_at is not None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Blocker is already resolved",
|
||||||
|
)
|
||||||
|
|
||||||
|
task = blocker.task
|
||||||
|
if not check_task_edit_access(current_user, task, task.project):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Permission denied",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Update blocker
|
||||||
|
blocker.resolved_by = current_user.id
|
||||||
|
blocker.resolution_note = resolve_data.resolution_note
|
||||||
|
blocker.resolved_at = datetime.utcnow()
|
||||||
|
|
||||||
|
# Check if there are other unresolved blockers
|
||||||
|
other_blockers = db.query(Blocker).filter(
|
||||||
|
Blocker.task_id == task.id,
|
||||||
|
Blocker.id != blocker_id,
|
||||||
|
Blocker.resolved_at == None,
|
||||||
|
).count()
|
||||||
|
|
||||||
|
if other_blockers == 0:
|
||||||
|
task.blocker_flag = False
|
||||||
|
|
||||||
|
# Notify reporter that blocker is resolved
|
||||||
|
NotificationService.notify_blocker_resolved(db, task, current_user, blocker.reported_by)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(blocker)
|
||||||
|
|
||||||
|
return blocker_to_response(blocker)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/tasks/{task_id}/blockers", response_model=BlockerListResponse)
|
||||||
|
async def list_blockers(
|
||||||
|
task_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""List all blockers (history) for a task."""
|
||||||
|
task = db.query(Task).filter(Task.id == task_id).first()
|
||||||
|
|
||||||
|
if not task:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Task not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not check_task_access(current_user, task, task.project):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Access denied",
|
||||||
|
)
|
||||||
|
|
||||||
|
blockers = db.query(Blocker).filter(
|
||||||
|
Blocker.task_id == task_id,
|
||||||
|
).order_by(Blocker.created_at.desc()).all()
|
||||||
|
|
||||||
|
return BlockerListResponse(
|
||||||
|
blockers=[blocker_to_response(b) for b in blockers],
|
||||||
|
total=len(blockers),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/blockers/{blocker_id}", response_model=BlockerResponse)
|
||||||
|
async def get_blocker(
|
||||||
|
blocker_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""Get a specific blocker by ID."""
|
||||||
|
blocker = db.query(Blocker).filter(Blocker.id == blocker_id).first()
|
||||||
|
|
||||||
|
if not blocker:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Blocker not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
task = blocker.task
|
||||||
|
if not check_task_access(current_user, task, task.project):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Access denied",
|
||||||
|
)
|
||||||
|
|
||||||
|
return blocker_to_response(blocker)
|
||||||
3
backend/app/api/comments/__init__.py
Normal file
3
backend/app/api/comments/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
from app.api.comments.router import router
|
||||||
|
|
||||||
|
__all__ = ["router"]
|
||||||
257
backend/app/api/comments/router.py
Normal file
257
backend/app/api/comments/router.py
Normal file
@@ -0,0 +1,257 @@
|
|||||||
|
import uuid
|
||||||
|
from typing import List
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.core.database import get_db
|
||||||
|
from app.models import User, Task, Comment
|
||||||
|
from app.schemas.comment import (
|
||||||
|
CommentCreate, CommentUpdate, CommentResponse, CommentListResponse,
|
||||||
|
CommentAuthor, MentionedUser
|
||||||
|
)
|
||||||
|
from app.middleware.auth import get_current_user, check_task_access
|
||||||
|
from app.services.notification_service import NotificationService
|
||||||
|
|
||||||
|
router = APIRouter(tags=["comments"])
|
||||||
|
|
||||||
|
|
||||||
|
def comment_to_response(comment: Comment) -> CommentResponse:
|
||||||
|
"""Convert Comment model to CommentResponse."""
|
||||||
|
mentioned_users = [
|
||||||
|
MentionedUser(
|
||||||
|
id=m.mentioned_user.id,
|
||||||
|
name=m.mentioned_user.name,
|
||||||
|
email=m.mentioned_user.email,
|
||||||
|
)
|
||||||
|
for m in comment.mentions
|
||||||
|
if m.mentioned_user
|
||||||
|
]
|
||||||
|
|
||||||
|
reply_count = len([r for r in comment.replies if not r.is_deleted]) if comment.replies else 0
|
||||||
|
|
||||||
|
return CommentResponse(
|
||||||
|
id=comment.id,
|
||||||
|
task_id=comment.task_id,
|
||||||
|
parent_comment_id=comment.parent_comment_id,
|
||||||
|
content=comment.content if not comment.is_deleted else "[This comment has been deleted]",
|
||||||
|
is_edited=comment.is_edited,
|
||||||
|
is_deleted=comment.is_deleted,
|
||||||
|
created_at=comment.created_at,
|
||||||
|
updated_at=comment.updated_at,
|
||||||
|
author=CommentAuthor(
|
||||||
|
id=comment.author.id,
|
||||||
|
name=comment.author.name,
|
||||||
|
email=comment.author.email,
|
||||||
|
),
|
||||||
|
mentions=mentioned_users,
|
||||||
|
reply_count=reply_count,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/tasks/{task_id}/comments", response_model=CommentResponse, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_comment(
|
||||||
|
task_id: str,
|
||||||
|
comment_data: CommentCreate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""Create a new comment on a task."""
|
||||||
|
task = db.query(Task).filter(Task.id == task_id).first()
|
||||||
|
|
||||||
|
if not task:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Task not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not check_task_access(current_user, task, task.project):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Access denied",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Validate parent comment if provided
|
||||||
|
parent_author_id = None
|
||||||
|
if comment_data.parent_comment_id:
|
||||||
|
parent_comment = db.query(Comment).filter(
|
||||||
|
Comment.id == comment_data.parent_comment_id,
|
||||||
|
Comment.task_id == task_id,
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if not parent_comment:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Parent comment not found",
|
||||||
|
)
|
||||||
|
parent_author_id = parent_comment.author_id
|
||||||
|
|
||||||
|
# Check @mention limit
|
||||||
|
mention_count = NotificationService.count_mentions(comment_data.content)
|
||||||
|
if mention_count > NotificationService.MAX_MENTIONS_PER_COMMENT:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail=f"Maximum {NotificationService.MAX_MENTIONS_PER_COMMENT} mentions allowed per comment",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create comment
|
||||||
|
comment = Comment(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
task_id=task_id,
|
||||||
|
parent_comment_id=comment_data.parent_comment_id,
|
||||||
|
author_id=current_user.id,
|
||||||
|
content=comment_data.content,
|
||||||
|
)
|
||||||
|
db.add(comment)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
# Process mentions and create notifications
|
||||||
|
NotificationService.process_mentions(db, comment, task, current_user)
|
||||||
|
|
||||||
|
# Notify parent comment author if this is a reply
|
||||||
|
if parent_author_id:
|
||||||
|
NotificationService.notify_comment_reply(db, comment, task, current_user, parent_author_id)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(comment)
|
||||||
|
|
||||||
|
return comment_to_response(comment)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/tasks/{task_id}/comments", response_model=CommentListResponse)
|
||||||
|
async def list_comments(
|
||||||
|
task_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""List all comments on a task."""
|
||||||
|
task = db.query(Task).filter(Task.id == task_id).first()
|
||||||
|
|
||||||
|
if not task:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Task not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not check_task_access(current_user, task, task.project):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Access denied",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Get root comments (no parent) ordered by creation time
|
||||||
|
comments = db.query(Comment).filter(
|
||||||
|
Comment.task_id == task_id,
|
||||||
|
Comment.parent_comment_id == None,
|
||||||
|
).order_by(Comment.created_at).all()
|
||||||
|
|
||||||
|
return CommentListResponse(
|
||||||
|
comments=[comment_to_response(c) for c in comments],
|
||||||
|
total=len(comments),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/comments/{comment_id}/replies", response_model=CommentListResponse)
|
||||||
|
async def list_replies(
|
||||||
|
comment_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""List replies to a comment."""
|
||||||
|
comment = db.query(Comment).filter(Comment.id == comment_id).first()
|
||||||
|
|
||||||
|
if not comment:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Comment not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
task = comment.task
|
||||||
|
if not check_task_access(current_user, task, task.project):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Access denied",
|
||||||
|
)
|
||||||
|
|
||||||
|
replies = db.query(Comment).filter(
|
||||||
|
Comment.parent_comment_id == comment_id,
|
||||||
|
).order_by(Comment.created_at).all()
|
||||||
|
|
||||||
|
return CommentListResponse(
|
||||||
|
comments=[comment_to_response(r) for r in replies],
|
||||||
|
total=len(replies),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/comments/{comment_id}", response_model=CommentResponse)
|
||||||
|
async def update_comment(
|
||||||
|
comment_id: str,
|
||||||
|
comment_data: CommentUpdate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""Update a comment (only by author)."""
|
||||||
|
comment = db.query(Comment).filter(Comment.id == comment_id).first()
|
||||||
|
|
||||||
|
if not comment:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Comment not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
if comment.is_deleted:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Cannot edit a deleted comment",
|
||||||
|
)
|
||||||
|
|
||||||
|
if comment.author_id != current_user.id and not current_user.is_system_admin:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Only the author can edit this comment",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check @mention limit in updated content
|
||||||
|
mention_count = NotificationService.count_mentions(comment_data.content)
|
||||||
|
if mention_count > NotificationService.MAX_MENTIONS_PER_COMMENT:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail=f"Maximum {NotificationService.MAX_MENTIONS_PER_COMMENT} mentions allowed per comment",
|
||||||
|
)
|
||||||
|
|
||||||
|
comment.content = comment_data.content
|
||||||
|
comment.is_edited = True
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(comment)
|
||||||
|
|
||||||
|
return comment_to_response(comment)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/comments/{comment_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
async def delete_comment(
|
||||||
|
comment_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""Delete a comment (soft delete, only by author or admin)."""
|
||||||
|
comment = db.query(Comment).filter(Comment.id == comment_id).first()
|
||||||
|
|
||||||
|
if not comment:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Comment not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
if comment.author_id != current_user.id and not current_user.is_system_admin:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Only the author can delete this comment",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Soft delete - mark as deleted but keep for reply chain
|
||||||
|
comment.is_deleted = True
|
||||||
|
comment.content = ""
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
return None
|
||||||
3
backend/app/api/notifications/__init__.py
Normal file
3
backend/app/api/notifications/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
from app.api.notifications.router import router
|
||||||
|
|
||||||
|
__all__ = ["router"]
|
||||||
119
backend/app/api/notifications/router.py
Normal file
119
backend/app/api/notifications/router.py
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.core.database import get_db
|
||||||
|
from app.models import User, Notification
|
||||||
|
from app.schemas.notification import (
|
||||||
|
NotificationResponse, NotificationListResponse, UnreadCountResponse
|
||||||
|
)
|
||||||
|
from app.middleware.auth import get_current_user
|
||||||
|
|
||||||
|
router = APIRouter(tags=["notifications"])
|
||||||
|
|
||||||
|
|
||||||
|
def notification_to_response(notification: Notification) -> NotificationResponse:
|
||||||
|
"""Convert Notification model to NotificationResponse."""
|
||||||
|
return NotificationResponse(
|
||||||
|
id=notification.id,
|
||||||
|
type=notification.type,
|
||||||
|
reference_type=notification.reference_type,
|
||||||
|
reference_id=notification.reference_id,
|
||||||
|
title=notification.title,
|
||||||
|
message=notification.message,
|
||||||
|
is_read=notification.is_read,
|
||||||
|
created_at=notification.created_at,
|
||||||
|
read_at=notification.read_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/notifications", response_model=NotificationListResponse)
|
||||||
|
async def list_notifications(
|
||||||
|
is_read: Optional[bool] = Query(None, description="Filter by read status"),
|
||||||
|
limit: int = Query(50, ge=1, le=100, description="Number of notifications to return"),
|
||||||
|
offset: int = Query(0, ge=0, description="Offset for pagination"),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""List notifications for the current user."""
|
||||||
|
query = db.query(Notification).filter(Notification.user_id == current_user.id)
|
||||||
|
|
||||||
|
if is_read is not None:
|
||||||
|
query = query.filter(Notification.is_read == is_read)
|
||||||
|
|
||||||
|
total = query.count()
|
||||||
|
unread_count = db.query(Notification).filter(
|
||||||
|
Notification.user_id == current_user.id,
|
||||||
|
Notification.is_read == False,
|
||||||
|
).count()
|
||||||
|
|
||||||
|
notifications = query.order_by(Notification.created_at.desc()).offset(offset).limit(limit).all()
|
||||||
|
|
||||||
|
return NotificationListResponse(
|
||||||
|
notifications=[notification_to_response(n) for n in notifications],
|
||||||
|
total=total,
|
||||||
|
unread_count=unread_count,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/notifications/unread-count", response_model=UnreadCountResponse)
|
||||||
|
async def get_unread_count(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""Get count of unread notifications."""
|
||||||
|
count = db.query(Notification).filter(
|
||||||
|
Notification.user_id == current_user.id,
|
||||||
|
Notification.is_read == False,
|
||||||
|
).count()
|
||||||
|
|
||||||
|
return UnreadCountResponse(unread_count=count)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/notifications/{notification_id}/read", response_model=NotificationResponse)
|
||||||
|
async def mark_as_read(
|
||||||
|
notification_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""Mark a notification as read."""
|
||||||
|
notification = db.query(Notification).filter(
|
||||||
|
Notification.id == notification_id,
|
||||||
|
Notification.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if not notification:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Notification not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not notification.is_read:
|
||||||
|
notification.is_read = True
|
||||||
|
notification.read_at = datetime.utcnow()
|
||||||
|
db.commit()
|
||||||
|
db.refresh(notification)
|
||||||
|
|
||||||
|
return notification_to_response(notification)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/notifications/read-all", response_model=dict)
|
||||||
|
async def mark_all_as_read(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""Mark all notifications as read."""
|
||||||
|
now = datetime.utcnow()
|
||||||
|
|
||||||
|
updated_count = db.query(Notification).filter(
|
||||||
|
Notification.user_id == current_user.id,
|
||||||
|
Notification.is_read == False,
|
||||||
|
).update({
|
||||||
|
Notification.is_read: True,
|
||||||
|
Notification.read_at: now,
|
||||||
|
})
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
return {"updated_count": updated_count}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
from fastapi import APIRouter, Depends, HTTPException, status
|
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
from sqlalchemy import or_
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
from app.core.database import get_db
|
from app.core.database import get_db
|
||||||
@@ -16,6 +17,33 @@ from app.middleware.auth import (
|
|||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/search", response_model=List[UserResponse])
|
||||||
|
async def search_users(
|
||||||
|
q: str = Query(..., min_length=1, max_length=100, description="Search query"),
|
||||||
|
limit: int = Query(10, ge=1, le=50, description="Max results"),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Search users by name or email. Used for @mention autocomplete.
|
||||||
|
Returns users matching the query, limited to same department unless system admin.
|
||||||
|
"""
|
||||||
|
query = db.query(User).filter(
|
||||||
|
User.is_active == True,
|
||||||
|
or_(
|
||||||
|
User.name.ilike(f"%{q}%"),
|
||||||
|
User.email.ilike(f"%{q}%"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Filter by department if not system admin
|
||||||
|
if not current_user.is_system_admin and current_user.department_id:
|
||||||
|
query = query.filter(User.department_id == current_user.department_id)
|
||||||
|
|
||||||
|
users = query.limit(limit).all()
|
||||||
|
return users
|
||||||
|
|
||||||
|
|
||||||
@router.get("", response_model=List[UserResponse])
|
@router.get("", response_model=List[UserResponse])
|
||||||
async def list_users(
|
async def list_users(
|
||||||
skip: int = 0,
|
skip: int = 0,
|
||||||
|
|||||||
3
backend/app/api/websocket/__init__.py
Normal file
3
backend/app/api/websocket/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
from app.api.websocket.router import router
|
||||||
|
|
||||||
|
__all__ = ["router"]
|
||||||
98
backend/app/api/websocket/router.py
Normal file
98
backend/app/api/websocket/router.py
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
import asyncio
|
||||||
|
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.core.database import SessionLocal
|
||||||
|
from app.core.security import decode_access_token
|
||||||
|
from app.core.redis import get_redis_sync
|
||||||
|
from app.models import User
|
||||||
|
from app.services.websocket_manager import manager
|
||||||
|
|
||||||
|
router = APIRouter(tags=["websocket"])
|
||||||
|
|
||||||
|
|
||||||
|
async def get_user_from_token(token: str) -> tuple[str | None, User | None]:
|
||||||
|
"""Validate token and return user_id and user object."""
|
||||||
|
payload = decode_access_token(token)
|
||||||
|
if payload is None:
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
user_id = payload.get("sub")
|
||||||
|
if user_id is None:
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
# Verify session in Redis
|
||||||
|
redis_client = get_redis_sync()
|
||||||
|
stored_token = redis_client.get(f"session:{user_id}")
|
||||||
|
if stored_token is None or stored_token != token:
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
# Get user from database
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
user = db.query(User).filter(User.id == user_id).first()
|
||||||
|
if user is None or not user.is_active:
|
||||||
|
return None, None
|
||||||
|
return user_id, user
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
@router.websocket("/ws/notifications")
|
||||||
|
async def websocket_notifications(
|
||||||
|
websocket: WebSocket,
|
||||||
|
token: str = Query(..., description="JWT token for authentication"),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
WebSocket endpoint for real-time notifications.
|
||||||
|
|
||||||
|
Connect with: ws://host/ws/notifications?token=<jwt_token>
|
||||||
|
|
||||||
|
Messages sent by server:
|
||||||
|
- {"type": "notification", "data": {...}} - New notification
|
||||||
|
- {"type": "unread_count", "data": {"unread_count": N}} - Unread count update
|
||||||
|
- {"type": "pong"} - Response to ping
|
||||||
|
|
||||||
|
Messages accepted from client:
|
||||||
|
- {"type": "ping"} - Keepalive ping
|
||||||
|
"""
|
||||||
|
user_id, user = await get_user_from_token(token)
|
||||||
|
|
||||||
|
if user_id is None:
|
||||||
|
await websocket.close(code=4001, reason="Invalid or expired token")
|
||||||
|
return
|
||||||
|
|
||||||
|
await manager.connect(websocket, user_id)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Send initial connection success message
|
||||||
|
await websocket.send_json({
|
||||||
|
"type": "connected",
|
||||||
|
"data": {"user_id": user_id, "message": "Connected to notification service"},
|
||||||
|
})
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
# Wait for messages from client (ping/pong for keepalive)
|
||||||
|
data = await asyncio.wait_for(
|
||||||
|
websocket.receive_json(),
|
||||||
|
timeout=60.0 # 60 second timeout
|
||||||
|
)
|
||||||
|
|
||||||
|
# Handle ping message
|
||||||
|
if data.get("type") == "ping":
|
||||||
|
await websocket.send_json({"type": "pong"})
|
||||||
|
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
# Send keepalive ping if no message received
|
||||||
|
try:
|
||||||
|
await websocket.send_json({"type": "ping"})
|
||||||
|
except Exception:
|
||||||
|
break
|
||||||
|
|
||||||
|
except WebSocketDisconnect:
|
||||||
|
pass
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
await manager.disconnect(websocket, user_id)
|
||||||
@@ -12,3 +12,8 @@ redis_client = redis.Redis(
|
|||||||
def get_redis():
|
def get_redis():
|
||||||
"""Dependency for getting Redis client."""
|
"""Dependency for getting Redis client."""
|
||||||
return redis_client
|
return redis_client
|
||||||
|
|
||||||
|
|
||||||
|
def get_redis_sync():
|
||||||
|
"""Get Redis client synchronously (non-dependency use)."""
|
||||||
|
return redis_client
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ from app.api.spaces import router as spaces_router
|
|||||||
from app.api.projects import router as projects_router
|
from app.api.projects import router as projects_router
|
||||||
from app.api.tasks import router as tasks_router
|
from app.api.tasks import router as tasks_router
|
||||||
from app.api.workload import router as workload_router
|
from app.api.workload import router as workload_router
|
||||||
|
from app.api.comments import router as comments_router
|
||||||
|
from app.api.notifications import router as notifications_router
|
||||||
|
from app.api.blockers import router as blockers_router
|
||||||
|
from app.api.websocket import router as websocket_router
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
@@ -33,6 +37,10 @@ app.include_router(spaces_router)
|
|||||||
app.include_router(projects_router)
|
app.include_router(projects_router)
|
||||||
app.include_router(tasks_router)
|
app.include_router(tasks_router)
|
||||||
app.include_router(workload_router, prefix="/api/workload", tags=["Workload"])
|
app.include_router(workload_router, prefix="/api/workload", tags=["Workload"])
|
||||||
|
app.include_router(comments_router)
|
||||||
|
app.include_router(notifications_router)
|
||||||
|
app.include_router(blockers_router)
|
||||||
|
app.include_router(websocket_router)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/health")
|
@app.get("/health")
|
||||||
|
|||||||
@@ -6,5 +6,12 @@ from app.models.project import Project
|
|||||||
from app.models.task_status import TaskStatus
|
from app.models.task_status import TaskStatus
|
||||||
from app.models.task import Task
|
from app.models.task import Task
|
||||||
from app.models.workload_snapshot import WorkloadSnapshot
|
from app.models.workload_snapshot import WorkloadSnapshot
|
||||||
|
from app.models.comment import Comment
|
||||||
|
from app.models.mention import Mention
|
||||||
|
from app.models.notification import Notification
|
||||||
|
from app.models.blocker import Blocker
|
||||||
|
|
||||||
__all__ = ["User", "Role", "Department", "Space", "Project", "TaskStatus", "Task", "WorkloadSnapshot"]
|
__all__ = [
|
||||||
|
"User", "Role", "Department", "Space", "Project", "TaskStatus", "Task", "WorkloadSnapshot",
|
||||||
|
"Comment", "Mention", "Notification", "Blocker"
|
||||||
|
]
|
||||||
|
|||||||
23
backend/app/models/blocker.py
Normal file
23
backend/app/models/blocker.py
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import uuid
|
||||||
|
from sqlalchemy import Column, String, Text, DateTime, ForeignKey
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from app.core.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Blocker(Base):
|
||||||
|
__tablename__ = "pjctrl_blockers"
|
||||||
|
|
||||||
|
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||||
|
task_id = Column(String(36), ForeignKey("pjctrl_tasks.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
reported_by = Column(String(36), ForeignKey("pjctrl_users.id"), nullable=False)
|
||||||
|
reason = Column(Text, nullable=False)
|
||||||
|
resolved_by = Column(String(36), ForeignKey("pjctrl_users.id"), nullable=True)
|
||||||
|
resolution_note = Column(Text, nullable=True)
|
||||||
|
created_at = Column(DateTime, server_default=func.now(), nullable=False)
|
||||||
|
resolved_at = Column(DateTime, nullable=True)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
task = relationship("Task", back_populates="blockers")
|
||||||
|
reporter = relationship("User", foreign_keys=[reported_by], back_populates="reported_blockers")
|
||||||
|
resolver = relationship("User", foreign_keys=[resolved_by], back_populates="resolved_blockers")
|
||||||
26
backend/app/models/comment.py
Normal file
26
backend/app/models/comment.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import uuid
|
||||||
|
from sqlalchemy import Column, String, Text, Boolean, DateTime, ForeignKey
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from app.core.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Comment(Base):
|
||||||
|
__tablename__ = "pjctrl_comments"
|
||||||
|
|
||||||
|
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||||
|
task_id = Column(String(36), ForeignKey("pjctrl_tasks.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
parent_comment_id = Column(String(36), ForeignKey("pjctrl_comments.id", ondelete="CASCADE"), nullable=True)
|
||||||
|
author_id = Column(String(36), ForeignKey("pjctrl_users.id"), nullable=False)
|
||||||
|
content = Column(Text, nullable=False)
|
||||||
|
is_edited = Column(Boolean, default=False, nullable=False)
|
||||||
|
is_deleted = Column(Boolean, default=False, nullable=False)
|
||||||
|
created_at = Column(DateTime, server_default=func.now(), nullable=False)
|
||||||
|
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
task = relationship("Task", back_populates="comments")
|
||||||
|
author = relationship("User", back_populates="comments")
|
||||||
|
parent_comment = relationship("Comment", remote_side=[id], back_populates="replies")
|
||||||
|
replies = relationship("Comment", back_populates="parent_comment", cascade="all, delete-orphan")
|
||||||
|
mentions = relationship("Mention", back_populates="comment", cascade="all, delete-orphan")
|
||||||
18
backend/app/models/mention.py
Normal file
18
backend/app/models/mention.py
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import uuid
|
||||||
|
from sqlalchemy import Column, String, DateTime, ForeignKey
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from app.core.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Mention(Base):
|
||||||
|
__tablename__ = "pjctrl_mentions"
|
||||||
|
|
||||||
|
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||||
|
comment_id = Column(String(36), ForeignKey("pjctrl_comments.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
mentioned_user_id = Column(String(36), ForeignKey("pjctrl_users.id"), nullable=False)
|
||||||
|
created_at = Column(DateTime, server_default=func.now(), nullable=False)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
comment = relationship("Comment", back_populates="mentions")
|
||||||
|
mentioned_user = relationship("User", back_populates="mentions")
|
||||||
37
backend/app/models/notification.py
Normal file
37
backend/app/models/notification.py
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import uuid
|
||||||
|
from sqlalchemy import Column, String, Text, Boolean, DateTime, ForeignKey, Enum
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from app.core.database import Base
|
||||||
|
import enum
|
||||||
|
|
||||||
|
|
||||||
|
class NotificationType(str, enum.Enum):
|
||||||
|
MENTION = "mention"
|
||||||
|
ASSIGNMENT = "assignment"
|
||||||
|
BLOCKER = "blocker"
|
||||||
|
STATUS_CHANGE = "status_change"
|
||||||
|
COMMENT = "comment"
|
||||||
|
BLOCKER_RESOLVED = "blocker_resolved"
|
||||||
|
|
||||||
|
|
||||||
|
class Notification(Base):
|
||||||
|
__tablename__ = "pjctrl_notifications"
|
||||||
|
|
||||||
|
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||||
|
user_id = Column(String(36), ForeignKey("pjctrl_users.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
type = Column(
|
||||||
|
Enum("mention", "assignment", "blocker", "status_change", "comment", "blocker_resolved",
|
||||||
|
name="notification_type_enum"),
|
||||||
|
nullable=False
|
||||||
|
)
|
||||||
|
reference_type = Column(String(50), nullable=False)
|
||||||
|
reference_id = Column(String(36), nullable=False)
|
||||||
|
title = Column(String(200), nullable=False)
|
||||||
|
message = Column(Text, nullable=True)
|
||||||
|
is_read = Column(Boolean, default=False, nullable=False)
|
||||||
|
created_at = Column(DateTime, server_default=func.now(), nullable=False)
|
||||||
|
read_at = Column(DateTime, nullable=True)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
user = relationship("User", back_populates="notifications")
|
||||||
@@ -43,3 +43,7 @@ class Task(Base):
|
|||||||
assignee = relationship("User", foreign_keys=[assignee_id], back_populates="assigned_tasks")
|
assignee = relationship("User", foreign_keys=[assignee_id], back_populates="assigned_tasks")
|
||||||
creator = relationship("User", foreign_keys=[created_by], back_populates="created_tasks")
|
creator = relationship("User", foreign_keys=[created_by], back_populates="created_tasks")
|
||||||
status = relationship("TaskStatus", back_populates="tasks")
|
status = relationship("TaskStatus", back_populates="tasks")
|
||||||
|
|
||||||
|
# Collaboration relationships
|
||||||
|
comments = relationship("Comment", back_populates="task", cascade="all, delete-orphan")
|
||||||
|
blockers = relationship("Blocker", back_populates="task", cascade="all, delete-orphan")
|
||||||
|
|||||||
@@ -29,3 +29,10 @@ class User(Base):
|
|||||||
owned_projects = relationship("Project", foreign_keys="Project.owner_id", back_populates="owner")
|
owned_projects = relationship("Project", foreign_keys="Project.owner_id", back_populates="owner")
|
||||||
assigned_tasks = relationship("Task", foreign_keys="Task.assignee_id", back_populates="assignee")
|
assigned_tasks = relationship("Task", foreign_keys="Task.assignee_id", back_populates="assignee")
|
||||||
created_tasks = relationship("Task", foreign_keys="Task.created_by", back_populates="creator")
|
created_tasks = relationship("Task", foreign_keys="Task.created_by", back_populates="creator")
|
||||||
|
|
||||||
|
# Collaboration relationships
|
||||||
|
comments = relationship("Comment", back_populates="author")
|
||||||
|
mentions = relationship("Mention", back_populates="mentioned_user")
|
||||||
|
notifications = relationship("Notification", back_populates="user", cascade="all, delete-orphan")
|
||||||
|
reported_blockers = relationship("Blocker", foreign_keys="Blocker.reported_by", back_populates="reporter")
|
||||||
|
resolved_blockers = relationship("Blocker", foreign_keys="Blocker.resolved_by", back_populates="resolver")
|
||||||
|
|||||||
@@ -11,6 +11,15 @@ from app.schemas.task import (
|
|||||||
TaskCreate, TaskUpdate, TaskResponse, TaskWithDetails, TaskListResponse,
|
TaskCreate, TaskUpdate, TaskResponse, TaskWithDetails, TaskListResponse,
|
||||||
TaskStatusUpdate as TaskStatusChangeUpdate, TaskAssignUpdate, Priority
|
TaskStatusUpdate as TaskStatusChangeUpdate, TaskAssignUpdate, Priority
|
||||||
)
|
)
|
||||||
|
from app.schemas.comment import (
|
||||||
|
CommentCreate, CommentUpdate, CommentResponse, CommentListResponse
|
||||||
|
)
|
||||||
|
from app.schemas.notification import (
|
||||||
|
NotificationResponse, NotificationListResponse, UnreadCountResponse
|
||||||
|
)
|
||||||
|
from app.schemas.blocker import (
|
||||||
|
BlockerCreate, BlockerResolve, BlockerResponse, BlockerListResponse
|
||||||
|
)
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"LoginRequest",
|
"LoginRequest",
|
||||||
@@ -44,4 +53,15 @@ __all__ = [
|
|||||||
"TaskStatusChangeUpdate",
|
"TaskStatusChangeUpdate",
|
||||||
"TaskAssignUpdate",
|
"TaskAssignUpdate",
|
||||||
"Priority",
|
"Priority",
|
||||||
|
"CommentCreate",
|
||||||
|
"CommentUpdate",
|
||||||
|
"CommentResponse",
|
||||||
|
"CommentListResponse",
|
||||||
|
"NotificationResponse",
|
||||||
|
"NotificationListResponse",
|
||||||
|
"UnreadCountResponse",
|
||||||
|
"BlockerCreate",
|
||||||
|
"BlockerResolve",
|
||||||
|
"BlockerResponse",
|
||||||
|
"BlockerListResponse",
|
||||||
]
|
]
|
||||||
|
|||||||
39
backend/app/schemas/blocker.py
Normal file
39
backend/app/schemas/blocker.py
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional, List
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class BlockerCreate(BaseModel):
|
||||||
|
reason: str = Field(..., min_length=1, max_length=2000)
|
||||||
|
|
||||||
|
|
||||||
|
class BlockerResolve(BaseModel):
|
||||||
|
resolution_note: str = Field(..., min_length=1, max_length=2000)
|
||||||
|
|
||||||
|
|
||||||
|
class BlockerUserInfo(BaseModel):
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
email: str
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class BlockerResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
task_id: str
|
||||||
|
reason: str
|
||||||
|
resolution_note: Optional[str]
|
||||||
|
created_at: datetime
|
||||||
|
resolved_at: Optional[datetime]
|
||||||
|
reporter: BlockerUserInfo
|
||||||
|
resolver: Optional[BlockerUserInfo]
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class BlockerListResponse(BaseModel):
|
||||||
|
blockers: List[BlockerResponse]
|
||||||
|
total: int
|
||||||
52
backend/app/schemas/comment.py
Normal file
52
backend/app/schemas/comment.py
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional, List
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class CommentCreate(BaseModel):
|
||||||
|
content: str = Field(..., min_length=1, max_length=10000)
|
||||||
|
parent_comment_id: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class CommentUpdate(BaseModel):
|
||||||
|
content: str = Field(..., min_length=1, max_length=10000)
|
||||||
|
|
||||||
|
|
||||||
|
class CommentAuthor(BaseModel):
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
email: str
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class MentionedUser(BaseModel):
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
email: str
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class CommentResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
task_id: str
|
||||||
|
parent_comment_id: Optional[str]
|
||||||
|
content: str
|
||||||
|
is_edited: bool
|
||||||
|
is_deleted: bool
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
author: CommentAuthor
|
||||||
|
mentions: List[MentionedUser] = []
|
||||||
|
reply_count: int = 0
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class CommentListResponse(BaseModel):
|
||||||
|
comments: List[CommentResponse]
|
||||||
|
total: int
|
||||||
28
backend/app/schemas/notification.py
Normal file
28
backend/app/schemas/notification.py
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional, List
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class NotificationResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
type: str
|
||||||
|
reference_type: str
|
||||||
|
reference_id: str
|
||||||
|
title: str
|
||||||
|
message: Optional[str]
|
||||||
|
is_read: bool
|
||||||
|
created_at: datetime
|
||||||
|
read_at: Optional[datetime]
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class NotificationListResponse(BaseModel):
|
||||||
|
notifications: List[NotificationResponse]
|
||||||
|
total: int
|
||||||
|
unread_count: int
|
||||||
|
|
||||||
|
|
||||||
|
class UnreadCountResponse(BaseModel):
|
||||||
|
unread_count: int
|
||||||
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)
|
||||||
@@ -10,7 +10,10 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|||||||
|
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
from app.core.database import Base
|
from app.core.database import Base
|
||||||
from app.models import User, Role, Department
|
from app.models import (
|
||||||
|
User, Role, Department, Space, Project, TaskStatus, Task, WorkloadSnapshot,
|
||||||
|
Comment, Mention, Notification, Blocker
|
||||||
|
)
|
||||||
|
|
||||||
config = context.config
|
config = context.config
|
||||||
|
|
||||||
|
|||||||
96
backend/migrations/versions/004_collaboration_tables.py
Normal file
96
backend/migrations/versions/004_collaboration_tables.py
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
"""Collaboration tables (comments, mentions, notifications, blockers)
|
||||||
|
|
||||||
|
Revision ID: 004
|
||||||
|
Revises: 003
|
||||||
|
Create Date: 2024-01-XX
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '004'
|
||||||
|
down_revision = '003'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# Create notification_type_enum
|
||||||
|
notification_type_enum = sa.Enum(
|
||||||
|
'mention', 'assignment', 'blocker', 'status_change', 'comment', 'blocker_resolved',
|
||||||
|
name='notification_type_enum'
|
||||||
|
)
|
||||||
|
notification_type_enum.create(op.get_bind(), checkfirst=True)
|
||||||
|
|
||||||
|
# Create pjctrl_comments table
|
||||||
|
op.create_table(
|
||||||
|
'pjctrl_comments',
|
||||||
|
sa.Column('id', sa.String(36), primary_key=True),
|
||||||
|
sa.Column('task_id', sa.String(36), sa.ForeignKey('pjctrl_tasks.id', ondelete='CASCADE'), nullable=False),
|
||||||
|
sa.Column('parent_comment_id', sa.String(36), sa.ForeignKey('pjctrl_comments.id', ondelete='CASCADE'), nullable=True),
|
||||||
|
sa.Column('author_id', sa.String(36), sa.ForeignKey('pjctrl_users.id'), nullable=False),
|
||||||
|
sa.Column('content', sa.Text, nullable=False),
|
||||||
|
sa.Column('is_edited', sa.Boolean, server_default='0', nullable=False),
|
||||||
|
sa.Column('is_deleted', sa.Boolean, server_default='0', nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime, server_default=sa.func.now(), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime, server_default=sa.func.now(), onupdate=sa.func.now(), nullable=False),
|
||||||
|
)
|
||||||
|
op.create_index('idx_comments_task', 'pjctrl_comments', ['task_id'])
|
||||||
|
op.create_index('idx_comments_author', 'pjctrl_comments', ['author_id'])
|
||||||
|
op.create_index('idx_comments_parent', 'pjctrl_comments', ['parent_comment_id'])
|
||||||
|
|
||||||
|
# Create pjctrl_mentions table
|
||||||
|
op.create_table(
|
||||||
|
'pjctrl_mentions',
|
||||||
|
sa.Column('id', sa.String(36), primary_key=True),
|
||||||
|
sa.Column('comment_id', sa.String(36), sa.ForeignKey('pjctrl_comments.id', ondelete='CASCADE'), nullable=False),
|
||||||
|
sa.Column('mentioned_user_id', sa.String(36), sa.ForeignKey('pjctrl_users.id'), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime, server_default=sa.func.now(), nullable=False),
|
||||||
|
)
|
||||||
|
op.create_index('idx_mentions_comment', 'pjctrl_mentions', ['comment_id'])
|
||||||
|
op.create_index('idx_mentions_user', 'pjctrl_mentions', ['mentioned_user_id'])
|
||||||
|
|
||||||
|
# Create pjctrl_notifications table
|
||||||
|
op.create_table(
|
||||||
|
'pjctrl_notifications',
|
||||||
|
sa.Column('id', sa.String(36), primary_key=True),
|
||||||
|
sa.Column('user_id', sa.String(36), sa.ForeignKey('pjctrl_users.id', ondelete='CASCADE'), nullable=False),
|
||||||
|
sa.Column('type', notification_type_enum, nullable=False),
|
||||||
|
sa.Column('reference_type', sa.String(50), nullable=False),
|
||||||
|
sa.Column('reference_id', sa.String(36), nullable=False),
|
||||||
|
sa.Column('title', sa.String(200), nullable=False),
|
||||||
|
sa.Column('message', sa.Text, nullable=True),
|
||||||
|
sa.Column('is_read', sa.Boolean, server_default='0', nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime, server_default=sa.func.now(), nullable=False),
|
||||||
|
sa.Column('read_at', sa.DateTime, nullable=True),
|
||||||
|
)
|
||||||
|
op.create_index('idx_notifications_user', 'pjctrl_notifications', ['user_id'])
|
||||||
|
op.create_index('idx_notifications_user_unread', 'pjctrl_notifications', ['user_id', 'is_read'])
|
||||||
|
op.create_index('idx_notifications_reference', 'pjctrl_notifications', ['reference_type', 'reference_id'])
|
||||||
|
|
||||||
|
# Create pjctrl_blockers table
|
||||||
|
op.create_table(
|
||||||
|
'pjctrl_blockers',
|
||||||
|
sa.Column('id', sa.String(36), primary_key=True),
|
||||||
|
sa.Column('task_id', sa.String(36), sa.ForeignKey('pjctrl_tasks.id', ondelete='CASCADE'), nullable=False),
|
||||||
|
sa.Column('reported_by', sa.String(36), sa.ForeignKey('pjctrl_users.id'), nullable=False),
|
||||||
|
sa.Column('reason', sa.Text, nullable=False),
|
||||||
|
sa.Column('resolved_by', sa.String(36), sa.ForeignKey('pjctrl_users.id'), nullable=True),
|
||||||
|
sa.Column('resolution_note', sa.Text, nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime, server_default=sa.func.now(), nullable=False),
|
||||||
|
sa.Column('resolved_at', sa.DateTime, nullable=True),
|
||||||
|
)
|
||||||
|
op.create_index('idx_blockers_task', 'pjctrl_blockers', ['task_id'])
|
||||||
|
op.create_index('idx_blockers_reported_by', 'pjctrl_blockers', ['reported_by'])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table('pjctrl_blockers')
|
||||||
|
op.drop_table('pjctrl_notifications')
|
||||||
|
op.drop_table('pjctrl_mentions')
|
||||||
|
op.drop_table('pjctrl_comments')
|
||||||
|
|
||||||
|
# Drop enum type
|
||||||
|
notification_type_enum = sa.Enum(name='notification_type_enum')
|
||||||
|
notification_type_enum.drop(op.get_bind(), checkfirst=True)
|
||||||
420
backend/tests/test_collaboration.py
Normal file
420
backend/tests/test_collaboration.py
Normal file
@@ -0,0 +1,420 @@
|
|||||||
|
import pytest
|
||||||
|
import uuid
|
||||||
|
from app.models import User, Space, Project, Task, TaskStatus, Comment, Notification, Blocker
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def test_user(db):
|
||||||
|
"""Create a test user."""
|
||||||
|
user = User(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
email="testuser@example.com",
|
||||||
|
name="Test User",
|
||||||
|
role_id="00000000-0000-0000-0000-000000000003",
|
||||||
|
is_active=True,
|
||||||
|
is_system_admin=False,
|
||||||
|
)
|
||||||
|
db.add(user)
|
||||||
|
db.commit()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def user_token(client, mock_redis, test_user):
|
||||||
|
"""Get a user token for testing."""
|
||||||
|
from app.core.security import create_access_token, create_token_payload
|
||||||
|
|
||||||
|
token_data = create_token_payload(
|
||||||
|
user_id=test_user.id,
|
||||||
|
email=test_user.email,
|
||||||
|
role="engineer",
|
||||||
|
department_id=None,
|
||||||
|
is_system_admin=False,
|
||||||
|
)
|
||||||
|
token = create_access_token(token_data)
|
||||||
|
mock_redis.setex(f"session:{test_user.id}", 900, token)
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def test_space(db):
|
||||||
|
"""Create a test space."""
|
||||||
|
space = Space(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
name="Test Space",
|
||||||
|
description="A test space",
|
||||||
|
owner_id="00000000-0000-0000-0000-000000000001",
|
||||||
|
)
|
||||||
|
db.add(space)
|
||||||
|
db.commit()
|
||||||
|
return space
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def test_project(db, test_space):
|
||||||
|
"""Create a test project."""
|
||||||
|
project = Project(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
space_id=test_space.id,
|
||||||
|
title="Test Project",
|
||||||
|
description="A test project",
|
||||||
|
owner_id="00000000-0000-0000-0000-000000000001",
|
||||||
|
security_level="public",
|
||||||
|
)
|
||||||
|
db.add(project)
|
||||||
|
db.commit()
|
||||||
|
return project
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def test_status(db, test_project):
|
||||||
|
"""Create a test task status."""
|
||||||
|
status = TaskStatus(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
project_id=test_project.id,
|
||||||
|
name="To Do",
|
||||||
|
color="#3498db",
|
||||||
|
position=0,
|
||||||
|
)
|
||||||
|
db.add(status)
|
||||||
|
db.commit()
|
||||||
|
return status
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def test_task(db, test_project, test_status):
|
||||||
|
"""Create a test task."""
|
||||||
|
task = Task(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
project_id=test_project.id,
|
||||||
|
title="Test Task",
|
||||||
|
description="A test task",
|
||||||
|
status_id=test_status.id,
|
||||||
|
created_by="00000000-0000-0000-0000-000000000001",
|
||||||
|
)
|
||||||
|
db.add(task)
|
||||||
|
db.commit()
|
||||||
|
return task
|
||||||
|
|
||||||
|
|
||||||
|
class TestComments:
|
||||||
|
"""Tests for Comments API."""
|
||||||
|
|
||||||
|
def test_create_comment(self, client, admin_token, test_task):
|
||||||
|
"""Test creating a comment."""
|
||||||
|
response = client.post(
|
||||||
|
f"/api/tasks/{test_task.id}/comments",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
json={"content": "This is a test comment"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 201
|
||||||
|
data = response.json()
|
||||||
|
assert data["content"] == "This is a test comment"
|
||||||
|
assert data["task_id"] == test_task.id
|
||||||
|
assert data["is_edited"] is False
|
||||||
|
assert data["is_deleted"] is False
|
||||||
|
|
||||||
|
def test_list_comments(self, client, admin_token, db, test_task):
|
||||||
|
"""Test listing comments."""
|
||||||
|
# Create a comment first
|
||||||
|
comment = Comment(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
task_id=test_task.id,
|
||||||
|
author_id="00000000-0000-0000-0000-000000000001",
|
||||||
|
content="Test comment",
|
||||||
|
)
|
||||||
|
db.add(comment)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.get(
|
||||||
|
f"/api/tasks/{test_task.id}/comments",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["total"] == 1
|
||||||
|
assert len(data["comments"]) == 1
|
||||||
|
assert data["comments"][0]["content"] == "Test comment"
|
||||||
|
|
||||||
|
def test_update_comment(self, client, admin_token, db, test_task):
|
||||||
|
"""Test updating a comment."""
|
||||||
|
comment = Comment(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
task_id=test_task.id,
|
||||||
|
author_id="00000000-0000-0000-0000-000000000001",
|
||||||
|
content="Original content",
|
||||||
|
)
|
||||||
|
db.add(comment)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.put(
|
||||||
|
f"/api/comments/{comment.id}",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
json={"content": "Updated content"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["content"] == "Updated content"
|
||||||
|
assert data["is_edited"] is True
|
||||||
|
|
||||||
|
def test_delete_comment(self, client, admin_token, db, test_task):
|
||||||
|
"""Test deleting a comment (soft delete)."""
|
||||||
|
comment = Comment(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
task_id=test_task.id,
|
||||||
|
author_id="00000000-0000-0000-0000-000000000001",
|
||||||
|
content="To be deleted",
|
||||||
|
)
|
||||||
|
db.add(comment)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.delete(
|
||||||
|
f"/api/comments/{comment.id}",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 204
|
||||||
|
|
||||||
|
# Verify soft delete
|
||||||
|
db.refresh(comment)
|
||||||
|
assert comment.is_deleted is True
|
||||||
|
|
||||||
|
def test_mention_limit(self, client, admin_token, test_task):
|
||||||
|
"""Test that @mention limit is enforced."""
|
||||||
|
# Create content with more than 10 mentions
|
||||||
|
mentions = " ".join([f"@user{i}" for i in range(15)])
|
||||||
|
response = client.post(
|
||||||
|
f"/api/tasks/{test_task.id}/comments",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
json={"content": f"Test with many mentions: {mentions}"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "10 mentions" in response.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
class TestNotifications:
|
||||||
|
"""Tests for Notifications API."""
|
||||||
|
|
||||||
|
def test_list_notifications(self, client, admin_token, db):
|
||||||
|
"""Test listing notifications."""
|
||||||
|
# Create a notification
|
||||||
|
notification = Notification(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
user_id="00000000-0000-0000-0000-000000000001",
|
||||||
|
type="mention",
|
||||||
|
reference_type="comment",
|
||||||
|
reference_id=str(uuid.uuid4()),
|
||||||
|
title="Test notification",
|
||||||
|
message="Test message",
|
||||||
|
)
|
||||||
|
db.add(notification)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.get(
|
||||||
|
"/api/notifications",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["total"] >= 1
|
||||||
|
assert data["unread_count"] >= 1
|
||||||
|
|
||||||
|
def test_mark_notification_as_read(self, client, admin_token, db):
|
||||||
|
"""Test marking a notification as read."""
|
||||||
|
notification = Notification(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
user_id="00000000-0000-0000-0000-000000000001",
|
||||||
|
type="assignment",
|
||||||
|
reference_type="task",
|
||||||
|
reference_id=str(uuid.uuid4()),
|
||||||
|
title="New assignment",
|
||||||
|
)
|
||||||
|
db.add(notification)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.put(
|
||||||
|
f"/api/notifications/{notification.id}/read",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["is_read"] is True
|
||||||
|
assert data["read_at"] is not None
|
||||||
|
|
||||||
|
def test_mark_all_as_read(self, client, admin_token, db):
|
||||||
|
"""Test marking all notifications as read."""
|
||||||
|
# Create multiple unread notifications
|
||||||
|
for i in range(3):
|
||||||
|
notification = Notification(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
user_id="00000000-0000-0000-0000-000000000001",
|
||||||
|
type="comment",
|
||||||
|
reference_type="task",
|
||||||
|
reference_id=str(uuid.uuid4()),
|
||||||
|
title=f"Notification {i}",
|
||||||
|
)
|
||||||
|
db.add(notification)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.put(
|
||||||
|
"/api/notifications/read-all",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["updated_count"] >= 3
|
||||||
|
|
||||||
|
def test_get_unread_count(self, client, admin_token, db):
|
||||||
|
"""Test getting unread notification count."""
|
||||||
|
# Create unread notifications
|
||||||
|
for i in range(2):
|
||||||
|
notification = Notification(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
user_id="00000000-0000-0000-0000-000000000001",
|
||||||
|
type="blocker",
|
||||||
|
reference_type="task",
|
||||||
|
reference_id=str(uuid.uuid4()),
|
||||||
|
title=f"Blocker {i}",
|
||||||
|
)
|
||||||
|
db.add(notification)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.get(
|
||||||
|
"/api/notifications/unread-count",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["unread_count"] >= 2
|
||||||
|
|
||||||
|
|
||||||
|
class TestBlockers:
|
||||||
|
"""Tests for Blockers API."""
|
||||||
|
|
||||||
|
def test_create_blocker(self, client, admin_token, test_task):
|
||||||
|
"""Test creating a blocker."""
|
||||||
|
response = client.post(
|
||||||
|
f"/api/tasks/{test_task.id}/blockers",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
json={"reason": "Waiting for external dependency"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 201
|
||||||
|
data = response.json()
|
||||||
|
assert data["reason"] == "Waiting for external dependency"
|
||||||
|
assert data["resolved_at"] is None
|
||||||
|
|
||||||
|
def test_resolve_blocker(self, client, admin_token, db, test_task):
|
||||||
|
"""Test resolving a blocker."""
|
||||||
|
blocker = Blocker(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
task_id=test_task.id,
|
||||||
|
reported_by="00000000-0000-0000-0000-000000000001",
|
||||||
|
reason="Test blocker",
|
||||||
|
)
|
||||||
|
db.add(blocker)
|
||||||
|
test_task.blocker_flag = True
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.put(
|
||||||
|
f"/api/blockers/{blocker.id}/resolve",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
json={"resolution_note": "Issue resolved by updating config"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["resolved_at"] is not None
|
||||||
|
assert data["resolution_note"] == "Issue resolved by updating config"
|
||||||
|
|
||||||
|
# Verify task blocker_flag is cleared
|
||||||
|
db.refresh(test_task)
|
||||||
|
assert test_task.blocker_flag is False
|
||||||
|
|
||||||
|
def test_list_blockers(self, client, admin_token, db, test_task):
|
||||||
|
"""Test listing blockers for a task."""
|
||||||
|
blocker = Blocker(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
task_id=test_task.id,
|
||||||
|
reported_by="00000000-0000-0000-0000-000000000001",
|
||||||
|
reason="Test blocker",
|
||||||
|
)
|
||||||
|
db.add(blocker)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.get(
|
||||||
|
f"/api/tasks/{test_task.id}/blockers",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["total"] == 1
|
||||||
|
assert data["blockers"][0]["reason"] == "Test blocker"
|
||||||
|
|
||||||
|
def test_cannot_create_duplicate_active_blocker(self, client, admin_token, db, test_task):
|
||||||
|
"""Test that duplicate active blockers are prevented."""
|
||||||
|
# Create first blocker
|
||||||
|
blocker = Blocker(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
task_id=test_task.id,
|
||||||
|
reported_by="00000000-0000-0000-0000-000000000001",
|
||||||
|
reason="First blocker",
|
||||||
|
)
|
||||||
|
db.add(blocker)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
# Try to create second blocker
|
||||||
|
response = client.post(
|
||||||
|
f"/api/tasks/{test_task.id}/blockers",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
json={"reason": "Second blocker"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "already has an unresolved blocker" in response.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
class TestUserSearch:
|
||||||
|
"""Tests for User Search API."""
|
||||||
|
|
||||||
|
def test_search_users(self, client, admin_token, db):
|
||||||
|
"""Test searching users by name."""
|
||||||
|
# Create test users
|
||||||
|
user1 = User(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
email="john@example.com",
|
||||||
|
name="John Doe",
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
user2 = User(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
email="jane@example.com",
|
||||||
|
name="Jane Doe",
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
db.add_all([user1, user2])
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.get(
|
||||||
|
"/api/users/search?q=Doe",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert len(data) >= 2
|
||||||
|
|
||||||
|
def test_search_users_by_email(self, client, admin_token, db):
|
||||||
|
"""Test searching users by email."""
|
||||||
|
user = User(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
email="searchtest@example.com",
|
||||||
|
name="Search Test",
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
db.add(user)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
response = client.get(
|
||||||
|
"/api/users/search?q=searchtest",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert len(data) >= 1
|
||||||
|
assert any(u["email"] == "searchtest@example.com" for u in data)
|
||||||
218
frontend/src/components/BlockerDialog.tsx
Normal file
218
frontend/src/components/BlockerDialog.tsx
Normal file
@@ -0,0 +1,218 @@
|
|||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import { blockersApi, Blocker } from '../services/collaboration'
|
||||||
|
|
||||||
|
interface BlockerDialogProps {
|
||||||
|
taskId: string
|
||||||
|
taskTitle: string
|
||||||
|
isBlocked: boolean
|
||||||
|
onClose: () => void
|
||||||
|
onBlockerChange: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BlockerDialog({
|
||||||
|
taskId,
|
||||||
|
taskTitle,
|
||||||
|
isBlocked,
|
||||||
|
onClose,
|
||||||
|
onBlockerChange,
|
||||||
|
}: BlockerDialogProps) {
|
||||||
|
const [blockers, setBlockers] = useState<Blocker[]>([])
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [reason, setReason] = useState('')
|
||||||
|
const [resolutionNote, setResolutionNote] = useState('')
|
||||||
|
const [submitting, setSubmitting] = useState(false)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [activeBlocker, setActiveBlocker] = useState<Blocker | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchBlockers = async () => {
|
||||||
|
try {
|
||||||
|
const response = await blockersApi.list(taskId)
|
||||||
|
setBlockers(response.blockers)
|
||||||
|
// Find active blocker (unresolved)
|
||||||
|
const active = response.blockers.find(b => !b.resolved_at)
|
||||||
|
setActiveBlocker(active || null)
|
||||||
|
} catch (err) {
|
||||||
|
setError('Failed to load blockers')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fetchBlockers()
|
||||||
|
}, [taskId])
|
||||||
|
|
||||||
|
const handleCreateBlocker = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!reason.trim()) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
setSubmitting(true)
|
||||||
|
const blocker = await blockersApi.create(taskId, reason)
|
||||||
|
setBlockers(prev => [blocker, ...prev])
|
||||||
|
setActiveBlocker(blocker)
|
||||||
|
setReason('')
|
||||||
|
setError(null)
|
||||||
|
onBlockerChange()
|
||||||
|
} catch (err) {
|
||||||
|
setError('Failed to create blocker')
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleResolveBlocker = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!activeBlocker || !resolutionNote.trim()) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
setSubmitting(true)
|
||||||
|
const updated = await blockersApi.resolve(activeBlocker.id, resolutionNote)
|
||||||
|
setBlockers(prev => prev.map(b => (b.id === updated.id ? updated : b)))
|
||||||
|
setActiveBlocker(null)
|
||||||
|
setResolutionNote('')
|
||||||
|
setError(null)
|
||||||
|
onBlockerChange()
|
||||||
|
} catch (err) {
|
||||||
|
setError('Failed to resolve blocker')
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||||
|
<div className="bg-white rounded-lg shadow-xl w-full max-w-lg max-h-[90vh] overflow-hidden">
|
||||||
|
<div className="p-4 border-b flex justify-between items-center">
|
||||||
|
<h2 className="text-lg font-semibold">
|
||||||
|
{isBlocked ? 'Task Blocked' : 'Mark as Blocked'}
|
||||||
|
</h2>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="text-gray-500 hover:text-gray-700"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-4 overflow-y-auto max-h-[60vh]">
|
||||||
|
<p className="text-gray-600 mb-4">Task: {taskTitle}</p>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="p-2 bg-red-100 text-red-700 rounded text-sm mb-4">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="text-center text-gray-500 py-4">Loading...</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{/* Active blocker */}
|
||||||
|
{activeBlocker && (
|
||||||
|
<div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-4">
|
||||||
|
<h3 className="font-semibold text-red-800 mb-2">
|
||||||
|
Active Blocker
|
||||||
|
</h3>
|
||||||
|
<p className="text-gray-700 mb-2">{activeBlocker.reason}</p>
|
||||||
|
<p className="text-sm text-gray-500">
|
||||||
|
Reported by {activeBlocker.reporter.name} on{' '}
|
||||||
|
{new Date(activeBlocker.created_at).toLocaleString()}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* Resolve form */}
|
||||||
|
<form onSubmit={handleResolveBlocker} className="mt-4">
|
||||||
|
<label className="block text-sm font-medium mb-1">
|
||||||
|
Resolution Note
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
value={resolutionNote}
|
||||||
|
onChange={e => setResolutionNote(e.target.value)}
|
||||||
|
placeholder="Describe how the blocker was resolved..."
|
||||||
|
className="w-full p-2 border rounded resize-none"
|
||||||
|
rows={3}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={submitting || !resolutionNote.trim()}
|
||||||
|
className="mt-2 px-4 py-2 bg-green-600 text-white rounded disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{submitting ? 'Resolving...' : 'Resolve Blocker'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Create blocker form */}
|
||||||
|
{!activeBlocker && (
|
||||||
|
<form onSubmit={handleCreateBlocker} className="mb-4">
|
||||||
|
<label className="block text-sm font-medium mb-1">
|
||||||
|
Blocker Reason
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
value={reason}
|
||||||
|
onChange={e => setReason(e.target.value)}
|
||||||
|
placeholder="Describe what is blocking this task..."
|
||||||
|
className="w-full p-2 border rounded resize-none"
|
||||||
|
rows={3}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={submitting || !reason.trim()}
|
||||||
|
className="mt-2 px-4 py-2 bg-red-600 text-white rounded disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{submitting ? 'Creating...' : 'Mark as Blocked'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* History */}
|
||||||
|
{blockers.filter(b => b.resolved_at).length > 0 && (
|
||||||
|
<div className="mt-4">
|
||||||
|
<h3 className="font-semibold mb-2">Blocker History</h3>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{blockers
|
||||||
|
.filter(b => b.resolved_at)
|
||||||
|
.map(blocker => (
|
||||||
|
<div
|
||||||
|
key={blocker.id}
|
||||||
|
className="bg-gray-50 border rounded p-3 text-sm"
|
||||||
|
>
|
||||||
|
<p className="font-medium">{blocker.reason}</p>
|
||||||
|
<p className="text-gray-500 mt-1">
|
||||||
|
Reported: {blocker.reporter.name} •{' '}
|
||||||
|
{new Date(blocker.created_at).toLocaleDateString()}
|
||||||
|
</p>
|
||||||
|
{blocker.resolver && (
|
||||||
|
<p className="text-green-600 mt-1">
|
||||||
|
Resolved: {blocker.resolver.name} •{' '}
|
||||||
|
{new Date(blocker.resolved_at!).toLocaleDateString()}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{blocker.resolution_note && (
|
||||||
|
<p className="text-gray-600 mt-1 italic">
|
||||||
|
"{blocker.resolution_note}"
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-4 border-t flex justify-end">
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300"
|
||||||
|
>
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
258
frontend/src/components/Comments.tsx
Normal file
258
frontend/src/components/Comments.tsx
Normal file
@@ -0,0 +1,258 @@
|
|||||||
|
import { useState, useEffect, useCallback } from 'react'
|
||||||
|
import { commentsApi, usersApi, Comment, UserSearchResult } from '../services/collaboration'
|
||||||
|
import { useAuth } from '../contexts/AuthContext'
|
||||||
|
|
||||||
|
interface CommentsProps {
|
||||||
|
taskId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Comments({ taskId }: CommentsProps) {
|
||||||
|
const { user } = useAuth()
|
||||||
|
const [comments, setComments] = useState<Comment[]>([])
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [newComment, setNewComment] = useState('')
|
||||||
|
const [submitting, setSubmitting] = useState(false)
|
||||||
|
const [replyTo, setReplyTo] = useState<string | null>(null)
|
||||||
|
const [editingId, setEditingId] = useState<string | null>(null)
|
||||||
|
const [editContent, setEditContent] = useState('')
|
||||||
|
const [mentionSuggestions, setMentionSuggestions] = useState<UserSearchResult[]>([])
|
||||||
|
const [showMentions, setShowMentions] = useState(false)
|
||||||
|
|
||||||
|
const fetchComments = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true)
|
||||||
|
const response = await commentsApi.list(taskId)
|
||||||
|
setComments(response.comments)
|
||||||
|
setError(null)
|
||||||
|
} catch (err) {
|
||||||
|
setError('Failed to load comments')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [taskId])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchComments()
|
||||||
|
}, [fetchComments])
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!newComment.trim() || submitting) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
setSubmitting(true)
|
||||||
|
const comment = await commentsApi.create(taskId, newComment, replyTo || undefined)
|
||||||
|
if (replyTo) {
|
||||||
|
// For replies, we'd need to refresh or update the parent
|
||||||
|
await fetchComments()
|
||||||
|
} else {
|
||||||
|
setComments(prev => [...prev, comment])
|
||||||
|
}
|
||||||
|
setNewComment('')
|
||||||
|
setReplyTo(null)
|
||||||
|
} catch (err) {
|
||||||
|
setError('Failed to post comment')
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleEdit = async (commentId: string) => {
|
||||||
|
if (!editContent.trim()) return
|
||||||
|
try {
|
||||||
|
const updated = await commentsApi.update(commentId, editContent)
|
||||||
|
setComments(prev => prev.map(c => (c.id === commentId ? updated : c)))
|
||||||
|
setEditingId(null)
|
||||||
|
setEditContent('')
|
||||||
|
} catch (err) {
|
||||||
|
setError('Failed to update comment')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (commentId: string) => {
|
||||||
|
if (!confirm('Delete this comment?')) return
|
||||||
|
try {
|
||||||
|
await commentsApi.delete(commentId)
|
||||||
|
await fetchComments()
|
||||||
|
} catch (err) {
|
||||||
|
setError('Failed to delete comment')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleMentionSearch = async (query: string) => {
|
||||||
|
if (query.length < 1) {
|
||||||
|
setMentionSuggestions([])
|
||||||
|
setShowMentions(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const results = await usersApi.search(query)
|
||||||
|
setMentionSuggestions(results)
|
||||||
|
setShowMentions(results.length > 0)
|
||||||
|
} catch {
|
||||||
|
setMentionSuggestions([])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleInputChange = (value: string) => {
|
||||||
|
setNewComment(value)
|
||||||
|
// Check for @mention
|
||||||
|
const atMatch = value.match(/@(\w*)$/)
|
||||||
|
if (atMatch) {
|
||||||
|
handleMentionSearch(atMatch[1])
|
||||||
|
} else {
|
||||||
|
setShowMentions(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const insertMention = (userResult: UserSearchResult) => {
|
||||||
|
const newValue = newComment.replace(/@\w*$/, `@${userResult.name} `)
|
||||||
|
setNewComment(newValue)
|
||||||
|
setShowMentions(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) return <div className="p-4 text-gray-500">Loading comments...</div>
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="font-semibold text-lg">Comments ({comments.length})</h3>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="p-2 bg-red-100 text-red-700 rounded text-sm">{error}</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Comment list */}
|
||||||
|
<div className="space-y-3">
|
||||||
|
{comments.map(comment => (
|
||||||
|
<div key={comment.id} className="border rounded-lg p-3 bg-gray-50">
|
||||||
|
<div className="flex justify-between items-start mb-2">
|
||||||
|
<div>
|
||||||
|
<span className="font-medium">{comment.author.name}</span>
|
||||||
|
<span className="text-gray-500 text-sm ml-2">
|
||||||
|
{new Date(comment.created_at).toLocaleString()}
|
||||||
|
</span>
|
||||||
|
{comment.is_edited && (
|
||||||
|
<span className="text-gray-400 text-xs ml-1">(edited)</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{user?.id === comment.author.id && !comment.is_deleted && (
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setEditingId(comment.id)
|
||||||
|
setEditContent(comment.content)
|
||||||
|
}}
|
||||||
|
className="text-sm text-blue-600 hover:underline"
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(comment.id)}
|
||||||
|
className="text-sm text-red-600 hover:underline"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{editingId === comment.id ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<textarea
|
||||||
|
value={editContent}
|
||||||
|
onChange={e => setEditContent(e.target.value)}
|
||||||
|
className="w-full p-2 border rounded"
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => handleEdit(comment.id)}
|
||||||
|
className="px-3 py-1 bg-blue-600 text-white rounded text-sm"
|
||||||
|
>
|
||||||
|
Save
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setEditingId(null)}
|
||||||
|
className="px-3 py-1 bg-gray-300 rounded text-sm"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className={`whitespace-pre-wrap ${comment.is_deleted ? 'text-gray-400 italic' : ''}`}>
|
||||||
|
{comment.content}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Mentions */}
|
||||||
|
{comment.mentions.length > 0 && (
|
||||||
|
<div className="mt-2 text-sm text-gray-500">
|
||||||
|
Mentioned: {comment.mentions.map(m => m.name).join(', ')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Reply button */}
|
||||||
|
{!comment.is_deleted && (
|
||||||
|
<button
|
||||||
|
onClick={() => setReplyTo(comment.id)}
|
||||||
|
className="text-sm text-blue-600 hover:underline mt-2"
|
||||||
|
>
|
||||||
|
Reply {comment.reply_count > 0 && `(${comment.reply_count})`}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* New comment form */}
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-2">
|
||||||
|
{replyTo && (
|
||||||
|
<div className="flex items-center gap-2 text-sm text-gray-600">
|
||||||
|
<span>Replying to comment</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setReplyTo(null)}
|
||||||
|
className="text-red-600 hover:underline"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="relative">
|
||||||
|
<textarea
|
||||||
|
value={newComment}
|
||||||
|
onChange={e => handleInputChange(e.target.value)}
|
||||||
|
placeholder="Add a comment... Use @name to mention someone"
|
||||||
|
className="w-full p-3 border rounded-lg resize-none"
|
||||||
|
rows={3}
|
||||||
|
/>
|
||||||
|
{/* Mention suggestions dropdown */}
|
||||||
|
{showMentions && (
|
||||||
|
<div className="absolute bottom-full left-0 w-full bg-white border rounded shadow-lg max-h-40 overflow-y-auto">
|
||||||
|
{mentionSuggestions.map(u => (
|
||||||
|
<button
|
||||||
|
key={u.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => insertMention(u)}
|
||||||
|
className="w-full text-left px-3 py-2 hover:bg-gray-100"
|
||||||
|
>
|
||||||
|
<span className="font-medium">{u.name}</span>
|
||||||
|
<span className="text-gray-500 text-sm ml-2">{u.email}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={!newComment.trim() || submitting}
|
||||||
|
className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{submitting ? 'Posting...' : 'Post Comment'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { ReactNode } from 'react'
|
import { ReactNode } from 'react'
|
||||||
import { useNavigate, useLocation } from 'react-router-dom'
|
import { useNavigate, useLocation } from 'react-router-dom'
|
||||||
import { useAuth } from '../contexts/AuthContext'
|
import { useAuth } from '../contexts/AuthContext'
|
||||||
|
import { NotificationBell } from './NotificationBell'
|
||||||
|
|
||||||
interface LayoutProps {
|
interface LayoutProps {
|
||||||
children: ReactNode
|
children: ReactNode
|
||||||
@@ -43,6 +44,7 @@ export default function Layout({ children }: LayoutProps) {
|
|||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
<div style={styles.headerRight}>
|
<div style={styles.headerRight}>
|
||||||
|
<NotificationBell />
|
||||||
<span style={styles.userName}>{user?.name}</span>
|
<span style={styles.userName}>{user?.name}</span>
|
||||||
{user?.is_system_admin && (
|
{user?.is_system_admin && (
|
||||||
<span style={styles.badge}>Admin</span>
|
<span style={styles.badge}>Admin</span>
|
||||||
|
|||||||
155
frontend/src/components/NotificationBell.tsx
Normal file
155
frontend/src/components/NotificationBell.tsx
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
import { useState, useRef, useEffect } from 'react'
|
||||||
|
import { useNotifications } from '../contexts/NotificationContext'
|
||||||
|
|
||||||
|
export function NotificationBell() {
|
||||||
|
const { notifications, unreadCount, loading, fetchNotifications, markAsRead, markAllAsRead } =
|
||||||
|
useNotifications()
|
||||||
|
const [isOpen, setIsOpen] = useState(false)
|
||||||
|
const dropdownRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
|
// Close dropdown when clicking outside
|
||||||
|
useEffect(() => {
|
||||||
|
const handleClickOutside = (event: MouseEvent) => {
|
||||||
|
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||||
|
setIsOpen(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener('mousedown', handleClickOutside)
|
||||||
|
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleOpen = async () => {
|
||||||
|
setIsOpen(!isOpen)
|
||||||
|
if (!isOpen && notifications.length === 0) {
|
||||||
|
await fetchNotifications()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getNotificationIcon = (type: string) => {
|
||||||
|
switch (type) {
|
||||||
|
case 'mention':
|
||||||
|
return '@'
|
||||||
|
case 'assignment':
|
||||||
|
return '👤'
|
||||||
|
case 'blocker':
|
||||||
|
return '🚫'
|
||||||
|
case 'blocker_resolved':
|
||||||
|
return '✅'
|
||||||
|
case 'comment':
|
||||||
|
return '💬'
|
||||||
|
default:
|
||||||
|
return '🔔'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatTime = (dateStr: string) => {
|
||||||
|
const date = new Date(dateStr)
|
||||||
|
const now = new Date()
|
||||||
|
const diffMs = now.getTime() - date.getTime()
|
||||||
|
const diffMins = Math.floor(diffMs / 60000)
|
||||||
|
const diffHours = Math.floor(diffMins / 60)
|
||||||
|
const diffDays = Math.floor(diffHours / 24)
|
||||||
|
|
||||||
|
if (diffMins < 1) return 'Just now'
|
||||||
|
if (diffMins < 60) return `${diffMins}m ago`
|
||||||
|
if (diffHours < 24) return `${diffHours}h ago`
|
||||||
|
if (diffDays < 7) return `${diffDays}d ago`
|
||||||
|
return date.toLocaleDateString()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative" ref={dropdownRef}>
|
||||||
|
<button
|
||||||
|
onClick={handleOpen}
|
||||||
|
className="relative p-2 text-gray-600 hover:text-gray-900 focus:outline-none"
|
||||||
|
aria-label="Notifications"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="w-6 h-6"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
{unreadCount > 0 && (
|
||||||
|
<span className="absolute top-0 right-0 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-white transform translate-x-1/2 -translate-y-1/2 bg-red-600 rounded-full">
|
||||||
|
{unreadCount > 99 ? '99+' : unreadCount}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{isOpen && (
|
||||||
|
<div className="absolute right-0 mt-2 w-80 bg-white rounded-lg shadow-lg border z-50">
|
||||||
|
<div className="p-3 border-b flex justify-between items-center">
|
||||||
|
<h3 className="font-semibold">Notifications</h3>
|
||||||
|
{unreadCount > 0 && (
|
||||||
|
<button
|
||||||
|
onClick={() => markAllAsRead()}
|
||||||
|
className="text-sm text-blue-600 hover:underline"
|
||||||
|
>
|
||||||
|
Mark all read
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="max-h-96 overflow-y-auto">
|
||||||
|
{loading ? (
|
||||||
|
<div className="p-4 text-center text-gray-500">Loading...</div>
|
||||||
|
) : notifications.length === 0 ? (
|
||||||
|
<div className="p-4 text-center text-gray-500">No notifications</div>
|
||||||
|
) : (
|
||||||
|
notifications.map(notification => (
|
||||||
|
<div
|
||||||
|
key={notification.id}
|
||||||
|
onClick={() => !notification.is_read && markAsRead(notification.id)}
|
||||||
|
className={`p-3 border-b cursor-pointer hover:bg-gray-50 ${
|
||||||
|
!notification.is_read ? 'bg-blue-50' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<span className="text-xl">
|
||||||
|
{getNotificationIcon(notification.type)}
|
||||||
|
</span>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="font-medium text-sm truncate">
|
||||||
|
{notification.title}
|
||||||
|
</p>
|
||||||
|
{notification.message && (
|
||||||
|
<p className="text-gray-600 text-sm truncate">
|
||||||
|
{notification.message}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="text-gray-400 text-xs mt-1">
|
||||||
|
{formatTime(notification.created_at)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{!notification.is_read && (
|
||||||
|
<span className="w-2 h-2 bg-blue-600 rounded-full flex-shrink-0 mt-2" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{notifications.length > 0 && (
|
||||||
|
<div className="p-2 border-t text-center">
|
||||||
|
<button
|
||||||
|
onClick={() => fetchNotifications()}
|
||||||
|
className="text-sm text-blue-600 hover:underline"
|
||||||
|
>
|
||||||
|
Refresh
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
191
frontend/src/contexts/NotificationContext.tsx
Normal file
191
frontend/src/contexts/NotificationContext.tsx
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
import { createContext, useContext, useState, useEffect, useCallback, ReactNode, useRef } from 'react'
|
||||||
|
import { notificationsApi, Notification, NotificationListResponse } from '../services/collaboration'
|
||||||
|
|
||||||
|
interface NotificationContextType {
|
||||||
|
notifications: Notification[]
|
||||||
|
unreadCount: number
|
||||||
|
loading: boolean
|
||||||
|
error: string | null
|
||||||
|
fetchNotifications: (isRead?: boolean) => Promise<void>
|
||||||
|
markAsRead: (notificationId: string) => Promise<void>
|
||||||
|
markAllAsRead: () => Promise<void>
|
||||||
|
refreshUnreadCount: () => Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
const NotificationContext = createContext<NotificationContextType | undefined>(undefined)
|
||||||
|
|
||||||
|
const WS_RECONNECT_DELAY = 3000
|
||||||
|
const WS_PING_INTERVAL = 30000
|
||||||
|
|
||||||
|
export function NotificationProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [notifications, setNotifications] = useState<Notification[]>([])
|
||||||
|
const [unreadCount, setUnreadCount] = useState(0)
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const wsRef = useRef<WebSocket | null>(null)
|
||||||
|
const pingIntervalRef = useRef<NodeJS.Timeout | null>(null)
|
||||||
|
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||||
|
|
||||||
|
const refreshUnreadCount = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const count = await notificationsApi.getUnreadCount()
|
||||||
|
setUnreadCount(count)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch unread count:', err)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const fetchNotifications = useCallback(async (isRead?: boolean) => {
|
||||||
|
setLoading(true)
|
||||||
|
setError(null)
|
||||||
|
try {
|
||||||
|
const response: NotificationListResponse = await notificationsApi.list(isRead)
|
||||||
|
setNotifications(response.notifications)
|
||||||
|
setUnreadCount(response.unread_count)
|
||||||
|
} catch (err) {
|
||||||
|
setError('Failed to load notifications')
|
||||||
|
console.error('Failed to fetch notifications:', err)
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const markAsRead = useCallback(async (notificationId: string) => {
|
||||||
|
try {
|
||||||
|
const updated = await notificationsApi.markAsRead(notificationId)
|
||||||
|
setNotifications(prev =>
|
||||||
|
prev.map(n => (n.id === notificationId ? updated : n))
|
||||||
|
)
|
||||||
|
setUnreadCount(prev => Math.max(0, prev - 1))
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to mark as read:', err)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const markAllAsRead = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
await notificationsApi.markAllAsRead()
|
||||||
|
setNotifications(prev =>
|
||||||
|
prev.map(n => ({ ...n, is_read: true, read_at: new Date().toISOString() }))
|
||||||
|
)
|
||||||
|
setUnreadCount(0)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to mark all as read:', err)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
// WebSocket connection
|
||||||
|
const connectWebSocket = useCallback(() => {
|
||||||
|
const token = localStorage.getItem('token')
|
||||||
|
if (!token) return
|
||||||
|
|
||||||
|
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||||
|
const wsUrl = `${wsProtocol}//${window.location.host}/ws/notifications?token=${token}`
|
||||||
|
|
||||||
|
try {
|
||||||
|
const ws = new WebSocket(wsUrl)
|
||||||
|
wsRef.current = ws
|
||||||
|
|
||||||
|
ws.onopen = () => {
|
||||||
|
console.log('WebSocket connected')
|
||||||
|
// Start ping interval
|
||||||
|
pingIntervalRef.current = setInterval(() => {
|
||||||
|
if (ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws.send(JSON.stringify({ type: 'ping' }))
|
||||||
|
}
|
||||||
|
}, WS_PING_INTERVAL)
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
try {
|
||||||
|
const message = JSON.parse(event.data)
|
||||||
|
|
||||||
|
switch (message.type) {
|
||||||
|
case 'notification':
|
||||||
|
// Add new notification to the top
|
||||||
|
setNotifications(prev => [message.data, ...prev])
|
||||||
|
setUnreadCount(prev => prev + 1)
|
||||||
|
break
|
||||||
|
|
||||||
|
case 'unread_count':
|
||||||
|
setUnreadCount(message.data.unread_count)
|
||||||
|
break
|
||||||
|
|
||||||
|
case 'pong':
|
||||||
|
// Pong received, connection is alive
|
||||||
|
break
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to parse WebSocket message:', err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.onclose = () => {
|
||||||
|
console.log('WebSocket disconnected')
|
||||||
|
// Clear ping interval
|
||||||
|
if (pingIntervalRef.current) {
|
||||||
|
clearInterval(pingIntervalRef.current)
|
||||||
|
pingIntervalRef.current = null
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attempt to reconnect after delay
|
||||||
|
reconnectTimeoutRef.current = setTimeout(() => {
|
||||||
|
connectWebSocket()
|
||||||
|
}, WS_RECONNECT_DELAY)
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.onerror = (err) => {
|
||||||
|
console.error('WebSocket error:', err)
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to create WebSocket:', err)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
// Initial fetch and WebSocket connection
|
||||||
|
useEffect(() => {
|
||||||
|
const token = localStorage.getItem('token')
|
||||||
|
if (token) {
|
||||||
|
refreshUnreadCount()
|
||||||
|
connectWebSocket()
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
// Cleanup on unmount
|
||||||
|
if (wsRef.current) {
|
||||||
|
wsRef.current.close()
|
||||||
|
}
|
||||||
|
if (pingIntervalRef.current) {
|
||||||
|
clearInterval(pingIntervalRef.current)
|
||||||
|
}
|
||||||
|
if (reconnectTimeoutRef.current) {
|
||||||
|
clearTimeout(reconnectTimeoutRef.current)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [refreshUnreadCount, connectWebSocket])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<NotificationContext.Provider
|
||||||
|
value={{
|
||||||
|
notifications,
|
||||||
|
unreadCount,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
fetchNotifications,
|
||||||
|
markAsRead,
|
||||||
|
markAllAsRead,
|
||||||
|
refreshUnreadCount,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</NotificationContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useNotifications() {
|
||||||
|
const context = useContext(NotificationContext)
|
||||||
|
if (context === undefined) {
|
||||||
|
throw new Error('useNotifications must be used within a NotificationProvider')
|
||||||
|
}
|
||||||
|
return context
|
||||||
|
}
|
||||||
@@ -3,13 +3,16 @@ import ReactDOM from 'react-dom/client'
|
|||||||
import { BrowserRouter } from 'react-router-dom'
|
import { BrowserRouter } from 'react-router-dom'
|
||||||
import App from './App'
|
import App from './App'
|
||||||
import { AuthProvider } from './contexts/AuthContext'
|
import { AuthProvider } from './contexts/AuthContext'
|
||||||
|
import { NotificationProvider } from './contexts/NotificationContext'
|
||||||
import './index.css'
|
import './index.css'
|
||||||
|
|
||||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
|
<NotificationProvider>
|
||||||
<App />
|
<App />
|
||||||
|
</NotificationProvider>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
</React.StrictMode>,
|
</React.StrictMode>,
|
||||||
|
|||||||
169
frontend/src/services/collaboration.ts
Normal file
169
frontend/src/services/collaboration.ts
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
import api from './api'
|
||||||
|
|
||||||
|
// Types
|
||||||
|
export interface Comment {
|
||||||
|
id: string
|
||||||
|
task_id: string
|
||||||
|
parent_comment_id: string | null
|
||||||
|
content: string
|
||||||
|
is_edited: boolean
|
||||||
|
is_deleted: boolean
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
author: {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
email: string
|
||||||
|
}
|
||||||
|
mentions: Array<{
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
email: string
|
||||||
|
}>
|
||||||
|
reply_count: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CommentListResponse {
|
||||||
|
comments: Comment[]
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Notification {
|
||||||
|
id: string
|
||||||
|
type: 'mention' | 'assignment' | 'blocker' | 'status_change' | 'comment' | 'blocker_resolved'
|
||||||
|
reference_type: string
|
||||||
|
reference_id: string
|
||||||
|
title: string
|
||||||
|
message: string | null
|
||||||
|
is_read: boolean
|
||||||
|
created_at: string
|
||||||
|
read_at: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NotificationListResponse {
|
||||||
|
notifications: Notification[]
|
||||||
|
total: number
|
||||||
|
unread_count: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Blocker {
|
||||||
|
id: string
|
||||||
|
task_id: string
|
||||||
|
reason: string
|
||||||
|
resolution_note: string | null
|
||||||
|
created_at: string
|
||||||
|
resolved_at: string | null
|
||||||
|
reporter: {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
email: string
|
||||||
|
}
|
||||||
|
resolver: {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
email: string
|
||||||
|
} | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BlockerListResponse {
|
||||||
|
blockers: Blocker[]
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserSearchResult {
|
||||||
|
id: string
|
||||||
|
email: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Comments API
|
||||||
|
export const commentsApi = {
|
||||||
|
list: async (taskId: string): Promise<CommentListResponse> => {
|
||||||
|
const response = await api.get<CommentListResponse>(`/tasks/${taskId}/comments`)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
|
||||||
|
listReplies: async (commentId: string): Promise<CommentListResponse> => {
|
||||||
|
const response = await api.get<CommentListResponse>(`/comments/${commentId}/replies`)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
|
||||||
|
create: async (taskId: string, content: string, parentCommentId?: string): Promise<Comment> => {
|
||||||
|
const response = await api.post<Comment>(`/tasks/${taskId}/comments`, {
|
||||||
|
content,
|
||||||
|
parent_comment_id: parentCommentId,
|
||||||
|
})
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
|
||||||
|
update: async (commentId: string, content: string): Promise<Comment> => {
|
||||||
|
const response = await api.put<Comment>(`/comments/${commentId}`, { content })
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
|
||||||
|
delete: async (commentId: string): Promise<void> => {
|
||||||
|
await api.delete(`/comments/${commentId}`)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Notifications API
|
||||||
|
export const notificationsApi = {
|
||||||
|
list: async (isRead?: boolean, limit = 50, offset = 0): Promise<NotificationListResponse> => {
|
||||||
|
const params: Record<string, unknown> = { limit, offset }
|
||||||
|
if (isRead !== undefined) {
|
||||||
|
params.is_read = isRead
|
||||||
|
}
|
||||||
|
const response = await api.get<NotificationListResponse>('/notifications', { params })
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
|
||||||
|
getUnreadCount: async (): Promise<number> => {
|
||||||
|
const response = await api.get<{ unread_count: number }>('/notifications/unread-count')
|
||||||
|
return response.data.unread_count
|
||||||
|
},
|
||||||
|
|
||||||
|
markAsRead: async (notificationId: string): Promise<Notification> => {
|
||||||
|
const response = await api.put<Notification>(`/notifications/${notificationId}/read`)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
|
||||||
|
markAllAsRead: async (): Promise<{ updated_count: number }> => {
|
||||||
|
const response = await api.put<{ updated_count: number }>('/notifications/read-all')
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Blockers API
|
||||||
|
export const blockersApi = {
|
||||||
|
list: async (taskId: string): Promise<BlockerListResponse> => {
|
||||||
|
const response = await api.get<BlockerListResponse>(`/tasks/${taskId}/blockers`)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
|
||||||
|
create: async (taskId: string, reason: string): Promise<Blocker> => {
|
||||||
|
const response = await api.post<Blocker>(`/tasks/${taskId}/blockers`, { reason })
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
|
||||||
|
resolve: async (blockerId: string, resolutionNote: string): Promise<Blocker> => {
|
||||||
|
const response = await api.put<Blocker>(`/blockers/${blockerId}/resolve`, {
|
||||||
|
resolution_note: resolutionNote,
|
||||||
|
})
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
|
||||||
|
get: async (blockerId: string): Promise<Blocker> => {
|
||||||
|
const response = await api.get<Blocker>(`/blockers/${blockerId}`)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// User Search API (for @mention)
|
||||||
|
export const usersApi = {
|
||||||
|
search: async (query: string, limit = 10): Promise<UserSearchResult[]> => {
|
||||||
|
const response = await api.get<UserSearchResult[]>('/users/search', {
|
||||||
|
params: { q: query, limit },
|
||||||
|
})
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
}
|
||||||
125
openspec/changes/archive/2025-12-29-add-collaboration/design.md
Normal file
125
openspec/changes/archive/2025-12-29-add-collaboration/design.md
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
## Context
|
||||||
|
|
||||||
|
協作功能需要整合多個子系統:留言、@提及、阻礙管理、即時通知。這些功能與現有的 Task 模組緊密耦合,且需要引入 WebSocket 即時通訊機制。
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:**
|
||||||
|
- 提供任務內留言討論功能
|
||||||
|
- 實作 @提及與即時通知
|
||||||
|
- 建立阻礙追蹤與主管通知機制
|
||||||
|
- 使用 Redis Pub/Sub 處理即時推播
|
||||||
|
|
||||||
|
**Non-Goals:**
|
||||||
|
- 不實作 Email 通知(未來功能)
|
||||||
|
- 不實作離線訊息佇列
|
||||||
|
- 不實作留言的 Markdown 編輯器(僅純文字)
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
### 1. 留言儲存結構
|
||||||
|
- **決策**: 使用巢狀結構(parent_comment_id)支援回覆
|
||||||
|
- **理由**: 簡單且符合大多數專案管理工具的 UX 模式
|
||||||
|
|
||||||
|
### 2. @提及解析
|
||||||
|
- **決策**: 後端解析留言內容,提取 `@username` 模式並建立 Mention 記錄
|
||||||
|
- **理由**: 前端負責顯示建議,後端負責實際通知邏輯
|
||||||
|
|
||||||
|
### 3. 即時通知架構
|
||||||
|
- **決策**: Redis Pub/Sub + WebSocket (FastAPI WebSocket)
|
||||||
|
- **替代方案**:
|
||||||
|
- Server-Sent Events (SSE) - 單向,不支援雙向互動
|
||||||
|
- Polling - 延遲高,資源浪費
|
||||||
|
- **理由**: WebSocket 提供低延遲雙向通訊,Redis 已在架構中使用
|
||||||
|
|
||||||
|
### 4. 阻礙管理
|
||||||
|
- **決策**: 新增獨立 `pjctrl_blockers` 表記錄阻礙詳情
|
||||||
|
- **理由**: Task 的 `blocker_flag` 只是布林值,需要追蹤原因、處理人、解除說明
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
|
||||||
|
| 風險 | 緩解措施 |
|
||||||
|
|------|----------|
|
||||||
|
| WebSocket 連線管理複雜度 | 使用連線池,實作心跳機制 |
|
||||||
|
| 通知量過大導致效能問題 | 實作批次處理、設定通知合併策略 |
|
||||||
|
| @提及被濫用 | 限制單則留言最多提及 10 人 |
|
||||||
|
|
||||||
|
## Data Model
|
||||||
|
|
||||||
|
```
|
||||||
|
pjctrl_comments
|
||||||
|
├── id: UUID (PK)
|
||||||
|
├── task_id: UUID (FK -> tasks)
|
||||||
|
├── parent_comment_id: UUID (FK -> comments, nullable)
|
||||||
|
├── author_id: UUID (FK -> users)
|
||||||
|
├── content: TEXT
|
||||||
|
├── is_edited: BOOLEAN DEFAULT false
|
||||||
|
├── created_at: TIMESTAMP
|
||||||
|
└── updated_at: TIMESTAMP
|
||||||
|
|
||||||
|
pjctrl_mentions
|
||||||
|
├── id: UUID (PK)
|
||||||
|
├── comment_id: UUID (FK -> comments)
|
||||||
|
├── mentioned_user_id: UUID (FK -> users)
|
||||||
|
└── created_at: TIMESTAMP
|
||||||
|
|
||||||
|
pjctrl_notifications
|
||||||
|
├── id: UUID (PK)
|
||||||
|
├── user_id: UUID (FK -> users)
|
||||||
|
├── type: ENUM('mention', 'assignment', 'blocker', 'status_change', 'comment')
|
||||||
|
├── reference_type: VARCHAR(50)
|
||||||
|
├── reference_id: UUID
|
||||||
|
├── title: VARCHAR(200)
|
||||||
|
├── message: TEXT
|
||||||
|
├── is_read: BOOLEAN DEFAULT false
|
||||||
|
├── created_at: TIMESTAMP
|
||||||
|
└── read_at: TIMESTAMP
|
||||||
|
|
||||||
|
pjctrl_blockers
|
||||||
|
├── id: UUID (PK)
|
||||||
|
├── task_id: UUID (FK -> tasks)
|
||||||
|
├── reported_by: UUID (FK -> users)
|
||||||
|
├── reason: TEXT
|
||||||
|
├── resolved_by: UUID (FK -> users, nullable)
|
||||||
|
├── resolution_note: TEXT
|
||||||
|
├── created_at: TIMESTAMP
|
||||||
|
└── resolved_at: TIMESTAMP
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Design
|
||||||
|
|
||||||
|
```
|
||||||
|
# Comments
|
||||||
|
POST /api/tasks/{task_id}/comments # 新增留言
|
||||||
|
GET /api/tasks/{task_id}/comments # 取得任務留言列表
|
||||||
|
PUT /api/comments/{comment_id} # 編輯留言
|
||||||
|
DELETE /api/comments/{comment_id} # 刪除留言
|
||||||
|
|
||||||
|
# Notifications
|
||||||
|
GET /api/notifications # 取得通知列表
|
||||||
|
PUT /api/notifications/{id}/read # 標記已讀
|
||||||
|
PUT /api/notifications/read-all # 全部已讀
|
||||||
|
GET /api/notifications/unread-count # 取得未讀數量
|
||||||
|
|
||||||
|
# Blockers
|
||||||
|
POST /api/tasks/{task_id}/blockers # 標記阻礙
|
||||||
|
PUT /api/blockers/{blocker_id}/resolve # 解除阻礙
|
||||||
|
GET /api/tasks/{task_id}/blockers # 取得阻礙歷史
|
||||||
|
|
||||||
|
# WebSocket
|
||||||
|
WS /ws/notifications # 即時通知連線
|
||||||
|
|
||||||
|
# User Search (for @mention autocomplete)
|
||||||
|
GET /api/users/search?q={query} # 搜尋使用者
|
||||||
|
```
|
||||||
|
|
||||||
|
## Migration Plan
|
||||||
|
|
||||||
|
1. 新增資料表(無 breaking changes)
|
||||||
|
2. Task model 新增 comments relationship
|
||||||
|
3. User model 新增 notifications relationship
|
||||||
|
4. 前端漸進式整合
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
無(已與現有架構對齊)
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Change: Add Collaboration Features
|
||||||
|
|
||||||
|
## Why
|
||||||
|
專案管理系統需要協作功能,讓團隊成員能在任務內進行討論、標記相關人員,並處理任務阻礙。目前系統缺乏這些核心協作機制,導致使用者仍需依賴 Email 或其他工具進行溝通。
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
- 新增任務留言系統(支援巢狀回覆)
|
||||||
|
- 實作 @提及功能(自動完成 + 即時通知)
|
||||||
|
- 建立阻礙管理機制(標記原因、主管通知、解除追蹤)
|
||||||
|
- 實作即時通知系統(Redis Pub/Sub + WebSocket)
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
- Affected specs: `collaboration`
|
||||||
|
- Affected code:
|
||||||
|
- 新增 models: Comment, Mention, Notification, Blocker
|
||||||
|
- 新增 API routes: `/comments`, `/notifications`
|
||||||
|
- 新增 services: NotificationService, WebSocketManager
|
||||||
|
- 前端: 任務詳情頁新增留言區、通知中心
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Task Comments
|
||||||
|
系統 SHALL 支援任務內部的討論留言,減少 Email 往返。
|
||||||
|
|
||||||
|
#### Scenario: 新增留言
|
||||||
|
- **GIVEN** 使用者擁有任務的存取權限
|
||||||
|
- **WHEN** 使用者在任務中新增留言
|
||||||
|
- **THEN** 系統儲存留言並顯示在討論區
|
||||||
|
- **AND** 記錄留言者與時間戳記
|
||||||
|
|
||||||
|
#### Scenario: 回覆留言
|
||||||
|
- **GIVEN** 任務已有留言
|
||||||
|
- **WHEN** 使用者回覆特定留言
|
||||||
|
- **THEN** 系統建立巢狀回覆結構
|
||||||
|
- **AND** 通知原留言者
|
||||||
|
|
||||||
|
#### Scenario: 編輯留言
|
||||||
|
- **GIVEN** 使用者是留言的作者
|
||||||
|
- **WHEN** 使用者編輯自己的留言
|
||||||
|
- **THEN** 系統更新留言內容
|
||||||
|
- **AND** 標示「已編輯」及編輯時間
|
||||||
|
|
||||||
|
#### Scenario: 刪除留言
|
||||||
|
- **GIVEN** 使用者是留言的作者
|
||||||
|
- **WHEN** 使用者刪除自己的留言
|
||||||
|
- **THEN** 系統移除留言
|
||||||
|
- **AND** 若有回覆則顯示「此留言已刪除」
|
||||||
|
|
||||||
|
### Requirement: User Mentions
|
||||||
|
系統 SHALL 支援 @相關人員 功能,提及時發送即時通知。
|
||||||
|
|
||||||
|
#### Scenario: @提及通知
|
||||||
|
- **GIVEN** 使用者在留言中使用 @username 提及某人
|
||||||
|
- **WHEN** 留言送出
|
||||||
|
- **THEN** 被提及者收到即時通知
|
||||||
|
- **AND** 通知包含任務連結與留言摘要
|
||||||
|
|
||||||
|
#### Scenario: @提及自動完成
|
||||||
|
- **GIVEN** 使用者輸入 @ 符號
|
||||||
|
- **WHEN** 使用者繼續輸入
|
||||||
|
- **THEN** 系統顯示符合的使用者名單供選擇
|
||||||
|
- **AND** 可用鍵盤或滑鼠選擇
|
||||||
|
|
||||||
|
#### Scenario: @提及數量限制
|
||||||
|
- **GIVEN** 使用者在單則留言中提及超過 10 人
|
||||||
|
- **WHEN** 留言送出
|
||||||
|
- **THEN** 系統拒絕並顯示錯誤訊息
|
||||||
|
|
||||||
|
### Requirement: Blocker Management
|
||||||
|
系統 SHALL 提供阻礙 (Blocker) 機制,強制要求主管介入排解。
|
||||||
|
|
||||||
|
#### Scenario: 標記阻礙
|
||||||
|
- **GIVEN** 工程師的任務遇到阻礙無法進行
|
||||||
|
- **WHEN** 工程師將任務標記為 "Blocked"
|
||||||
|
- **THEN** 系統設定 Task.blocker_flag = true
|
||||||
|
- **AND** 建立 Blocker 記錄
|
||||||
|
- **AND** 發送即時通知給該任務所屬專案的 Owner
|
||||||
|
|
||||||
|
#### Scenario: 阻礙原因說明
|
||||||
|
- **GIVEN** 任務被標記為 Blocked
|
||||||
|
- **WHEN** 使用者標記阻礙
|
||||||
|
- **THEN** 系統要求填寫阻礙原因
|
||||||
|
- **AND** 原因顯示在任務詳情與通知中
|
||||||
|
|
||||||
|
#### Scenario: 解除阻礙
|
||||||
|
- **GIVEN** 主管或被指派者處理完阻礙
|
||||||
|
- **WHEN** 使用者解除 Blocked 狀態
|
||||||
|
- **THEN** 系統設定 Task.blocker_flag = false
|
||||||
|
- **AND** 記錄解除時間與處理說明
|
||||||
|
|
||||||
|
### Requirement: Real-time Notifications
|
||||||
|
系統 SHALL 透過 Redis Pub/Sub 與 WebSocket 推播即時通知。
|
||||||
|
|
||||||
|
#### Scenario: 即時通知推播
|
||||||
|
- **GIVEN** 發生需要通知的事件(被指派任務、被 @提及、阻礙標記)
|
||||||
|
- **WHEN** 事件發生
|
||||||
|
- **THEN** 系統透過 WebSocket 即時推播通知給相關使用者
|
||||||
|
- **AND** 未讀通知顯示數量標示
|
||||||
|
|
||||||
|
#### Scenario: 通知已讀標記
|
||||||
|
- **GIVEN** 使用者有未讀通知
|
||||||
|
- **WHEN** 使用者查看通知
|
||||||
|
- **THEN** 系統標記為已讀
|
||||||
|
- **AND** 更新未讀數量
|
||||||
|
|
||||||
|
#### Scenario: 通知清單查詢
|
||||||
|
- **GIVEN** 使用者需要查看歷史通知
|
||||||
|
- **WHEN** 使用者開啟通知中心
|
||||||
|
- **THEN** 系統顯示通知列表(依時間降序)
|
||||||
|
- **AND** 支援分頁與已讀/未讀篩選
|
||||||
|
|
||||||
|
#### Scenario: WebSocket 重連
|
||||||
|
- **GIVEN** 使用者的 WebSocket 連線中斷
|
||||||
|
- **WHEN** 連線恢復
|
||||||
|
- **THEN** 系統自動重新建立連線
|
||||||
|
- **AND** 補送中斷期間的未讀通知
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
## 1. Database Schema
|
||||||
|
|
||||||
|
- [x] 1.1 建立 Comment model (`pjctrl_comments`)
|
||||||
|
- [x] 1.2 建立 Mention model (`pjctrl_mentions`)
|
||||||
|
- [x] 1.3 建立 Notification model (`pjctrl_notifications`)
|
||||||
|
- [x] 1.4 建立 Blocker model (`pjctrl_blockers`)
|
||||||
|
- [x] 1.5 建立 Alembic migration
|
||||||
|
- [x] 1.6 更新 Task model 加入 comments relationship
|
||||||
|
- [x] 1.7 更新 User model 加入 notifications relationship
|
||||||
|
|
||||||
|
## 2. Backend API - Comments
|
||||||
|
|
||||||
|
- [x] 2.1 建立 Comment schemas (request/response)
|
||||||
|
- [x] 2.2 實作 POST `/api/tasks/{task_id}/comments` - 新增留言
|
||||||
|
- [x] 2.3 實作 GET `/api/tasks/{task_id}/comments` - 取得留言列表
|
||||||
|
- [x] 2.4 實作 PUT `/api/comments/{comment_id}` - 編輯留言
|
||||||
|
- [x] 2.5 實作 DELETE `/api/comments/{comment_id}` - 刪除留言
|
||||||
|
- [x] 2.6 實作 @mention 解析邏輯(從留言內容提取 @username)
|
||||||
|
|
||||||
|
## 3. Backend API - Notifications
|
||||||
|
|
||||||
|
- [x] 3.1 建立 Notification schemas
|
||||||
|
- [x] 3.2 實作 NotificationService(建立、發送通知)
|
||||||
|
- [x] 3.3 實作 GET `/api/notifications` - 取得通知列表
|
||||||
|
- [x] 3.4 實作 PUT `/api/notifications/{id}/read` - 標記已讀
|
||||||
|
- [x] 3.5 實作 PUT `/api/notifications/read-all` - 全部已讀
|
||||||
|
- [x] 3.6 實作 GET `/api/notifications/unread-count` - 未讀數量
|
||||||
|
|
||||||
|
## 4. Backend API - Blockers
|
||||||
|
|
||||||
|
- [x] 4.1 建立 Blocker schemas
|
||||||
|
- [x] 4.2 實作 POST `/api/tasks/{task_id}/blockers` - 標記阻礙
|
||||||
|
- [x] 4.3 實作 PUT `/api/blockers/{blocker_id}/resolve` - 解除阻礙
|
||||||
|
- [x] 4.4 實作 GET `/api/tasks/{task_id}/blockers` - 取得阻礙歷史
|
||||||
|
- [x] 4.5 整合阻礙通知(通知專案 Owner)
|
||||||
|
|
||||||
|
## 5. WebSocket Integration
|
||||||
|
|
||||||
|
- [x] 5.1 建立 WebSocket connection manager
|
||||||
|
- [x] 5.2 實作 `/ws/notifications` endpoint
|
||||||
|
- [x] 5.3 整合 Redis Pub/Sub 發布通知
|
||||||
|
- [x] 5.4 實作 WebSocket 認證(JWT token)
|
||||||
|
- [x] 5.5 實作心跳機制(keepalive)
|
||||||
|
|
||||||
|
## 6. Backend API - User Search
|
||||||
|
|
||||||
|
- [x] 6.1 實作 GET `/api/users/search?q={query}` - 使用者搜尋(支援 @mention 自動完成)
|
||||||
|
|
||||||
|
## 7. Frontend - Comments
|
||||||
|
|
||||||
|
- [x] 7.1 建立 CommentList 元件
|
||||||
|
- [x] 7.2 建立 CommentItem 元件(支援巢狀回覆)
|
||||||
|
- [x] 7.3 建立 CommentForm 元件(含 @mention 自動完成)
|
||||||
|
- [x] 7.4 整合至 Task 詳情頁
|
||||||
|
|
||||||
|
## 8. Frontend - Notifications
|
||||||
|
|
||||||
|
- [x] 8.1 建立 NotificationContext(狀態管理)
|
||||||
|
- [x] 8.2 建立 NotificationBell 元件(未讀數量 badge)
|
||||||
|
- [x] 8.3 建立 NotificationList 元件
|
||||||
|
- [x] 8.4 建立 NotificationItem 元件
|
||||||
|
- [x] 8.5 整合 WebSocket 連線
|
||||||
|
|
||||||
|
## 9. Frontend - Blockers
|
||||||
|
|
||||||
|
- [x] 9.1 建立 BlockerDialog 元件(標記阻礙表單)
|
||||||
|
- [x] 9.2 建立 BlockerHistory 元件
|
||||||
|
- [x] 9.3 整合至 Task 詳情頁
|
||||||
|
|
||||||
|
## 10. Testing
|
||||||
|
|
||||||
|
- [x] 10.1 Comment API 單元測試
|
||||||
|
- [x] 10.2 Notification API 單元測試
|
||||||
|
- [x] 10.3 Blocker API 單元測試
|
||||||
|
- [x] 10.4 WebSocket 連線測試
|
||||||
|
- [x] 10.5 @mention 解析測試
|
||||||
Reference in New Issue
Block a user