Skip to content

feat: allow tagging in incident comments #4669

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { KeyedMutator } from "swr";
import { useApi } from "@/shared/lib/hooks/useApi";
import { showErrorToast } from "@/shared/ui";
import { AuditEvent } from "@/entities/alerts/model";
import { useUsers } from "@/entities/users/model/useUsers";
import { MentionsInput } from "./MentionsInput";

export function IncidentActivityComment({
incident,
Expand All @@ -16,12 +18,17 @@ export function IncidentActivityComment({
}) {
const [comment, setComment] = useState("");
const api = useApi();
const { data: users = [] } = useUsers();

const onSubmit = useCallback(async () => {
try {
// Extract mentioned users from comment
const mentionedUsers = comment.match(/@([\w.-]+@[\w.-]+)/g)?.map(mention => mention.slice(1)) || [];

await api.post(`/incidents/${incident.id}/comment`, {
status: incident.status,
comment,
mentioned_users: mentionedUsers,
});
toast.success("Comment added!", { position: "top-right" });
setComment("");
Expand Down Expand Up @@ -53,10 +60,11 @@ export function IncidentActivityComment({

return (
<div className="flex h-full w-full relative items-center">
<TextInput
<MentionsInput
value={comment}
onValueChange={setComment}
placeholder="Add a new comment..."
users={users}
placeholder="Add a new comment... Use @ to mention users"
/>
<Button
color="orange"
Expand Down
153 changes: 153 additions & 0 deletions keep-ui/app/(keep)/incidents/[id]/activity/ui/MentionsInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { User } from "@/app/(keep)/settings/models";
import { useEffect, useRef, useState } from "react";
import { TextInput } from "@tremor/react";

interface MentionsInputProps {
value: string;
onValueChange: (value: string) => void;
users: User[];
placeholder?: string;
}

interface SuggestionState {
isOpen: boolean;
query: string;
index: number;
startPosition: number;
}

export function MentionsInput({
value,
onValueChange,
users,
placeholder,
}: MentionsInputProps) {
const [suggestion, setSuggestion] = useState<SuggestionState>({
isOpen: false,
query: "",
index: 0,
startPosition: 0,
});

const inputRef = useRef<HTMLInputElement>(null);

const filteredUsers = users.filter((user) =>
(user.name?.toLowerCase() || user.email.toLowerCase()).includes(
suggestion.query.toLowerCase()
)
);

const insertMention = (user: User) => {
const before = value.slice(0, suggestion.startPosition);
const after = value.slice(inputRef.current?.selectionStart || 0);
const mention = `@${user.email} `;
onValueChange(before + mention + after);
setSuggestion({ isOpen: false, query: "", index: 0, startPosition: 0 });
};

const handleKeyDown = (event: React.KeyboardEvent) => {
if (!suggestion.isOpen) return;

switch (event.key) {
case "ArrowDown":
event.preventDefault();
setSuggestion((prev) => ({
...prev,
index: (prev.index + 1) % filteredUsers.length,
}));
break;
case "ArrowUp":
event.preventDefault();
setSuggestion((prev) => ({
...prev,
index:
prev.index - 1 < 0 ? filteredUsers.length - 1 : prev.index - 1,
}));
break;
case "Enter":
event.preventDefault();
if (filteredUsers[suggestion.index]) {
insertMention(filteredUsers[suggestion.index]);
}
break;
case "Escape":
setSuggestion({ isOpen: false, query: "", index: 0, startPosition: 0 });
break;
}
};

const handleInput = (newValue: string) => {
onValueChange(newValue);

const cursorPosition = inputRef.current?.selectionStart || 0;
const textBeforeCursor = newValue.slice(0, cursorPosition);
const matches = textBeforeCursor.match(/@([\w\s]*)$/);

if (matches) {
setSuggestion({
isOpen: true,
query: matches[1],
index: 0,
startPosition: cursorPosition - matches[1].length - 1,
});
} else {
setSuggestion({ isOpen: false, query: "", index: 0, startPosition: 0 });
}
};

useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
suggestion.isOpen &&
inputRef.current &&
!inputRef.current.contains(event.target as Node)
) {
setSuggestion({ isOpen: false, query: "", index: 0, startPosition: 0 });
}
};

document.addEventListener("click", handleClickOutside);
return () => document.removeEventListener("click", handleClickOutside);
}, [suggestion.isOpen]);

return (
<div className="relative w-full">
<TextInput
ref={inputRef}
value={value}
onValueChange={handleInput}
placeholder={placeholder}
onKeyDown={handleKeyDown}
/>
{suggestion.isOpen && filteredUsers.length > 0 && (
<div className="absolute z-10 w-64 mt-1 bg-white rounded-md shadow-lg border border-gray-200">
<ul className="py-1">
{filteredUsers.map((user, index) => (
<li
key={user.email}
className={`px-3 py-2 cursor-pointer hover:bg-gray-100 ${suggestion.index === index ? "bg-gray-100" : ""}`}
onClick={() => insertMention(user)}
>
<div className="flex items-center">
{user.picture && (
<img
src={user.picture}
alt={user.name}
className="w-6 h-6 rounded-full mr-2"
/>
)}
<div>
<div className="font-medium">{user.name || user.email}</div>
{user.name && (
<div className="text-sm text-gray-500">{user.email}</div>
)}
</div>
</div>
</li>
))}
</ul>
</div>
)}
</div>
);
}
8 changes: 8 additions & 0 deletions keep/api/models/comment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from typing import List
from pydantic import BaseModel
from keep.api.models.db.incident import IncidentStatus

class IncidentCommentDto(BaseModel):
status: IncidentStatus
comment: str
mentioned_users: List[str] = []
29 changes: 29 additions & 0 deletions keep/api/models/db/comment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from datetime import datetime
from typing import List
from uuid import UUID, uuid4

from sqlalchemy import Column, ForeignKey, Text
from sqlalchemy_utils import UUIDType
from sqlmodel import Field, JSON, SQLModel

from keep.api.models.db.incident import Incident, IncidentStatus


class IncidentComment(SQLModel, table=True):
"""Model for storing incident comments with mentioned users."""
id: UUID = Field(default_factory=uuid4, primary_key=True)
incident_id: UUID = Field(
sa_column=Column(
UUIDType(binary=False),
ForeignKey("incident.id", ondelete="CASCADE"),
index=True,
)
)
status: str = Field(sa_column=Column(Text, nullable=False))
comment: str = Field(sa_column=Column(Text, nullable=False))
mentioned_users: List[str] = Field(default=[], sa_column=Column(JSON))
created_at: datetime = Field(
default_factory=datetime.utcnow,
nullable=False,
)
created_by: str | None = Field(default=None)
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Add incident comments table

Revision ID: add_incident_comments
Revises: 92f4f93f2140
Create Date: 2024-07-29 18:11:00.000000

"""
from typing import List

import sqlalchemy as sa
import sqlmodel
from alembic import op
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy_utils import UUIDType

# revision identifiers, used by Alembic.
revision = "add_incident_comments"
down_revision = "92f4f93f2140"
branch_labels = None
depends_on = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"incident_comment",
sa.Column("id", UUIDType(binary=False), primary_key=True),
sa.Column("incident_id", UUIDType(binary=False), nullable=False),
sa.Column("status", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("comment", sa.Text(), nullable=False),
sa.Column(
"mentioned_users",
sa.JSON(),
nullable=False,
server_default=sa.text("'[]'"),
),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
),
sa.Column("created_by", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.ForeignKeyConstraint(
["incident_id"],
["incident.id"],
ondelete="CASCADE",
),
)
op.create_index(
op.f("ix_incident_comment_incident_id"),
"incident_comment",
["incident_id"],
unique=False,
)


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_incident_comment_incident_id"), table_name="incident_comment")
op.drop_table("incident_comment")
19 changes: 17 additions & 2 deletions keep/api/routes/incidents.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
from keep.identitymanager.identitymanagerfactory import IdentityManagerFactory
from keep.providers.providers_factory import ProvidersFactory
from keep.topologies.topologies_service import TopologiesService # noqa
from keep.api.models.comment import IncidentCommentDto

router = APIRouter()
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -888,7 +889,7 @@ def change_incident_severity(
@router.post("/{incident_id}/comment", description="Add incident audit activity")
def add_comment(
incident_id: UUID,
change: IncidentStatusChangeDto,
change: IncidentCommentDto,
authenticated_entity: AuthenticatedEntity = Depends(
IdentityManagerFactory.get_auth_verifier(["write:incident"])
),
Expand All @@ -899,6 +900,7 @@ def add_comment(
"commenter": authenticated_entity.email,
"comment": change.comment,
"incident_id": str(incident_id),
"mentioned_users": change.mentioned_users,
}
logger.info("Adding comment to incident", extra=extra)
comment = add_audit(
Expand All @@ -910,11 +912,24 @@ def add_comment(
)

if pusher_client:
# Notify about the comment
pusher_client.trigger(
f"private-{authenticated_entity.tenant_id}", "incident-comment", {}
)

# Send notifications to mentioned users
for mentioned_user in change.mentioned_users:
pusher_client.trigger(
f"private-{authenticated_entity.tenant_id}-{mentioned_user}",
"user-mention",
{
"incident_id": str(incident_id),
"comment": change.comment,
"mentioned_by": authenticated_entity.email,
}
)

logger.info("Added comment to incident", extra=extra)
logger.info("Added comment to incident with mentions", extra=extra)
return comment


Expand Down
Loading
Loading