All files / src/app/compliance/_components ClockActions.tsx

34.48% Statements 10/29
40% Branches 18/45
14.28% Functions 1/7
37.03% Lines 10/27

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 1523x                                     43x 43x             43x 43x 43x 43x   43x                                                                                 43x 43x                                                                                                                                                          
"use client";
 
import { fetchApi } from "@/lib/api";
import { useState } from "react";
import { useT } from "@/lib/i18n/translate";
import { shortDate } from "./helpers";
import type { MatrixRow } from "./types";
 
/**
 * The access body's two actions on the Art. 68(4) clock: send the applicant
 * back for the missing items (four weeks), or extend the three months once.
 */
export function ClockActions({
  row,
  onDone,
}: {
  row: MatrixRow;
  onDone: () => Promise<void>;
}) {
  const t = useT("access");
  const [reason, setReason] = useState<string>(
    row.completeness && !row.completeness.complete
      ? `Missing: ${row.completeness.missing
          .map((m) => `(${m.item}) ${m.label}`)
          .join("; ")}`
      : "",
  );
  const [busy, setBusy] = useState<string | null>(null);
  const [msg, setMsg] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  Iif (!row.applicationId) return null;
 
  const act = async (action: "INCOMPLETE" | "EXTEND") => {
    setBusy(action);
    setError(null);
    setMsg(null);
    try {
      const r = await fetchApi("/api/compliance/applications/clock", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          applicationId: row.applicationId,
          action,
          reason,
        }),
      });
      const body = (await r.json().catch(() => ({}))) as Record<
        string,
        unknown
      >;
      if (!r.ok) {
        setError(String(body.error ?? `HTTP ${r.status}`));
        return;
      }
      setMsg(
        action === "EXTEND"
          ? t(
              "Extended once by three months; the decision is now due {date} (Art. 68(4)).",
              { date: shortDate(String(body.decisionDue ?? "")) },
            )
          : t(
              "Applicant notified; the application must be completed by {date}; the three months run again from the complete application (Art. 68(4)).",
              { date: shortDate(String(body.completeBy ?? "")) },
            ),
      );
      await onDone();
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setBusy(null);
    }
  };
 
  const paused = row.clockState === "paused";
  return (
    <div
      className="rounded-lg border border-(--border) bg-(--bg) p-3 space-y-2 text-xs"
      data-testid="clock-actions"
    >
      <div className="font-semibold text-(--text-primary)">
        {t("The clock, Art. 68(4)")}
        <span className="font-normal text-(--text-secondary)">
          {" "}
          ·{" "}
          {paused
            ? t("stopped since {date}: {reason}", {
                date: shortDate(row.incompleteNoticeAt),
                reason: row.incompleteReason ?? t("incomplete"),
              })
            : row.extended
              ? t("extended once: {reason}", {
                  reason: row.extensionReason ?? "",
                })
              : t("running")}
        </span>
      </div>
      <label className="flex flex-col gap-1">
        <span className="text-(--text-secondary)">
          {t("Reasons (what is missing, or why the extension)")}
        </span>
        <textarea
          id={`clock-reason-${row.applicationId}`}
          rows={2}
          value={reason}
          onChange={(e) => setReason(e.target.value)}
          className="rounded-sm border border-(--border) bg-(--surface) px-2 py-1"
        />
      </label>
      <div className="flex flex-wrap gap-2">
        <button
          type="button"
          disabled={busy !== null || paused || !reason.trim()}
          onClick={() => act("INCOMPLETE")}
          className="px-3 py-1.5 rounded-sm font-semibold border border-(--border) disabled:opacity-50"
          title={
            paused
              ? t(
                  "The applicant has already been asked to complete the application",
                )
              : t("Send the applicant back for the missing items; four weeks")
          }
        >
          {busy === "INCOMPLETE" ? t("Notifying…") : t("Notify incomplete")}
        </button>
        <button
          type="button"
          disabled={busy !== null || paused || row.extended || !reason.trim()}
          onClick={() => act("EXTEND")}
          className="px-3 py-1.5 rounded-sm font-semibold border border-(--border) disabled:opacity-50"
          title={
            row.extended
              ? t("Art. 68(4) allows one extension")
              : t("Extend the three months once, by three, with reasons")
          }
        >
          {busy === "EXTEND" ? t("Extending…") : t("Extend by three months")}
        </button>
      </div>
      {error && (
        <p className="text-(--danger-text)" role="alert">
          {error}
        </p>
      )}
      {msg && (
        <p className="text-(--success-text)" role="status">
          {msg}
        </p>
      )}
    </div>
  );
}