Skip to content

The open alternative to Salesforce, designed for AI.

13.9 KB
Raw Blame
import { SettingsEmptyPlaceholder } from '@/settings/components/SettingsEmptyPlaceholder';
import { SettingsAdminDeleteJobsConfirmationModal } from '@/settings/admin-panel/health-status/components/SettingsAdminDeleteJobsConfirmationModal';
import { SettingsAdminJobDetailsExpandable } from '@/settings/admin-panel/health-status/components/SettingsAdminJobDetailsExpandable';
import { SettingsAdminJobStateBadge } from '@/settings/admin-panel/health-status/components/SettingsAdminJobStateBadge';
import { SettingsAdminQueueJobRowDropdownMenu } from '@/settings/admin-panel/health-status/components/SettingsAdminQueueJobRowDropdownMenu';
import { SettingsAdminRetryJobsConfirmationModal } from '@/settings/admin-panel/health-status/components/SettingsAdminRetryJobsConfirmationModal';
import { useApolloAdminClient } from '@/settings/admin-panel/apollo/hooks/useApolloAdminClient';
import { useDeleteJobs } from '@/settings/admin-panel/health-status/hooks/useDeleteJobs';
import { useRetryJobs } from '@/settings/admin-panel/health-status/hooks/useRetryJobs';
import { Select } from '@/ui/input/components/Select';
import { useDialog } from '@/ui/layout/dialog/hooks/useDialog';
import { Table } from '@/ui/layout/table/components/Table';
import { TableBody } from '@/ui/layout/table/components/TableBody';
import { TableCell } from '@/ui/layout/table/components/TableCell';
import { TableHeader } from '@/ui/layout/table/components/TableHeader';
import { TableRow } from '@/ui/layout/table/components/TableRow';
import { styled } from '@linaria/react';
import { plural } from '@lingui/core/macro';
import { useState } from 'react';
import { IconRefresh, IconTrash } from 'twenty-ui/icon';
import { Button, Checkbox } from 'twenty-ui/primitives/input';
import { themeCssVariables } from 'twenty-ui/theme';
import { useQuery } from '@apollo/client/react';
import {
  JobState,
  type QueueJob,
  GetQueueJobsDocument,
} from '~/generated-admin/graphql';
import { beautifyPastDateRelativeToNow } from '~/utils/date-utils';
import { useLingui } from '@lingui/react/macro';

type SettingsAdminQueueJobsTableProps = {
  queueName: string;
  onRetentionConfigLoaded?: (config: {
    completedMaxAge: number;
    completedMaxCount: number;
    failedMaxAge: number;
    failedMaxCount: number;
  }) => void;
};

const StyledContainer = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${themeCssVariables.spacing[4]};
`;

const StyledControlsContainer = styled.div`
  align-items: center;
  display: flex;
  gap: ${themeCssVariables.spacing[2]};
  justify-content: space-between;
`;

const StyledPaginationContainer = styled.div`
  align-items: center;
  display: flex;
  justify-content: space-between;
  padding: ${themeCssVariables.spacing[2]};
`;

const StyledJobRowWrapper = styled.div`
  display: contents;
`;

const StyledButtonGroup = styled.div`
  display: flex;
  gap: ${themeCssVariables.spacing[2]};
