Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

17.0 KB
Raw Blame
import React, { useState, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import {
  Stack,
  Card,
  Text,
  Badge,
  Group,
  Loader,
  Alert,
  TextInput,
  FileInput,
  Select,
} from "@mantine/core";
import { Button } from "@editor/ui/Button";
import { useParticipantSession } from "@editor/hooks/workflow/useParticipantSession";
import { Icon } from "@editor/ui/Icon";
import { PrivateContent } from "@editor/components/shared/PrivateContent";
import { privateContentClassName } from "@editor/components/shared/privateContentClassName";
import { uploadSafeFormData } from "@editor/utils/inMemoryUpload";
interface ParticipantViewProps {
  token: string;
}

const ParticipantView: React.FC<ParticipantViewProps> = ({ token }) => {
  const { t } = useTranslation();
  const {
    session,
    participant,
    loading,
    error,
    submitSignature,
    decline,
    downloadDocument,
  } = useParticipantSession(token);

  const [certType, setCertType] = useState<string>("P12");
  const [password, setPassword] = useState<string>("");
  const [certFile, setCertFile] = useState<File | null>(null);
  const [location, setLocation] = useState<string>("");
  const [reason, setReason] = useState<string>(() =>
    t("workflow.participant.defaultReason", "Document Signing"),
  );
  const [showSignature, _setShowSignature] = useState<boolean>(true);
  const [pageNumber, setPageNumber] = useState<number>(1);
  const [declineReason, _setDeclineReason] = useState<string>("");
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const [notification, setNotification] = useState<{
    type: "success" | "error";
    message: string;
  } | null>(null);

  type CertValidationState =
    | { status: "idle" }
    | { status: "validating" }
    | { status: "valid"; notAfter: string | null; subjectName: string | null }
    | { status: "error"; message: string };

  const [certValidation, setCertValidation] = useState<CertValidationState>({
    status: "idle",
  });
  const validationTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (certType === "SERVER" || !certFile) {
      setCertValidation({ status: "idle" });
      return;
    }

    if (validationTimerRef.current) clearTimeout(validationTimerRef.current);
    setCertValidation({ status: "validating" });

    validationTimerRef.current = setTimeout(async () => {
      try {
        const formData = new FormData();
        formData.append("participantToken", token);
        formData.append("certType", certType);
        formData.append("password", password);
        if (certType === "JKS") {
          formData.append("jksFile", certFile);
        } else {
          formData.append("p12File", certFile);
        }

        const res = await fetch(
          "/api/v1/workflow/participant/validate-certificate",
          {
            method: "POST",
            body: await uploadSafeFormData(formData),
          },
        );
        const data = await res.json();

        if (data.valid) {
          setCertValidation({
            status: "valid",
            notAfter: data.notAfter,
            subjectName: data.subjectName,
          });
        } else {
          setCertValidation({
            status: "error",
            message:
              data.error ??
              t(
                "certSign.collab.participant.certInvalidFallback",
                "Invalid certificate",
              ),
          });
        }
      } catch {
        setCertValidation({
          status: "error",
          message: t(
            "certSign.collab.participant.certNetworkError",
            "Could not validate certificate",
          ),
        });
      }
    }, 600);

    return () => {
      if (validationTimerRef.current) clearTimeout(validationTimerRef.current);
    };
  }, [certFile, password, certType, token]);

  const handleSubmitSignature = async () => {
    if (!certFile && certType !== "SERVER") {
      setNotification({
        type: "error",
        message: t(
          "workflow.participant.selectCertificateFile",
          "Please select a certificate file",
        ),
      });
      return;
    }

    setIsSubmitting(true);
    setNotification(null);
    try {
      await submitSignature({
        participantToken: token,
        certType,
        password,
        p12File: certType === "P12" ? certFile || undefined : undefined,
        jksFile: certType === "JKS" ? certFile || undefined : undefined,
        showSignature,
        pageNumber,
        location,
        reason,
        showLogo: true,
      });
      setNotification({
        type: "success",
        message: t(
          "workflow.participant.submitSuccess",
          "Signature submitted successfully!",
        ),
      });
    } catch (err: unknown) {
      setNotification({
        type: "error",
        message: t(
          "workflow.participant.submitFailed",
          "Failed to submit signature: {{error}}",
          {
            error: err instanceof Error ? err.message : String(err),
          },
        ),
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDecline = async () => {
    if (
      window.confirm(
        t(
          "workflow.participant.declineConfirm",
          "Are you sure you want to decline signing this document?",
        ),
      )
    ) {
      setNotification(null);
      try {
        await decline(token, declineReason || "Declined by participant");
        setNotification({
          type: "success",
          message: t(
            "workflow.participant.declineSuccess",
            "You have declined this signing request.",
          ),
        });
      } catch (err: unknown) {
        setNotification({
          type: "error",
          message: t(
            "workflow.participant.declineFailed",
            "Failed to decline: {{error}}",
            {
              error: err instanceof Error ? err.message : String(err),
            },
          ),
        });
      }
    }
  };

  if (loading && !session) {
    return (
      <Stack align="center" justify="center" p="xl">
        <Loader size="lg" />
        <Text c="dimmed">
          {t("workflow.participant.loadingSession", "Loading session...")}
        </Text>
      </Stack>
    );
  }

  if (error) {
    return (
      <Alert
        icon={<Icon name="info" size={20} />}
        color="red"
        title={t("workflow.participant.errorTitle", "Error")}
      >
        {error}
      </Alert>
    );
  }

  if (!session || !participant) {
    return (
      <Alert icon={<Icon name="info" size={20} />} color="orange">
        {t(
          "workflow.participant.sessionNotFound",
          "Session not found or access denied.",
        )}
      </Alert>
    );
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "SIGNED":
        return (
          <Badge color="green">
            {t("workflow.participant.statusSigned", "Signed")}
          </Badge>
        );
      case "DECLINED":
        return (
          <Badge color="red">
            {t("workflow.participant.statusDeclined", "Declined")}
          </Badge>
        );
      case "VIEWED":
        return (
          <Badge color="blue">
            {t("workflow.participant.statusViewed", "Viewed")}
          </Badge>
        );
      case "NOTIFIED":
        return (
          <Badge color="yellow">
            {t("workflow.participant.statusNotified", "Notified")}
          </Badge>
        );
      case "PENDING":
        return (
          <Badge color="gray">
            {t("workflow.participant.statusPending", "Pending")}
          </Badge>
        );
      default:
        return <Badge>{status}</Badge>;
    }
  };

  const canSign =
    !participant.hasCompleted &&
    !participant.isExpired &&
    session.status === "IN_PROGRESS";

  return (
    <Stack gap="md">
      {notification && (
        <Alert
          icon={
            notification.type === "success" ? (
              <Icon name="circle-check" size={20} />
            ) : (
              <Icon name="info" size={20} />
            )
          }
          color={notification.type === "success" ? "green" : "red"}
          withCloseButton
          onClose={() => setNotification(null)}
        >
          {notification.message}
        </Alert>
      )}
      <Card shadow="sm" padding="md" radius="md" withBorder>
        <Stack gap="sm">
          <Group justify="space-between">
            <div>
              <Text fw={500} size="lg" className={privateContentClassName}>
                {session.documentName}
              </Text>
              <Text size="sm" c="dimmed" className={privateContentClassName}>
                {t("workflow.participant.from", "From: {{name}}", {
                  name: session.ownerUsername,
                })}
              </Text>
            </div>
            {getStatusBadge(participant.status)}
          </Group>

          {session.message && (
            <Alert
              icon={<Icon name="info" size={20} />}
              color="blue"
              variant="light"
            >
              <Text size="sm" className={privateContentClassName}>
                {session.message}
              </Text>
            </Alert>
          )}

          {session.dueDate && (
            <Text size="sm" c="dimmed">
              {t("workflow.participant.dueDate", "Due Date: {{date}}", {
                date: session.dueDate,
              })}
            </Text>
          )}

          <Group gap="xs" mt="sm">
            <Button
              size="sm"
              leftSection={<Icon name="download" size={20} />}
              onClick={() => downloadDocument(token)}
              variant="secondary"
            >
              {t("workflow.participant.downloadDocument", "Download Document")}
            </Button>
          </Group>
        </Stack>
      </Card>

      {canSign && (
        <Card shadow="sm" padding="md" radius="md" withBorder>
          <Stack gap="md">
            <Text fw={500} size="lg">
              {t("workflow.participant.signDocument", "Sign Document")}
            </Text>

            <Select
              label={t(
                "workflow.participant.certificateType",
                "Certificate Type",
              )}
              value={certType}
              onChange={(value) => setCertType(value || "P12")}
              data={[
                {
                  value: "P12",
                  label: t(
                    "workflow.participant.certTypeP12",
                    "P12/PKCS12 Certificate",
                  ),
                },
                {
                  value: "JKS",
                  label: t("workflow.participant.certTypeJks", "JKS Keystore"),
                },
                {
                  value: "SERVER",
                  label: t(
                    "workflow.participant.certTypeServer",
                    "Server Certificate (if available)",
                  ),
                },
              ]}
              size="sm"
              data-testid="cert-type-select"
            />

            {certType !== "SERVER" && (
              <>
                <FileInput
                  label={t(
                    "workflow.participant.certificateFile",
                    "Certificate File",
                  )}
                  placeholder={t(
                    "workflow.participant.certificateFilePlaceholder",
                    "Select certificate file",
                  )}
                  value={certFile}
                  className={privateContentClassName}
                  onChange={setCertFile}
                  accept=".p12,.pfx,.jks"
                  size="sm"
                  data-testid="cert-file-input"
                />

                <TextInput
                  label={t(
                    "workflow.participant.certificatePassword",
                    "Certificate Password",
                  )}
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.currentTarget.value)}
                  size="sm"
                  data-testid="cert-password-input"
                />

                {/* Certificate validation feedback */}
                {certValidation.status === "validating" && (
                  <Text
                    size="sm"
                    c="dimmed"
                    data-testid="cert-validation-feedback"
                  >
                    {t(
                      "certSign.collab.participant.certValidating",
                      "Validating certificate...",
                    )}
                  </Text>
                )}
                {certValidation.status === "valid" && (
                  <Text
                    size="sm"
                    c="var(--color-green-dark)"
                    data-testid="cert-validation-feedback"
                  >
                    {t(
                      "certSign.collab.participant.certValid",
                      "✓ Certificate valid",
                    )}
                    {certValidation.notAfter
                      ? t(
                          "certSign.collab.participant.certValidUntil",
                          " until {{date}}",
                          {
                            date: new Date(
                              certValidation.notAfter,
                            ).toLocaleDateString(),
                          },
                        )
                      : ""}
                    {certValidation.subjectName && (
                      <PrivateContent>
                        {` · ${certValidation.subjectName}`}
                      </PrivateContent>
                    )}
                  </Text>
                )}
                {certValidation.status === "error" && (
                  <Text
                    size="sm"
                    c="var(--color-red-dark)"
                    data-testid="cert-validation-feedback"
                  >
                    {t(
                      "certSign.collab.participant.certInvalid",
                      "✗ {{error}}",
                      { error: certValidation.message },
                    )}
                  </Text>
                )}
              </>
            )}

            <TextInput
              label={t("workflow.participant.location", "Location")}
              placeholder={t(
                "workflow.participant.locationPlaceholder",
                "e.g., San Francisco, CA",
              )}
              value={location}
              className={privateContentClassName}
              onChange={(e) => setLocation(e.currentTarget.value)}
              size="sm"
            />

            <TextInput
              label={t("workflow.participant.reason", "Reason")}
              placeholder={t(
                "workflow.participant.reasonPlaceholder",
                "e.g., Document approval",
              )}
              value={reason}
              className={privateContentClassName}
              onChange={(e) => setReason(e.currentTarget.value)}
              size="sm"
            />

            <TextInput
              label={t(
                "workflow.participant.pageNumber",
                "Page Number (optional)",
              )}
              type="number"
              value={pageNumber}
              onChange={(e) =>
                setPageNumber(parseInt(e.currentTarget.value) || 1)
              }
              size="sm"
              min={1}
            />

            <Group gap="xs">
              <Button
                leftSection={<Icon name="circle-check" size={20} />}
                onClick={handleSubmitSignature}
                loading={isSubmitting}
                disabled={
                  isSubmitting || certValidation.status === "validating"
                }
                accent="success"
                data-testid="submit-signature-button"
              >
                {t("workflow.participant.submitSignature", "Submit Signature")}
              </Button>

              <Button
                leftSection={<Icon name="circle-x" size={20} />}
                onClick={handleDecline}
                variant="secondary"
                accent="danger"
                data-testid="decline-button"
              >
                {t("workflow.participant.decline", "Decline")}
              </Button>
            </Group>
          </Stack>
        </Card>
      )}

      {participant.hasCompleted && (
        <Alert icon={<Icon name="circle-check" size={20} />} color="green">
          {participant.status === "SIGNED"
            ? t(
                "workflow.participant.completedSigned",
                "You have signed this document.",
              )
            : t(
                "workflow.participant.completedDeclined",
                "You have declined this document.",
              )}
        </Alert>
      )}

      {participant.isExpired && (
        <Alert icon={<Icon name="info" size={20} />} color="orange">
          {t(
            "workflow.participant.accessExpired",
            "Your access to this document has expired.",
          )}
        </Alert>
      )}
    </Stack>
  );
};

export default ParticipantView;