All files / pages ChatHistoryPage.jsx

100% Statements 72/72
100% Branches 64/64
100% Functions 26/26
100% Lines 71/71

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388                          1x 1x   1x 64x 64x 64x   64x 64x 64x   64x                         64x 64x   123x 123x       64x 1x                         64x 1x             1x 1x 1x         64x 1x             1x 1x 1x         64x 2x 1x       64x 8x 8x 8x     64x 4x         3x 3x     1x           64x 1x     64x 2x                   2x                   64x   3x         64x 45x 38x     7x   3x 1x               7x 7x   7x 7x       64x   62x 3x   59x             64x 64x   64x           1x                                                                                                               39x                                                                                 8x               2x                                                           1x 1x                                   4x                 1x 1x                                                        
import React, { useEffect, useRef, useState } from "react";
import { Button, Spinner, Modal, Form } from "react-bootstrap";
import { useParams, useNavigate } from "react-router";
import { useInfiniteQuery } from "react-query";
import axios from "axios";
import { toast } from "react-toastify";
 
import BasicLayout from "main/layouts/BasicLayout/BasicLayout";
import ChatMessageDisplay from "main/components/Chat/ChatMessageDisplay";
import ChatMessageCreate from "main/components/Chat/ChatMessageCreate";
import { useBackendMutation } from "main/utils/useBackend";
import { useBackend } from "main/utils/useBackend";
 
const PAGE_SIZE = 25;
const REFRESH_RATE = 2000;
 
