Skip to content

Open-source status page, incident response and uptime monitoring

7.2 KB
Raw Blame
"use client";

import type { RouterOutputs } from "@openstatus/api";
import { AI, Check, Copy, Loading } from "@openstatus/icons";
import { Button } from "@openstatus/ui/components/ui/button";
import { useCopyToClipboard } from "@openstatus/ui/hooks/use-copy-to-clipboard";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";

import { StatusDot } from "@/components/common/status-dot";
import {
  Composer,
  ComposerActions,
  ComposerFooter,
  ComposerIconButton,
  ComposerPreview,
  ComposerPreviewToggle,
  ComposerTextarea,
} from "@/components/content/composer";
import {
  EmptyStateContainer,
  EmptyStateDescription,
  EmptyStateTitle,
} from "@/components/content/empty-state";
import { useTRPC } from "@/lib/trpc/client";
import { errorMessage } from "@/lib/trpc/error";

import { ConfirmCloseDialog } from "./confirm-close-dialog";
import { useInvalidateIncident } from "./use-invalidate-incident";

type Incident = NonNullable<RouterOutputs["incident"]["get"]>;

const TEMPLATE = `## Summary

## Impact

## Timeline

## Root cause

## What went well

## What went wrong

## Action items
- [ ] `;

/** The postmortem editor: draft by hand or with the agent, then approve. */
export function IncidentPostmortem({
  incident,
  agentAllowed,
}: {
  incident: Incident;
  agentAllowed: boolean;
}) {
  const trpc = useTRPC();
  const queryClient = useQueryClient();
  const invalidate = useInvalidateIncident(incident.id);
  const { data: postmortem } = useQuery({
    ...trpc.incident.getPostmortem.queryOptions({ id: incident.id }),
    enabled: incident.status === "resolved",
  });
  // null = pristine: the editor follows the server copy, so a background
  // refetch never clobbers unsaved edits.
  const [draft, setDraft] = useState<string | null>(null);
  const [confirmClose, setConfirmClose] = useState(false);
  const { copy, isCopied } = useCopyToClipboard();
  const server = postmortem?.content ?? TEMPLATE;
  const content = draft ?? server;

  const refresh = () =>
    Promise.all([
      queryClient.invalidateQueries({
        queryKey: trpc.incident.getPostmortem.queryKey({ id: incident.id }),
      }),
      invalidate(),
    ]);
  const onError = (error: { message: string }) => {
    toast.error(errorMessage(error));
  };

  const save = useMutation(
    trpc.incident.draftPostmortem.mutationOptions({
      onSuccess: () => {
        toast.success("Postmortem saved");
        return refresh().then(() => setDraft(null));
      },
      onError,
    }),
  );
  const draftWithAgent = useMutation(
    trpc.incident.draftPostmortemWithAgent.mutationOptions({
      onSuccess: () => {
        toast.success("Draft ready");
        return refresh().then(() => setDraft(null));
      },
      onError,
    }),
  );
  const approve = useMutation(
    trpc.incident.approvePostmortem.mutationOptions({
      onSuccess: () => {
        toast.success("Postmortem approved");
        setConfirmClose(false);
        return refresh();
      },
      onError,
    }),
  );

  if (incident.status !== "resolved") {
    return (
      <EmptyStateContainer>
        <EmptyStateTitle>No postmortem yet</EmptyStateTitle>
        <EmptyStateDescription>
          The postmortem opens once the incident is resolved.
        </EmptyStateDescription>
      </EmptyStateContainer>
    );
  }
  // The default tab depends on the server copy; mounting earlier would pin it.
  if (postmortem === undefined) return null;

  const approved = postmortem?.status === "approved";
  const dirty = draft !== null && draft !== server;
  const busy = save.isPending || draftWithAgent.isPending || approve.isPending;
  const canSave = !busy && dirty && content.trim().length > 0;
  const canApprove = postmortem !== null && !approved;

  const showAgent = agentAllowed && !approved;

  const hint = dirty
    ? "Unsaved changes"
    : approved && incident.closedAt === null
      ? "Close the incident from the header"
      : postmortem
        ? null
        : "No postmortem yet";

  return (
    <Composer size="lg" defaultValue={postmortem ? "preview" : "write"}>
      <ComposerTextarea
        aria-label="Postmortem"
        value={content}
        onChange={(e) => setDraft(e.target.value)}
        onSubmit={
          canSave ? () => save.mutate({ id: incident.id, content }) : undefined
        }
      />
      <ComposerPreview value={content} />
      <ComposerFooter>
        {/* px-2 like a ghost control so the dot sits on the text column */}
        <div className="flex items-center gap-2 px-2">
          {postmortem ? (
            <span className="text-foreground flex items-center gap-2 font-mono">
              <StatusDot variant={approved ? "success" : "default"} />
              {approved ? "Approved" : "Draft"}
            </span>
          ) : null}
          {hint ? <span>{hint}</span> : null}
        </div>
        <ComposerActions>
          <div className="flex items-center gap-1">
            <ComposerPreviewToggle />
            {postmortem ? (
              <ComposerIconButton
                label={isCopied ? "Copied" : "Copy markdown"}
                onClick={() =>
                  copy(content, { withToast: "Postmortem copied" })
                }
              >
                {isCopied ? <Check /> : <Copy />}
              </ComposerIconButton>
            ) : null}
            {showAgent ? (
              <ComposerIconButton
                label="Draft with agent"
                disabled={busy}
                onClick={() => draftWithAgent.mutate({ id: incident.id })}
              >
                {draftWithAgent.isPending ? (
                  <Loading className="animate-spin" />
                ) : (
                  <AI />
                )}
              </ComposerIconButton>
            ) : null}
          </div>
          {/* Three verbs that differ in consequence; icons alone would not tell them apart. */}
          <div className="flex items-center gap-2">
            <Button
              size="sm"
              variant={canApprove ? "outline" : "default"}
              disabled={!canSave}
              onClick={() => save.mutate({ id: incident.id, content })}
            >
              Save
            </Button>
            {canApprove ? (
              <>
                <Button
                  size="sm"
                  variant="outline"
                  disabled={busy || dirty}
                  onClick={() => approve.mutate({ id: incident.id })}
                >
                  Approve
                </Button>
                <Button
                  size="sm"
                  disabled={busy || dirty || incident.closedAt !== null}
                  onClick={() => setConfirmClose(true)}
                >
                  Approve & close
                </Button>
                <ConfirmCloseDialog
                  kind="close"
                  open={confirmClose}
                  onOpenChange={setConfirmClose}
                  pending={approve.isPending}
                  onConfirm={() =>
                    approve.mutate({ id: incident.id, close: true })
                  }
                />
              </>
            ) : null}
          </div>
        </ComposerActions>
      </ComposerFooter>
    </Composer>
  );
}