`;

const RETRY_MODAL_ID = 'retry-jobs-modal';
const DELETE_MODAL_ID = 'delete-jobs-modal';
const LIMIT = 50;
const JOB_TABLE_GRID_COLUMNS =
  '32px minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) 32px';

export const SettingsAdminQueueJobsTable = ({
  queueName,
  onRetentionConfigLoaded,
}: SettingsAdminQueueJobsTableProps) => {
  const { t } = useLingui();
  const apolloAdminClient = useApolloAdminClient();
  const [page, setPage] = useState(0);
  const [stateFilter, setStateFilter] = useState<JobState>(JobState.COMPLETED);
  const [expandedJobId, setExpandedJobId] = useState<string | null>(null);
  const [selectedJobIds, setSelectedJobIds] = useState<Set<string>>(new Set());
  const { openDialog } = useDialog();

  const jobStateOptions: { value: JobState; label: string }[] = [
    { value: JobState.COMPLETED, label: t`Completed` },
    { value: JobState.FAILED, label: t`Failed` },
    { value: JobState.ACTIVE, label: t`Active` },
    { value: JobState.WAITING, label: t`Waiting` },
    { value: JobState.DELAYED, label: t`Delayed` },
    { value: JobState.PRIORITIZED, label: t`Prioritized` },
    { value: JobState.WAITING_CHILDREN, label: t`Waiting Children` },
  ];

  const offset = page * LIMIT;

  const { data, loading, refetch } = useQuery(GetQueueJobsDocument, {
    client: apolloAdminClient,
    variables: {
      queueName,
      state: stateFilter,
      limit: LIMIT,
      offset,
    },
    fetchPolicy: 'network-only',
  });

  const { retryJobs, isRetrying } = useRetryJobs({
    queueName,
    onSuccess: () => {
      refetch();
      setSelectedJobIds(new Set());
    },
  });

  const { deleteJobs, isDeleting } = useDeleteJobs({
    queueName,
    onSuccess: () => {
      refetch();
      setSelectedJobIds(new Set());
    },
  });

  const jobs = data?.getQueueJobs?.jobs || [];
  const hasMore = data?.getQueueJobs?.hasMore || false;
  const totalCount = data?.getQueueJobs?.totalCount || 0;
  const failedJobs = jobs.filter((job) => job.state === JobState.FAILED);

  const shouldPassConfig =
    data?.getQueueJobs?.retentionConfig !== undefined &&
    onRetentionConfigLoaded !== undefined;

  if (shouldPassConfig) {
    onRetentionConfigLoaded(data.getQueueJobs.retentionConfig);
  }

  const selectedCount = selectedJobIds.size;
  const allJobsSelected =
    jobs.length > 0 && jobs.every((job) => selectedJobIds.has(job.id));
  const someJobsSelected =
    jobs.some((job) => selectedJobIds.has(job.id)) && !allJobsSelected;

  const selectedJobs = jobs.filter((job) => selectedJobIds.has(job.id));
  const allSelectedAreFailed =
    selectedJobs.length > 0 &&
    selectedJobs.every((job) => job.state === JobState.FAILED);

  const handleToggleAll = () => {
    const shouldClearSelection = allJobsSelected === true;

    if (shouldClearSelection) {
      setSelectedJobIds(new Set());
    } else {
      setSelectedJobIds(new Set(jobs.map((job) => job.id)));
    }
  };

  const handleToggleJob = (event: React.MouseEvent, jobId: string) => {
    event.stopPropagation();
    const newSelected = new Set(selectedJobIds);

    if (newSelected.has(jobId)) {
      newSelected.delete(jobId);
    } else {
      newSelected.add(jobId);
    }
    setSelectedJobIds(newSelected);
  };

  const handleRetrySelected = () => {
    openDialog(RETRY_MODAL_ID);
  };

  const confirmRetrySelected = async () => {
    const jobIdsToRetry = selectedCount > 0 ? Array.from(selectedJobIds) : [];

    await retryJobs(jobIdsToRetry);
  };

  const handleDeleteSelected = () => {
    openDialog(DELETE_MODAL_ID);
  };

  const confirmDeleteSelected = async () => {
    await deleteJobs(Array.from(selectedJobIds));
  };

  const handleRetryOne = async (jobId: string) => {
    await retryJobs([jobId]);
  };

  const handleDeleteOne = async (jobId: string) => {
    await deleteJobs([jobId]);
  };

  const handleRowClick = (jobId: string) => {
    setExpandedJobId(expandedJobId === jobId ? null : jobId);
  };

  const formatTimestampRelative = (timestamp?: number | null) => {
    if (!timestamp) return '-';

    return beautifyPastDateRelativeToNow(timestamp);
  };

  const formatTimestampFull = (timestamp?: number | null) => {
    if (!timestamp) return '';

    return new Date(timestamp).toLocaleString();
  };

  return (
    <StyledContainer>
      <StyledControlsContainer>
        <Select
          dropdownId="job-state-filter"
          value={stateFilter}
          options={jobStateOptions}
          onChange={(value) => {
            setStateFilter(value as JobState);
            setPage(0);
            setSelectedJobIds(new Set());
          }}
          selectSizeVariant="small"
        />
        <StyledButtonGroup>
          {selectedCount > 0 && (
            <Button
              startIcon={<IconTrash />}
              onClick={handleDeleteSelected}
              disabled={isDeleting || loading}
              size="sm"
              variant="outline"
              color="danger"
            >
              {plural(selectedCount, {
                one: `Delete ${selectedCount} Job`,
                other: `Delete ${selectedCount} Jobs`,
              })}
            </Button>
          )}
          {allSelectedAreFailed && (
            <Button
              startIcon={<IconRefresh />}
              onClick={handleRetrySelected}
              disabled={isRetrying || loading}
              size="sm"
              variant="outline"
            >
              {plural(selectedCount, {
                one: `Retry ${selectedCount} Job`,
                other: `Retry ${selectedCount} Jobs`,
              })}
            </Button>
          )}
          {failedJobs.length > 0 && selectedCount === 0 && (
            <Button
              startIcon={<IconRefresh />}
              onClick={handleRetrySelected}
              disabled={isRetrying || loading}
              size="sm"
              variant="outline"
            >{t`Retry All Failed`}</Button>
          )}
        </StyledButtonGroup>
      </StyledControlsContainer>

      {loading && jobs.length === 0 ? (
        <SettingsEmptyPlaceholder>{t`Loading jobs...`}</SettingsEmptyPlaceholder>
      ) : jobs.length === 0 ? (
        <SettingsEmptyPlaceholder>{t`No jobs found`}</SettingsEmptyPlaceholder>
      ) : (
        <>
          <Table>
            <TableRow gridTemplateColumns={JOB_TABLE_GRID_COLUMNS}>
              <TableHeader
                align="center"
                padding={`0 ${themeCssVariables.spacing[1]} 0 ${themeCssVariables.spacing[2]}`}
              >
                {jobs.length > 0 && (
                  <Checkbox
                    checked={allJobsSelected}
                    indeterminate={someJobsSelected}
                    onCheckedChange={() => handleToggleAll()}
                  />
                )}
              </TableHeader>
              <TableHeader>{t`Job Name`}</TableHeader>
              <TableHeader>{t`State`}</TableHeader>
              <TableHeader align="right">{t`Timestamp`}</TableHeader>
              <TableHeader></TableHeader>
            </TableRow>
            <TableBody>
              {jobs.map((job: QueueJob) => {
                const isExpanded = expandedJobId === job.id;
                const isSelected = selectedJobIds.has(job.id);

                return (
                  <StyledJobRowWrapper key={job.id}>
                    <TableRow
                      gridTemplateColumns={JOB_TABLE_GRID_COLUMNS}
                      onClick={() => handleRowClick(job.id)}
                      isExpanded={isExpanded}
                      cursor="pointer"
                      hoverBackgroundColor={
                        themeCssVariables.background.transparent.light
                      }
                    >
                      <TableCell
                        align="center"
                        padding={`0 0 0 ${themeCssVariables.spacing[1]}`}
                        onClick={(e) => {
                          e.stopPropagation();
                          handleToggleJob(e, job.id);
                        }}
                      >
                        <Checkbox checked={isSelected} />
                      </TableCell>
                      <TableCell
                        color={themeCssVariables.font.color.primary}
                        title={job.name}
                        maxWidth="200px"
                        overflow="hidden"
                        textOverflow="ellipsis"
                        whiteSpace="nowrap"
                      >
                        {job.name}
                      </TableCell>
                      <TableCell>
                        <SettingsAdminJobStateBadge
                          state={job.state}
                          attemptsMade={job.attemptsMade}
                        />
                      </TableCell>
                      <TableCell
                        align="right"
                        title={formatTimestampFull(
                          job.finishedOn || job.processedOn || job.timestamp,
                        )}
                      >
                        {formatTimestampRelative(
                          job.finishedOn || job.processedOn || job.timestamp,
                        )}
                      </TableCell>
                      <TableCell onClick={(e) => e.stopPropagation()}>
                        <SettingsAdminQueueJobRowDropdownMenu
                          jobId={job.id}
                          jobState={job.state}
                          onRetry={
                            job.state === JobState.FAILED
                              ? () => handleRetryOne(job.id)
                              : undefined
                          }
                          onDelete={() => handleDeleteOne(job.id)}
                        />
                      </TableCell>
                    </TableRow>
                    <SettingsAdminJobDetailsExpandable
                      job={job}
                      isExpanded={isExpanded}
                    />
                  </StyledJobRowWrapper>
                );
              })}
            </TableBody>
          </Table>

          <StyledPaginationContainer>
            <Button
              onClick={() => setPage((p) => Math.max(0, p - 1))}
              disabled={page === 0 || loading}
              size="sm"
              variant="outline"
            >{t`Previous`}</Button>
            <div>
              {t`Page`} {page + 1} {totalCount > 0 ? t`of` : ''}{' '}
              {totalCount > 0 ? Math.max(1, Math.ceil(totalCount / LIMIT)) : ''}
            </div>
            <Button
              onClick={() => setPage((p) => p + 1)}
              disabled={!hasMore || loading}
              size="sm"
              variant="outline"
            >{t`Next`}</Button>
          </StyledPaginationContainer>
        </>
      )}

      <SettingsAdminRetryJobsConfirmationModal
        modalInstanceId={RETRY_MODAL_ID}
        jobCount={selectedCount > 0 ? selectedCount : failedJobs.length}
        onConfirm={confirmRetrySelected}
      />
      <SettingsAdminDeleteJobsConfirmationModal
        modalInstanceId={DELETE_MODAL_ID}
        jobCount={selectedCount}
        onConfirm={confirmDeleteSelected}
      />
    </StyledContainer>
  );
};