All files / src/pages/AcquirerPortal/LegalDocuments/LegalDocumentDetail LegalDocumentDetailPage.tsx

96.06% Statements 122/127
90% Branches 81/90
93.33% Functions 28/30
97.41% Lines 113/116

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 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414                                                                          6x     288x 287x 287x 287x 287x   287x 287x 287x   287x           287x 287x     287x   287x 287x 287x         287x 287x 287x 287x           287x 199x         287x             287x   287x       287x 287x 287x         287x 287x 82x 58x 24x 18x                   287x 287x 40x 40x 40x 2x         287x 287x 287x 46x 46x 46x 46x     287x 6x       6x                     287x 287x 52x 12x 12x 12x 12x 12x         287x   287x 35x     252x           252x               252x           252x 9x   9x           7x 1x 1x     6x         252x 5x     5x       5x 5x 5x           252x 5x 5x       1x   4x     252x 6x 3x                       1x     1x       3x   3x     252x                   14x 3x 3x 3x                 11x 2x   9x       252x   252x       4x 4x       4x 4x                   4x 1x   3x       252x       252x 3x     252x 2x   1x     252x                                                                                                                                                          
import { useEffect, useRef, useState } from "react";
import { Box } from "@mui/material";
import {
  Navigate,
  useNavigate,
  useParams,
  useSearchParams,
} from "react-router-dom";
import NiceModal from "@ebay/nice-modal-react";
import { EditorState, convertToRaw } from "draft-js";
import { useAppTheme } from "@theme/v2/Provider";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import LoadingSpinner from "@components/Snipper/LoadingSpinner";
import { ACQUIRER_PATHS } from "@routes/paths";
import DocumentBanner from "./components/DocumentBanner";
import DocumentContent from "./components/DocumentContent";
import DocumentScrollRegion from "./components/DocumentScrollRegion";
import DocumentViewer from "./components/DocumentViewer";
import DocumentEditor from "./components/DocumentEditor";
import HistorySidePanel from "./components/HistorySidePanel";
import MobileFooter from "./components/MobileFooter";
import {
  useLegalDocument,
  useDocumentVersion,
  useListLegalDocuments,
} from "../api/useLegalDocuments";
import {
  useOpenDraft,
  useSaveDraft,
  useRestoreVersion,
} from "../api/useLegalDocumentMutations";
import { useDocumentLock } from "../api/useDocumentLock";
import PublishModal from "../modals/PublishModal";
import { GIVE_CONFIRMATION_POP_UP } from "modals/modal_names";
import { rawContentEquals } from "./contentDirty";
import type { DocumentState, DocumentVersion } from "../types";
 
const HEARTBEAT_INTERVAL_MS = 30_000;
 
