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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions comments/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Iterable

from django.db.models import Q, QuerySet
from django.utils import timezone

from comments.models import Comment
from projects.permissions import ObjectPermission
Expand Down Expand Up @@ -56,10 +57,16 @@ def comment_extract_user_mentions(
ObjectPermission.CURATOR
)
):
now = timezone.now()
query |= Q(
pk__in=User.objects.filter(
forecast__post=comment.on_post
).distinct("pk")
forecast__post=comment.on_post,
)
.exclude(
forecast__end_time__isnull=False,
forecast__end_time__lte=now,
)
.distinct("pk")
)
continue

Expand Down
1 change: 1 addition & 0 deletions front_end/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@
"estimatedReadingTime": "{minutes} min read",
"predictions": "Predictions",
"predictors": "Predictors",
"predictorsMentionWarning": "Only curators and admins can notify @predictors. Your mention will not send notifications.",
"relativeLog": "Relative Log",
"unreadAll": "all unread",
"questionsLeft": "{count, plural, =1 {1 question left} other {{count} questions left} }",
Expand Down
19 changes: 18 additions & 1 deletion front_end/src/components/comment_feed/comment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import Link from "next/link";
import { useTranslations } from "next-intl";
import { FC, useCallback, useEffect, useMemo, useRef, useState } from "react";

import toast from "react-hot-toast";

import { softDeleteUserAction } from "@/app/(main)/accounts/profile/actions";
import { useCommentsFeed } from "@/app/(main)/components/comments_feed_provider";
import KeyFactorsAddInComment from "@/app/(main)/questions/[id]/components/key_factors/add_in_comment/key_factors_add_in_comment";
Expand Down Expand Up @@ -49,7 +51,7 @@ import {
} from "@/types/post";
import { QuestionType } from "@/types/question";
import { sendAnalyticsEvent } from "@/utils/analytics";
import { parseUserMentions } from "@/utils/comments";
import { hasPredictorsMention, parseUserMentions } from "@/utils/comments";
import cn from "@/utils/core/cn";
import { logError } from "@/utils/core/errors";
import { isForecastActive } from "@/utils/forecasts/helpers";
Expand Down Expand Up @@ -520,6 +522,19 @@ const Comment: FC<CommentProps> = ({
if (response && "errors" in response) {
setErrorMessage(response.errors as ErrorResponse);
} else {
// Warn non-curators/admins if they used @predictors
const userPermission = postData?.user_permission;
if (
hasPredictorsMention(parsedMarkdown) &&
(!userPermission ||
![
ProjectPermissions.CURATOR,
ProjectPermissions.ADMIN,
].includes(userPermission))
) {
toast(t("predictorsMentionWarning"));
}

setCommentMarkdown(parsedMarkdown);
setComments((prev) =>
updateCommentTextInTree(prev, comment.id, parsedMarkdown)
Expand Down Expand Up @@ -853,6 +868,8 @@ const Comment: FC<CommentProps> = ({
saveEditDraftDebounced(val);
}}
withUgcLinks
withUserMentions
userPermission={postData?.user_permission}
withCodeBlocks
/>
{hadForecastAtCommentCreation && postData?.question && (
Expand Down
15 changes: 14 additions & 1 deletion front_end/src/components/comment_feed/comment_editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { MDXEditorMethods } from "@mdxeditor/editor";
import { useTranslations } from "next-intl";
import { FC, useCallback, useEffect, useRef, useState } from "react";

import toast from "react-hot-toast";

import { createComment } from "@/app/(main)/questions/actions";
import MarkdownEditor from "@/components/markdown_editor";
import Button from "@/components/ui/button";
Expand All @@ -19,7 +21,7 @@ import { CommentType } from "@/types/comment";
import { ErrorResponse } from "@/types/fetch";
import { ProjectPermissions } from "@/types/post";
import { sendAnalyticsEvent } from "@/utils/analytics";
import { parseComment } from "@/utils/comments";
import { hasPredictorsMention, parseComment } from "@/utils/comments";

import { validateComment } from "./validate_comment";

Expand Down Expand Up @@ -166,6 +168,17 @@ const CommentEditor: FC<CommentEditorProps> = ({

stopAndDiscardDraft();

// Warn non-curators/admins if they used @predictors
if (
hasPredictorsMention(parsedMarkdown) &&
(!userPermission ||
![ProjectPermissions.CURATOR, ProjectPermissions.ADMIN].includes(
userPermission
))
) {
toast(t("predictorsMentionWarning"));
}

setHasIncludedForecast(false);
markdownRef.current = "";
setHasContent(false);
Expand Down
14 changes: 14 additions & 0 deletions front_end/src/utils/comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,20 @@ export function parseUserMentions(
return markdown;
}

/**
* Checks if a comment text contains an @predictors mention.
*/
export function hasPredictorsMention(text: string): boolean {
const mentions = text.matchAll(userTagPattern);
for (const match of mentions) {
const username = (match[1] || match[2] || "").toLowerCase();
if (username === "predictors") {
return true;
}
}
return false;
}

/**
* Returns commentId to focus on if id is provided and comment is not already rendered
*/
Expand Down
43 changes: 43 additions & 0 deletions tests/unit/test_comments/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
from datetime import timedelta

import pytest
import re

from django.utils import timezone

from comments.utils import (
USERNAME_PATTERN,
get_mention_for_user,
Expand Down Expand Up @@ -150,3 +154,42 @@ def test_comment_extract_user_mentions(

assert {x.username for x in qs} == expected_usernames
assert mentions == expected_mentions


@pytest.mark.django_db
def test_predictors_mention_excludes_withdrawn_forecasts(question_binary):
"""@predictors should only notify users with active (non-withdrawn) predictions."""
active_forecaster = factory_user(username="active_forecaster")
withdrawn_forecaster = factory_user(username="withdrawn_forecaster")
admin = factory_user(username="admin")

post = factory_post(
question=question_binary,
default_project=factory_project(
type=Project.ProjectTypes.TOURNAMENT,
default_permission=ObjectPermission.FORECASTER,
override_permissions={
admin: ObjectPermission.ADMIN,
},
),
)

# Active forecast (no end_time)
factory_forecast(question=question_binary, author=active_forecaster)
# Withdrawn forecast (end_time in the past)
factory_forecast(
question=question_binary,
author=withdrawn_forecaster,
end_time=timezone.now() - timedelta(days=1),
)

qs, mentions = comment_extract_user_mentions(
factory_comment(
author=admin,
on_post=post,
text_original="Wanna mention @predictors",
)
)

assert {x.username for x in qs} == {"active_forecaster"}
assert mentions == {"predictors"}
Loading