const ChatHistoryPage = ({ readOnly = false, isAdmin = false }) => {
  const { gameId } = useParams();
  const navigate = useNavigate();
  const loadMoreRef = useRef(null);
 
  const [showCooldownModal, setShowCooldownModal] = useState(false);
  const [selectedUser, setSelectedUser] = useState(null);
  const [cooldownDuration, setCooldownDuration] = useState(10);
 
  const { data: farmerList } = useBackend(
    [`/api/farmer/game/all?gameId=${gameId}`],
    {
      method: "GET",
      url: "/api/farmer/game/all",
      params: {
        gameId: gameId,
      },
    },
    [],
    { refetchInterval: REFRESH_RATE, enabled: !!gameId },
  );
 
  const hasValidFarmer = Array.isArray(farmerList);
  const userIdToUsername = hasValidFarmer
    ? farmerList.reduce((acc, user) => {
        acc[user.userId] = user.username || "";
        return acc;
      }, {})
    : {};
 
  const deleteMutation = useBackendMutation(
    (id) => ({
      url: "/api/chat/hide",
      method: "PUT",
      params: { chatMessageId: id },
    }),
    {
      onSuccess: () => {
        // React Query will refetch automatically if keys match
      },
    },
    [`/api/chat/admin/get?gameId=${gameId}`], // IMPORTANT
  );
 
  const cooldownMutation = useBackendMutation(
    ({ userId, durationMinutes }) => ({
      url: "/api/admin/users/cooldown",
      method: "POST",
      params: { userId, durationMinutes },
    }),
    {
      onSuccess: () => {
        toast("Chat cooldown applied successfully.");
        setShowCooldownModal(false);
        setSelectedUser(null);
      },
    },
  );
 
  const clearCooldownMutation = useBackendMutation(
    ({ userId }) => ({
      url: "/api/admin/users/cooldown/clear",
      method: "POST",
      params: { userId },
    }),
    {
      onSuccess: () => {
        toast("Chat cooldown cleared successfully.");
        setShowCooldownModal(false);
        setSelectedUser(null);
      },
    },
  );
 
  const handleDelete = (id) => {
    if (window.confirm("Delete this message?")) {
      deleteMutation.mutate(id);
    }
  };
 
  const openCooldownModal = (userId, username) => {
    setSelectedUser({ userId, username });
    setCooldownDuration(10);
    setShowCooldownModal(true);
  };
 
  const applyCooldown = () => {
    if (
      !selectedUser ||
      !Number.isInteger(Number(cooldownDuration)) ||
      Number(cooldownDuration) <= 0
    ) {
      toast("Please enter a positive number of minutes.");
      return;
    }
 
    cooldownMutation.mutate({
      userId: selectedUser.userId,
      durationMinutes: Number(cooldownDuration),
    });
  };
 
  const clearCooldown = () => {
    clearCooldownMutation.mutate({ userId: selectedUser.userId });
  };
 
  const fetchChatPage = async ({ pageParam = 0 }) => {
    const response = await axios.get(
      isAdmin ? "/api/chat/admin/get" : "/api/chat/get",
      {
        params: {
          gameId,
          page: pageParam,
          size: PAGE_SIZE,
        },
      },
    );
    return response.data;
  };
 
  const {
    data,
    status,
    fetchNextPage,
    hasNextPage,
    isFetching,
    isFetchingNextPage,
  } = useInfiniteQuery(["chatHistory", gameId], fetchChatPage, {
    getNextPageParam: (lastPage, pages) =>
      lastPage?.last === false ? pages.length : undefined,
    refetchInterval: REFRESH_RATE,
    enabled: !!gameId,
  });
 
  useEffect(() => {
    if (!hasNextPage) {
      return;
    }
 
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasNextPage && !isFetchingNextPage) {
          fetchNextPage();
        }
      },
      {
        threshold: 1.0,
      },
    );
 
    const currentRef = loadMoreRef.current;
    observer.observe(currentRef);
 
    return () => {
      observer.unobserve(currentRef);
    };
  }, [fetchNextPage, hasNextPage, isFetchingNextPage]);
 
  const messages = Array.isArray(data?.pages)
    ? data.pages.flatMap((page) => {
        if (!page || !Array.isArray(page.content)) {
          return [];
        }
        return page.content.map((message) => ({
          ...message,
          username: userIdToUsername[message.userId],
        }));
      })
    : [];
 
  const isInitialLoading = status === "loading";
  const showError = status === "error";
 
  return (
    <BasicLayout>
      <div className="pt-3" data-testid="ChatHistoryPage">
        <Button
          variant="secondary"
          className="mb-3"
          onClick={() => navigate(-1)}
          data-testid="ChatHistoryPage-back"
        >
          Back
        </Button>
        <div className="d-flex flex-column mb-3">
          <div className="d-flex justify-content-between align-items-center">
            <span className="text-muted">
              Game #{gameId} {readOnly && "• Admin Read Only"}
            </span>
            <span className="text-muted">Game #{gameId}</span>
          </div>
 
          {isAdmin && (
            <div className="text-muted mt-1" style={{ fontSize: "0.9rem" }}>
              <span style={{ color: "red", fontWeight: "bold" }}>🚫</span> =
              Deleted Message
            </div>
          )}
        </div>
 
        {!readOnly && (
          <div className="mb-4">
            <ChatMessageCreate gameId={gameId} />
          </div>
        )}
 
        <div
          style={{
            minHeight: "50vh",
            maxHeight: "70vh",
            overflowY: "auto",
            border: "1px solid #dee2e6",
            borderRadius: "0.5rem",
            padding: "1rem",
            backgroundColor: "white",
          }}
          data-testid="ChatHistoryPage-message-container"
        >
          {isInitialLoading && (
            <div className="text-center my-3">
              <Spinner animation="border" role="status" size="sm" /> Loading
              messages...
            </div>
          )}
          {showError && (
            <div className="text-center text-danger my-3">
              Unable to load chat messages.
            </div>
          )}
          {!isInitialLoading && messages.length === 0 && (
            <div className="text-center text-muted my-3">
              No messages available for this game.
            </div>
          )}
          {messages.map((message) => (
            <div
              key={message.id}
              className="d-flex align-items-start mb-2 border rounded p-2"
              style={
                message.hidden
                  ? {
                      backgroundColor: "#fff5f5",
                      borderLeft: "4px solid red",
                    }
                  : {}
              }
            >
              <div className="flex-grow-1">
                <div
                  style={
                    message.hidden ? { opacity: 0.6, fontStyle: "italic" } : {}
                  }
                >
                  <ChatMessageDisplay message={message} />
                </div>
 
                {message.hidden && (
                  <div
                    className="mt-1"
                    style={{
                      color: "red",
                      fontSize: "0.8rem",
                      fontWeight: "bold",
                    }}
                  >
                    🚫 Message Deleted
                  </div>
                )}
              </div>
 
              {isAdmin && !message.hidden && (
                <div className="d-flex gap-2 ms-2">
                  <button
                    className="btn btn-primary btn-sm"
                    data-testid={`ChatHistoryPage-cooldown-${message.userId}`}
                    onClick={() =>
                      openCooldownModal(message.userId, message.username)
                    }
                  >
                    Cooldown
                  </button>
                  <button
                    className="btn btn-danger btn-sm"
                    data-testid={`ChatHistoryPage-delete-${message.id}`}
                    onClick={() => handleDelete(message.id)}
                  >
                    Delete
                  </button>
                </div>
              )}
            </div>
          ))}
          <div
            ref={loadMoreRef}
            className="text-center text-muted mt-3"
            data-testid="ChatHistoryPage-status"
          >
            {isFetchingNextPage
              ? "Loading more messages..."
              : hasNextPage
                ? "Scroll to load more messages"
                : "[no more messages]"}
          </div>
        </div>
        {isFetching && !isFetchingNextPage && (
          <div className="text-center text-muted mt-2">
            Updating conversation...
          </div>
        )}
 
        {isAdmin && (
          <Modal
            show={showCooldownModal}
            onHide={() => {
              setShowCooldownModal(false);
              setSelectedUser(null);
            }}
            data-testid="ChatHistoryPage-cooldown-modal"
          >
            <Modal.Header closeButton>
              <Modal.Title>Manage Chat Cooldown</Modal.Title>
            </Modal.Header>
            <Modal.Body>
              <p>
                User: <strong>{selectedUser?.username || "Unknown"}</strong>
              </p>
              <Form.Group>
                <Form.Label>Cooldown duration (minutes)</Form.Label>
                <Form.Control
                  type="number"
                  min="1"
                  step="1"
                  value={cooldownDuration}
                  onChange={(event) => setCooldownDuration(event.target.value)}
                  data-testid="ChatHistoryPage-cooldown-duration"
                />
              </Form.Group>
            </Modal.Body>
            <Modal.Footer>
              <Button
                variant="secondary"
                onClick={() => {
                  setShowCooldownModal(false);
                  setSelectedUser(null);
                }}
              >
                Cancel
              </Button>
              <Button
                variant="warning"
                onClick={clearCooldown}
                disabled={!selectedUser}
              >
                Clear Cooldown
              </Button>
              <Button
                variant="primary"
                onClick={applyCooldown}
                disabled={!selectedUser}
              >
                Apply Cooldown
              </Button>
            </Modal.Footer>
          </Modal>
        )}
      </div>
    </BasicLayout>
  );
};
 
export default ChatHistoryPage;