export default function LegalDocumentDetailPage() {
  const { id } = useParams<{ id: string }>();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { isMobileView } = useCustomThemeV2();
  const { palette } = useAppTheme();
 
  const documentID = id ? Number(id) : undefined;
  const versionParam = searchParams.get("version");
  const isViewingPrevious = !!versionParam;
 
  const listPath = `/${ACQUIRER_PATHS.ACQUIRER}/${ACQUIRER_PATHS.SETTINGS}/${ACQUIRER_PATHS.LEGAL_DOCUMENTS}`;
 
  const {
    data: baseDoc,
    isLoading: isLoadingBase,
    isError: isErrorBase,
  } = useLegalDocument(documentID);
  const { data: versionDoc, isLoading: isLoadingVersion } = useDocumentVersion(
    isViewingPrevious ? versionParam ?? undefined : undefined,
  );
  const { data: list } = useListLegalDocuments();
 
  const openDraft = useOpenDraft();
  const saveDraft = useSaveDraft(documentID ?? 0);
  const restore = useRestoreVersion(documentID ?? 0);
 
  // The read endpoint only ever returns the published version — the editable
  // draft is returned solely by the draft-open mutation (which is idempotent,
  // so clicking Edit resumes an existing draft). Prefer the opened draft.
  const openedDraft = openDraft.data;
  const doc = isViewingPrevious ? versionDoc : openedDraft ?? baseDoc;
  const listRow = list?.find((row) => row.documentID === documentID);
  const canEdit = listRow?.canEdit ?? true;
 
  // A draft already exists for this document when the list carries a separate
  // draft row for it. Only then does clicking Edit resume it (POST); with no
  // draft we enter edit mode locally and defer creation until the user actually
  // saves — so viewing-then-leaving never leaves a phantom empty draft behind.
  const hasExistingDraft = !!list?.some(
    (row) => row.documentID === documentID && row.isDraft,
  );
 
  // Local edit intent. Lets us show the editor before any draft is persisted;
  // `doc.isDraft` still drives edit mode once a draft is opened/resumed.
  const [isEditing, setIsEditing] = useState(false);
 
  // Local edit intent engages edit mode even while viewing a previous version —
  // that is how "Edit Version" edits the SELECTED version in place (doc stays
  // versionDoc) without eagerly creating a draft. A server draft (doc.isDraft)
  // only ever exists off the published head, so it is gated to the non-previous
  // view.
  const isEditMode = isEditing || (!isViewingPrevious && !!doc?.isDraft);
 
  const lock = useDocumentLock(documentID, {
    enabled: !isViewingPrevious && !isEditMode,
  });
 
  const [editorState, setEditorState] = useState<EditorState | null>(null);
  const [isDirty, setIsDirty] = useState(false);
  const [isHistoryOpen, setIsHistoryOpen] = useState(false);
 
  // The content the editor was seeded with, so a no-op onChange (mount echo)
  // isn't mistaken for an edit. Captured once on entering edit mode and
  // advanced on each successful save.
  const baselineContentRef = useRef<unknown>(null);
  useEffect(() => {
    if (!isEditMode) {
      baselineContentRef.current = null;
    } else if (baselineContentRef.current === null) {
      baselineContentRef.current = doc?.content ?? null;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isEditMode, doc?.content]);
 
  // Leaving a previous-version view (Back button, or a browser back) ends any
  // in-place deferred edit of that version: with no draft materialised there is
  // nothing to keep, so drop the local edit intent rather than strand the user
  // in the editor on the published document. Once a draft has been opened,
  // edit mode is held by the draft (not this flag), so this leaves it untouched.
  const wasViewingPreviousRef = useRef(isViewingPrevious);
  useEffect(() => {
    const wasViewingPrevious = wasViewingPreviousRef.current;
    wasViewingPreviousRef.current = isViewingPrevious;
    if (wasViewingPrevious && !isViewingPrevious && !openedDraft) {
      setIsEditing(false);
    }
  }, [isViewingPrevious, openedDraft]);
 
  // Measure the sticky banner so the editor toolbar can float just beneath it.
  const bannerRef = useRef<HTMLDivElement>(null);
  const [bannerHeight, setBannerHeight] = useState(0);
  useEffect(() => {
    const measure = () => setBannerHeight(bannerRef.current?.offsetHeight ?? 0);
    measure();
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, [isEditMode, isMobileView]);
 
  const handleEditorChange = (state: EditorState) => {
    setEditorState(state);
    // Only a genuine divergence from the seeded content counts as a change —
    // the editor re-emitting its initial state (or an edit reverted back to the
    // original) leaves nothing to save and must not create a draft.
    setIsDirty(
      !rawContentEquals(
        convertToRaw(state.getCurrentContent()),
        baselineContentRef.current,
      ),
    );
  };
 
  // The edit-lock is acquired as a side effect of opening the draft, so there is
  // nothing to keep alive or release until a draft actually exists. Hold it
  // alive only from that point; release it on exit.
  const hasDraft = !!openedDraft || !!doc?.isDraft;
  useEffect(() => {
    if (!isEditMode || !hasDraft) return;
    lock.sendHeartbeat();
    const interval = setInterval(() => lock.sendHeartbeat(), HEARTBEAT_INTERVAL_MS);
    return () => {
      clearInterval(interval);
      lock.release();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isEditMode, hasDraft]);
 
  const isLoading = isViewingPrevious ? isLoadingVersion : isLoadingBase;
 
  if (isLoading) {
    return <LoadingSpinner />;
  }
 
  Iif (isErrorBase || !doc || !documentID) {
    return <Navigate to={listPath} replace />;
  }
 
  // Editing (including an in-place edit of a previous version) takes precedence
  // over the read-only "previous" badge, so the banner shows the draft controls.
  const state: DocumentState = isEditMode
    ? "draft"
    : isViewingPrevious
      ? "previous"
      : "published";
 
  // The version highlighted in the history timeline: the one in the URL when
  // viewing a previous publication, otherwise the current published version.
  const activeVersionID = isViewingPrevious
    ? Number(versionParam)
    : doc.versionID;
 
  // The draft (and its edit-lock) is only created here — never on entering edit
  // mode. Returns the draft to persist against; resumes/creates it as needed.
  const ensureDraft = async (): Promise<DocumentVersion> => {
    Iif (openedDraft) return openedDraft;
    // Defensive: if a read ever hands back a draft directly, use it as-is.
    if (doc.isDraft) return doc as DocumentVersion;
    // Deferred edit of a previous version: branch the draft from THAT version
    // (restore), then resume it (draft-open is create-or-resume) so the
    // edit-lock and draft state settle exactly as the published path does.
    // Deferring the restore to the first save is what keeps "view an old
    // version and leave without editing" from leaving a phantom draft behind.
    if (isViewingPrevious) {
      await restore.mutateAsync({ versionID: doc.versionID });
      return openDraft.mutateAsync(documentID);
    }
    // Deferred path (published head): no draft yet — create one now.
    return openDraft.mutateAsync(documentID);
  };
 
  // PATCHes the editor's current content onto an already-ensured draft. Shared
  // by Save Draft and Publish so the typed content is persisted before either.
  const persistDraftContent = (onSuccess?: () => void) => {
    const content = editorState
      ? convertToRaw(editorState.getCurrentContent())
      : doc.content;
    saveDraft.mutate(
      { content },
      {
        onSuccess: () => {
          baselineContentRef.current = content;
          setIsDirty(false);
          onSuccess?.();
        },
      },
    );
  };
 
  const doSaveDraft = async (options?: { onSuccess?: () => void }) => {
    try {
      await ensureDraft();
    } catch {
      // Draft-open failed (e.g. another user holds the lock, 409) — the
      // mutation's onError already surfaced it; don't attempt the save.
      return;
    }
    persistDraftContent(options?.onSuccess);
  };
 
  const handleBack = () => {
    if (isEditMode && isDirty) {
      NiceModal.show(GIVE_CONFIRMATION_POP_UP, {
        modalType: "success",
        title: "Save as Draft",
        description: `Do you want to save ${doc.name} changes as draft? If you don't save it any information added will be lost.`,
        customSubmitBtnText: "Yes, Save",
        customCancelBtnText: "Don't Save",
        cancelSx: { color: palette.primitive?.error[100] },
        // Backdrop/X-close only dismisses the guard; leaving is explicit via
        // "Don't Save".
        useDefaultOnClose: true,
        actions: {
          handleSuccess: {
            onClick: () => doSaveDraft({ onSuccess: () => navigate(-1) }),
          },
          handleCancel: {
            onClick: () => navigate(-1),
          },
        },
      });
      return;
    }
    navigate(-1);
  };
 
  const handleEdit = () => {
    // Editing a previous version engages edit mode on THAT version in place —
    // no draft is created here. `doc` is already the selected version while
    // viewing a previous publication, so the editor seeds from its content, and
    // the draft is branched from it (restore) only on the first save (see
    // ensureDraft). Deferring is what keeps "view an old version and leave
    // without editing" from leaving a phantom draft behind — a phantom draft
    // would block restoring/editing another version (one draft per document).
    // Close the history panel so its "Edit Version" footer isn't shown while
    // already editing.
    if (isViewingPrevious) {
      setIsEditing(true);
      setIsHistoryOpen(false);
      return;
    }
    // Resume an existing draft (loads its content + re-takes the lock). Until the
    // list resolves we can't tell whether a draft exists, so resume rather than
    // defer: a deferred edit seeds the editor from the *published* version, and
    // saving it would overwrite an existing draft's content. Only once the list
    // is loaded and carries no draft row do we enter edit mode locally and defer
    // creation until the first save — so viewing-then-leaving leaves no phantom
    // draft. (The resume POST is create-or-resume, so it's safe when unknown.)
    if (hasExistingDraft || list === undefined) {
      openDraft.mutate(documentID);
    } else {
      setIsEditing(true);
    }
  };
 
  const handleSaveDraft = () => doSaveDraft();
 
  const handlePublish = async () => {
    // A draft must exist before it can be published; create it now if the user
    // went straight from Edit to Publish without saving.
    let draft: DocumentVersion;
    try {
      draft = await ensureDraft();
    } catch {
      return;
    }
    const openPublishModal = () =>
      NiceModal.show(PublishModal, {
        documentID,
        name: draft.name,
        version: draft.version,
        showSendNotification: !!draft.isNotifiable,
        listPath,
      });
    // Publish only sends version/date/notify, so it copies whatever content is
    // already on the draft. Persist unsaved edits first (Edit → type → Publish
    // without Save) or they'd be silently dropped; open the modal once saved.
    if (isDirty) {
      persistDraftContent(openPublishModal);
    } else {
      openPublishModal();
    }
  };
 
  const handleViewHistory = () => setIsHistoryOpen((prev) => !prev);
 
  // Keep the panel open while switching versions — the content updates behind
  // the inline timeline (matches the design).
  const handleSelectVersion = (selectedVersionID: number) => {
    navigate(`${listPath}/${documentID}?version=${selectedVersionID}`);
  };
 
  const handleRestore = () =>
    restore.mutate(
      { versionID: doc.versionID },
      { onSuccess: () => navigate(`${listPath}/${documentID}`) },
    );
 
  return (
    <Box
      sx={{
        paddingTop: "0",
        width: "100%",
        minHeight: "100vh",
        backgroundColor: palette.background.default,
      }}
    >
      <DocumentBanner
        ref={bannerRef}
        name={doc.name}
        version={doc.version}
        state={state}
        canEdit={canEdit}
        isLockedByOther={lock.isLockedByOther}
        lockedByName={lock.lock?.lockedByName}
        onBack={handleBack}
        onEdit={handleEdit}
        onSaveDraft={handleSaveDraft}
        onPublish={handlePublish}
        onViewHistory={handleViewHistory}
        onRestore={handleRestore}
        isSaving={saveDraft.isLoading}
        isEditLoading={openDraft.isLoading}
        isRestoring={restore.isLoading}
      />
 
      <Box
        sx={{
          display: "flex",
          flexDirection: "row",
          width: "100%",
          position: "relative",
        }}
      >
        <DocumentScrollRegion bannerHeight={bannerHeight}>
          <DocumentContent hasMobileFooter={isEditMode && isMobileView}>
            {isEditMode ? (
              <DocumentEditor
                content={doc.content}
                onChange={handleEditorChange}
                // Desktop scrolls inside DocumentScrollRegion, so the toolbar
                // sticks to the region's own top; mobile still scrolls the
                // page and needs the banner offset.
                stickyTop={isMobileView ? bannerHeight : 0}
              />
            ) : (
              <DocumentViewer content={doc.content} />
            )}
          </DocumentContent>
        </DocumentScrollRegion>
 
        <HistorySidePanel
          open={isHistoryOpen}
          onClose={() => setIsHistoryOpen(false)}
          documentID={documentID}
          activeVersionID={activeVersionID}
          onSelectVersion={handleSelectVersion}
          onEdit={handleEdit}
          editDisabled={!canEdit || lock.isLockedByOther}
          // Editing a previous version restores it into a draft first, so the
          // "Edit Version" button must reflect the restore round-trip too.
          isEditLoading={openDraft.isLoading || restore.isLoading}
          bannerHeight={bannerHeight}
        />
      </Box>
 
      {isEditMode && isMobileView && (
        <MobileFooter
          onSaveDraft={handleSaveDraft}
          onPublish={handlePublish}
        />
      )}
    </Box>
  );
}