{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "casework-review-decision",
  "title": "Review decision",
  "description": "A review task's decision form and the officer's own draft on it, with a confirm step before anything is sent.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/casework-content",
    "@registrystack/casework-shared",
    "@registrystack/field-renderers",
    "@registrystack/lib-format",
    "@registrystack/ui-button",
    "@registrystack/ui-input",
    "@registrystack/lib-content"
  ],
  "files": [
    {
      "path": "casework/review-decision.tsx",
      "content": "import { useEffect, useState, type ReactNode } from \"react\";\nimport {\n  planReviewResult,\n  rereadsOnRefusal,\n  reviewResultMissing,\n  reviewResultValues,\n  type ReviewDecision,\n  type ReviewJson,\n  type ReviewOutcome,\n  type ReviewResultField,\n  type ReviewResultPlan,\n  type ReviewSettlement,\n  type ReviewTaskDetail,\n} from \"@registrystack/app-runtime\";\nimport {\n  useReviewDraft,\n  useReviewHistory,\n  useReviewPolicies,\n  useSendBack,\n} from \"@registrystack/app-runtime/react\";\nimport { Button } from \"@/components/ui/button\";\nimport { Textarea } from \"@/components/ui/input\";\nimport { InputField } from \"@/blocks/fields/input-field\";\nimport { useCaseworkContent } from \"@/blocks/casework/casework-content\";\nimport {\n  caseworkRefusalText,\n  ErrorSummary,\n  Notice,\n  Unconfirmed,\n} from \"@/blocks/casework/shared\";\nimport { useLocale } from \"@/blocks/lib/content\";\nimport { fill } from \"@/blocks/lib/format\";\n\n/**\n * A task's decision and the officer's own draft on it. The context above them,\n * the hold that lets an officer decide, and the notes and history below stay\n * with the caller; each panel here reads and writes on its own.\n */\n\nconst decisionTypes: Record<ReviewSettlement, ReviewDecision[\"type\"]> = {\n  approved: \"approve\",\n  rejected: \"reject\",\n  changes_requested: \"changes_requested\",\n  answered: \"answer\",\n};\n/** The field id a host validation key names, as this form lays its fields out. */\nfunction fieldId(key: string): string | null {\n  if (key === \"reason\") return \"review-reason\";\n  if (key === \"outcome\") return \"review-outcome\";\n  if (key === \"publicReason\") return \"review-public-reason\";\n  if (key.startsWith(\"result.\")) return `review-result-${key.slice(7)}`;\n  return null;\n}\n\nfunction ResultField({\n  field,\n  value,\n  onChange,\n  error,\n  required,\n}: {\n  field: ReviewResultField;\n  value: string;\n  onChange: (value: string) => void;\n  error?: string;\n  required: boolean;\n}) {\n  const id = `review-result-${field.name}`;\n  const control = field.control;\n  if (control.kind === \"checkbox\")\n    return (\n      <div className=\"field\">\n        <label htmlFor={id}>\n          <input\n            id={id}\n            type=\"checkbox\"\n            checked={value === \"true\"}\n            onChange={(e) => onChange(e.target.checked ? \"true\" : \"false\")}\n          />{\" \"}\n          {field.name}\n        </label>\n      </div>\n    );\n  return (\n    <InputField\n      name={id}\n      label={field.name}\n      value={value}\n      onChange={onChange}\n      error={error}\n      required={required}\n      multiline={control.kind === \"textarea\"}\n      type={\n        control.kind === \"date\"\n          ? \"date\"\n          : control.kind === \"number\"\n            ? \"number\"\n            : \"text\"\n      }\n      {...(control.kind === \"choices\" ? { options: control.options } : {})}\n      {...(control.kind === \"number\"\n        ? {\n            ...(control.min !== undefined ? { min: control.min } : {}),\n            ...(control.max !== undefined ? { max: control.max } : {}),\n            ...(control.step !== undefined ? { step: control.step } : {}),\n          }\n        : {})}\n    />\n  );\n}\n\n/**\n * The reason the requester will see, offered when the chosen outcome asks for\n * or allows one. One line: Casework refuses line breaks in it.\n */\nexport function PublicReasonField({\n  outcome,\n  value,\n  onChange,\n  error,\n}: {\n  outcome: ReviewOutcome | undefined;\n  value: string;\n  onChange: (value: string) => void;\n  error?: string;\n}) {\n  const c = useCaseworkContent();\n  if (!outcome || outcome.publicReason === \"none\") return null;\n  return (\n    <InputField\n      name=\"review-public-reason\"\n      label={c.publicReason}\n      hint={c.publicReasonHint}\n      value={value}\n      required={outcome.publicReason === \"required\"}\n      onChange={onChange}\n      error={error}\n    />\n  );\n}\n\n/**\n * What a confirmed decision led to, read from the decided task's receipt and\n * the history entries recorded at or after the decision: the review moved on,\n * settled, or sent the request back. The decide route confirms only the\n * decision, so a case the reads do not show (an approval that needs more\n * approvals in its stage, a history page not yet loaded) says nothing.\n */\nfunction NextStep({\n  task,\n  stageNames,\n}: {\n  task: ReviewTaskDetail;\n  stageNames: Readonly<Record<string, string>> | undefined;\n}) {\n  const c = useCaseworkContent();\n  const locale = useLocale();\n  const history = useReviewHistory(task.requestId);\n  const policies = useReviewPolicies();\n  const receipt = task.decisionReceipt;\n  if (!receipt) return null;\n  if (receipt.decision === \"changes_requested\")\n    return <Notice tone=\"success\">{c.sentBack}</Notice>;\n  const decidedAt = Date.parse(receipt.decidedAt);\n  const since = new Set(\n    (history.data ?? [])\n      .filter((entry) => Date.parse(entry.occurredAt) >= decidedAt)\n      .map((entry) => entry.kind),\n  );\n  if (since.has(\"stage_advanced\")) {\n    const next = policies.data?.items.find(\n      (policy) => policy.id === task.policy.id,\n    )?.stages[task.stageIndex + 1];\n    const name =\n      next && (stageNames?.[next.id] ?? (next.queueLabel || undefined));\n    return (\n      <Notice tone=\"success\">\n        {name ? fill(c.nextStage, { stage: name }, locale) : c.nextStageUnnamed}\n      </Notice>\n    );\n  }\n  if (since.has(\"review_settled\")) {\n    if (receipt.decision === \"approve\")\n      return <Notice tone=\"success\">{c.settledApproved}</Notice>;\n    if (receipt.decision === \"reject\")\n      return <Notice tone=\"success\">{c.settledRejected}</Notice>;\n  }\n  return null;\n}\n\n/**\n * Where approving leads, read from the task's review policy: on to the next\n * stage, or to the end of the review. A stage that needs more than one\n * approval may stay where it is after this one, so it says nothing there, as\n * it does while the policy is unread or names another stage at this place.\n */\nfunction ApprovalLeadsTo({\n  task,\n  stageNames,\n}: {\n  task: ReviewTaskDetail;\n  stageNames: Readonly<Record<string, string>> | undefined;\n}) {\n  const c = useCaseworkContent();\n  const locale = useLocale();\n  const stages = useReviewPolicies().data?.items.find(\n    (policy) => policy.id === task.policy.id,\n  )?.stages;\n  const stage = stages?.[task.stageIndex];\n  if (!stages || stage?.id !== task.stageId || stage.requiredApprovals > 1)\n    return null;\n  const next = stages[task.stageIndex + 1];\n  if (!next) return <p className=\"muted\">{c.approvesSettles}</p>;\n  const name = stageNames?.[next.id] ?? (next.queueLabel || undefined);\n  return (\n    <p className=\"muted\">\n      {name\n        ? fill(c.approvesToStage, { stage: name }, locale)\n        : c.approvesToStageUnnamed}\n    </p>\n  );\n}\n\n/**\n * A task's decision: the outcome, its reason and result, and the note a\n * send-back or a rejection sends its requester. Fetches its own send-back\n * command from the task id, so the caller supplies only the task and how to\n * read it again.\n */\nexport function DecisionPanel({\n  task,\n  stageNames,\n  reread,\n  rereading,\n}: {\n  task: ReviewTaskDetail;\n  /** Names a stage by its stage id, in the page's wording; a stage with no entry reads as its queue. */\n  stageNames?: Readonly<Record<string, string>>;\n  reread: () => void;\n  rereading: boolean;\n}) {\n  const c = useCaseworkContent();\n  const locale = useLocale();\n  const sendBack = useSendBack(task.taskId);\n  const { decision, note } = sendBack;\n  const [picked, setPicked] = useState(\"\");\n  const [reason, setReason] = useState(\"\");\n  const [publicReason, setPublicReason] = useState(\"\");\n  const [requesterNote, setRequesterNote] = useState(\"\");\n  const [values, setValues] = useState<Record<string, string>>({});\n  const [errors, setErrors] = useState<Record<string, string>>({});\n  const [whole, setWhole] = useState(\"\");\n  const state = decision.state;\n  useEffect(() => {\n    if (rereadsOnRefusal(state)) reread();\n    if (state.state === \"refused\" && state.refusal.kind === \"validation\") {\n      const mapped: Record<string, string> = {};\n      const rest: string[] = [];\n      for (const [key, message] of Object.entries(state.refusal.fields)) {\n        const id = fieldId(key);\n        if (id) mapped[id] = message;\n        else rest.push(message);\n      }\n      setErrors(mapped);\n      setWhole(\n        rest.join(\" \") ||\n          (Object.keys(mapped).length\n            ? \"\"\n            : state.refusal.message || c.caseworkRefusedTitle),\n      );\n    }\n    // A refusal is read once, when it arrives: `state` is only ever replaced\n    // (never mutated) on a genuine transition, so its own identity already\n    // keys each arrival uniquely.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [state.state === \"refused\" ? state : null]);\n\n  // Only an approval review may approve; its approved outcomes come first, and\n  // a single one is the kit's own approve choice.\n  const approvals = task.policy.outcomes.filter(\n    (outcome) => outcome.settlement === \"approved\",\n  );\n  const others = task.policy.outcomes.filter(\n    (outcome) => outcome.settlement !== \"approved\",\n  );\n  const offered: { id: string; label: string; plan: ReviewResultPlan }[] = [\n    ...(task.policy.purpose === \"approval\" ? approvals : []),\n    ...others,\n  ].map((outcome) => ({\n    id: outcome.id,\n    label:\n      outcome.settlement === \"approved\" && approvals.length === 1\n        ? c.approve\n        : outcome.label,\n    plan: planReviewResult(task.policy, outcome.id, task.resultConstraints),\n  }));\n  const blocked = offered.filter((option) => option.plan.blocked);\n  const choices = offered.filter((option) => !option.plan.blocked);\n  // A choice a re-read withdrew or blocked no longer counts as chosen.\n  const chosen = choices.some((option) => option.id === picked) ? picked : \"\";\n  const plan = choices.find((option) => option.id === chosen)?.plan;\n  const approves = plan?.outcome.settlement === \"approved\";\n  const reasonRequired = plan?.reasonRequired ?? false;\n  const publicReasonAsked = plan && plan.outcome.publicReason !== \"none\";\n  // A request sent back for changes carries a note its requester reads. A\n  // rejected one carries none: its requester reads the public reason, which the\n  // outcome may refuse, and a note would give the explanation it withholds.\n  const sendsBack = plan?.outcome.settlement === \"changes_requested\";\n\n  function submit() {\n    const found: Record<string, string> = {};\n    if (!chosen) found[\"review-outcome\"] = c.chooseOutcome;\n    if (reasonRequired && !reason.trim())\n      found[\"review-reason\"] = c.reasonRequired;\n    if (plan?.outcome.publicReason === \"required\" && !publicReason.trim())\n      found[\"review-public-reason\"] = c.publicReasonRequired;\n    if (sendsBack && !requesterNote.trim())\n      found[\"review-requester-note\"] = c.requesterNoteRequired;\n    let result: Record<string, ReviewJson> | undefined;\n    if (plan?.resultDeclared) {\n      const captured = reviewResultValues(plan, values);\n      const given = Object.keys(captured).length > 0;\n      if (plan.resultRequired || given) {\n        for (const name of reviewResultMissing(plan, values))\n          found[`review-result-${name}`] = fill(\n            c.resultMissing,\n            { field: name },\n            locale,\n          );\n        result = captured;\n      }\n    }\n    setErrors(found);\n    setWhole(\"\");\n    if (Object.keys(found).length || !plan) return;\n    const type = decisionTypes[plan.outcome.settlement];\n    const shared =\n      publicReasonAsked && publicReason.trim() ? { publicReason } : {};\n    // An approval records no private reason and no result.\n    const next: ReviewDecision =\n      type === \"approve\"\n        ? { type, outcome: plan.outcome.id, ...shared }\n        : {\n            type,\n            outcome: plan.outcome.id,\n            ...(reason.trim() ? { reason } : {}),\n            ...shared,\n            ...(result ? { result } : {}),\n          };\n    if (sendsBack) void sendBack.sendBack(task, next, requesterNote);\n    else void decision.decide(task, next);\n  }\n\n  const deciding = task.heldByYou && task.status === \"held\";\n  const noteState = note.state;\n  if (!deciding && state.state === \"idle\" && noteState.state === \"idle\")\n    return null;\n  return (\n    <section className=\"decide-panel\">\n      <h2>{c.decisionHeading}</h2>\n      {state.state === \"confirmed\" && (\n        <Notice tone=\"success\">{c.decided}</Notice>\n      )}\n      {state.state === \"confirmed\" && task.decisionReceipt && (\n        <NextStep task={task} stageNames={stageNames} />\n      )}\n      {state.state === \"refused\" && state.refusal.kind !== \"validation\" && (\n        <Notice tone=\"warning\">\n          {caseworkRefusalText(c, state.refusal, c.decisionNotApplied)}\n        </Notice>\n      )}\n      {whole && <Notice tone=\"warning\">{whole}</Notice>}\n      <Unconfirmed\n        command={decision}\n        text={c.decisionUnconfirmed}\n        retryLabel={c.retryDecision}\n        {...(decision.decidedUnattributed\n          ? { replaceText: c.decisionUnattributed }\n          : {})}\n      />\n      {noteState.state === \"confirmed\" && (\n        <Notice tone=\"success\">{c.requesterNoteSent}</Notice>\n      )}\n      {noteState.state === \"refused\" && (\n        <Notice tone=\"warning\">\n          <p>{c.requesterNoteNotSent}</p>\n          {noteState.refusal.message && <p>{noteState.refusal.message}</p>}\n          <div className=\"actions\">\n            <Button disabled={note.locked} onClick={() => void note.resend()}>\n              {c.resendRequesterNote}\n            </Button>\n          </div>\n        </Notice>\n      )}\n      <Unconfirmed\n        // A note has no read back; only resending it can settle it.\n        command={{\n          state: noteState,\n          retry: note.retry,\n          dismissUnknown: note.dismissUnknown,\n        }}\n        text={c.requesterNoteUnconfirmed}\n        retryLabel={c.retryRequesterNote}\n        {...(note.expired\n          ? { replaceText: c.noteExpired, stopLabel: c.dismiss }\n          : {})}\n      />\n      {deciding && (\n        <>\n          <ErrorSummary errors={errors} />\n          <fieldset disabled={decision.locked}>\n            <div\n              role=\"radiogroup\"\n              aria-label={c.outcomeLegend}\n              id=\"review-outcome\"\n              tabIndex={-1}\n              className=\"decide-radios\"\n            >\n              {choices.map((option) => (\n                <label key={option.id} htmlFor={`review-choice-${option.id}`}>\n                  <input\n                    type=\"radio\"\n                    id={`review-choice-${option.id}`}\n                    name=\"review-outcome\"\n                    checked={chosen === option.id}\n                    onChange={() => setPicked(option.id)}\n                  />\n                  <span>{option.label}</span>\n                </label>\n              ))}\n            </div>\n            {errors[\"review-outcome\"] && (\n              <p className=\"field-error-message\">{errors[\"review-outcome\"]}</p>\n            )}\n            {blocked.map((option) => (\n              <p key={option.id} className=\"muted\">\n                {fill(c.outcomeBlocked, { outcome: option.label }, locale)}\n              </p>\n            ))}\n            {choices.some(\n              (option) => option.plan.outcome.settlement === \"approved\",\n            ) && <ApprovalLeadsTo task={task} stageNames={stageNames} />}\n            {plan && !approves && (\n              <InputField\n                name=\"review-reason\"\n                label={c.reason}\n                hint={c.reasonHint}\n                value={reason}\n                multiline\n                required={reasonRequired}\n                onChange={setReason}\n                error={errors[\"review-reason\"]}\n              />\n            )}\n            <PublicReasonField\n              outcome={plan?.outcome}\n              value={publicReason}\n              onChange={setPublicReason}\n              error={errors[\"review-public-reason\"]}\n            />\n            {sendsBack && (\n              <InputField\n                name=\"review-requester-note\"\n                label={c.requesterNote}\n                hint={c.requesterNoteHint}\n                value={requesterNote}\n                multiline\n                required\n                onChange={setRequesterNote}\n                error={errors[\"review-requester-note\"]}\n              />\n            )}\n            {plan && plan.fields.length > 0 && (\n              <>\n                <h3>{c.resultHeading}</h3>\n                {plan.fields.map((field) => (\n                  <ResultField\n                    key={field.name}\n                    field={field}\n                    value={values[field.name] ?? \"\"}\n                    required={plan.resultRequired && field.required}\n                    onChange={(value) =>\n                      setValues((previous) => ({\n                        ...previous,\n                        [field.name]: value,\n                      }))\n                    }\n                    error={errors[`review-result-${field.name}`]}\n                  />\n                ))}\n              </>\n            )}\n          </fieldset>\n          <div className=\"actions\">\n            <Button disabled={decision.locked || rereading} onClick={submit}>\n              {c.record}\n            </Button>\n          </div>\n        </>\n      )}\n    </section>\n  );\n}\n\nfunction draftText(body: ReviewJson | undefined): string {\n  return body &&\n    typeof body === \"object\" &&\n    !Array.isArray(body) &&\n    typeof body.text === \"string\"\n    ? body.text\n    : \"\";\n}\n/**\n * The officer's own draft on a held task. Fetches its own draft command from\n * the task id; a read error is rendered by the caller, which knows how the\n * app shows a failed read.\n */\nexport function DraftPanel({\n  task,\n  rereading,\n  renderError,\n}: {\n  task: ReviewTaskDetail;\n  rereading: boolean;\n  /** Renders the draft's own read error in place of the draft field. */\n  renderError: (error: unknown, retry: () => void) => ReactNode;\n}) {\n  const c = useCaseworkContent();\n  const { draft, save, remove } = useReviewDraft(task.taskId);\n  const [text, setText] = useState<string | null>(null);\n  const value = text ?? draftText(draft.data?.body);\n  // Once a delete is confirmed the field shows the (now empty) stored draft,\n  // not the text typed before it.\n  useEffect(() => {\n    if (remove.state.state === \"confirmed\") setText(null);\n  }, [remove.state.state]);\n  return (\n    <section className=\"review-draft\">\n      <h2>{c.draftHeading}</h2>\n      {draft.error && renderError(draft.error, () => void draft.refetch())}\n      <div className=\"field\">\n        <label htmlFor=\"review-draft\">{c.draftLabel}</label>\n        <p className=\"field-hint\" id=\"review-draft-hint\">\n          {c.draftHint}\n        </p>\n        <Textarea\n          id=\"review-draft\"\n          aria-describedby=\"review-draft-hint\"\n          value={value}\n          onChange={(e) => setText(e.target.value)}\n        />\n      </div>\n      <div className=\"actions\">\n        <Button\n          variant=\"outline\"\n          disabled={\n            rereading ||\n            save.state.state === \"sending\" ||\n            save.state.state === \"recovering\"\n          }\n          onClick={() => save.run(task, { text: value })}\n        >\n          {c.saveDraft}\n        </Button>\n        {draft.data && (\n          <Button\n            variant=\"ghost\"\n            disabled={rereading || remove.locked}\n            onClick={() => void remove.run(task)}\n          >\n            {c.deleteDraft}\n          </Button>\n        )}\n      </div>\n      {save.state.state === \"confirmed\" && (\n        <Notice tone=\"success\">{c.draftSaved}</Notice>\n      )}\n      {remove.state.state === \"confirmed\" && (\n        <Notice tone=\"success\">{c.draftDeleted}</Notice>\n      )}\n      {save.state.state === \"refused\" && (\n        <Notice tone=\"warning\">\n          {caseworkRefusalText(c, save.state.refusal, c.taskNotApplied)}\n        </Notice>\n      )}\n      {remove.state.state === \"refused\" && (\n        <Notice tone=\"warning\">\n          {caseworkRefusalText(c, remove.state.refusal, c.taskNotApplied)}\n        </Notice>\n      )}\n      <Unconfirmed\n        command={save}\n        text={c.draftUnconfirmed}\n        retryLabel={c.retryDraft}\n      />\n      <Unconfirmed\n        command={remove}\n        text={c.draftDeleteUnconfirmed}\n        retryLabel={c.retryDraftDelete}\n      />\n    </section>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/casework/review-decision.tsx"
    }
  ],
  "type": "registry:block"
}