All files / src/apps/user/pages/dashboards DashboardViewer.tsx

47.65% Statements 61/128
35.63% Branches 31/87
24% Functions 12/50
48.33% Lines 58/120

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 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498                                                                                    2x     2x           3x         6x                         2x                     2x 11x 11x 11x 11x   11x 11x 11x 11x     11x 11x 11x 11x   11x   5x         31x 31x   5x 10x 31x       11x   5x         11x 11x   11x 10x       11x                 11x                   11x                   11x           11x           11x           11x                   11x                     11x               11x         11x   1x   1x 1x       1x                       11x           11x               11x                     11x 5x                 6x 3x                               3x     3x   3x                                               1x 1x                                                                                                                                                                                                                                                                                                                                                                                  
import { MoveToShared, WorkspaceGuard } from "@/components/owner";
import AIProvenance from "@/components/badge/AIProvenance";
import BuiltInBadge from "@/components/badge/BuiltInBadge";
import { ResourceCostCard } from "@/components/cost";
import BoardSettings, {
  BoardSettingsValues,
} from "@/components/dashboard/BoardSettings";
import DashboardCanvas from "@/components/dashboard/DashboardCanvas";
import { toneOf } from "@/components/appearance/tones";
import WidgetEditor from "@/components/dashboard/WidgetEditor";
import WidgetPicker from "@/components/dashboard/WidgetPicker";
import MainPage from "@/components/page/MainPage/MainPage";
import {
  CreateDashboardBody,
  CreateWidgetBody,
  Dashboard,
  DashboardWidget,
  DashboardWithWidgets,
  WidgetPlacement,
  WidgetTypeSpec,
} from "@/objects/Dashboard";
import { isSystemManaged } from "@/objects/Doc";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  ArrowLeft,
  Check,
  Copy,
  Home,
  LayoutGrid,
  Loader2,
  Move,
  Plus,
  Settings2,
} from "lucide-react";
import React from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
 
/** Tile types whose refresh calls a model — svc-core's `AutomationWidget`
 *  and `ComparisonWidget`, the ones ledgered as `dashboard` spend. */
const MODEL_WIDGET_TYPES = new Set(["automation", "comparison"]);
 
/** How often to re-read a board while a widget is regenerating. */
const REFRESH_POLL_MS = 4000;
 
/** A board of the user's own with a built-in board's tiles, placed as they
 *  are. Built from what the board serves and created through the ordinary
 *  create path, so every tile is validated as if the user had added it — and
 *  its generated tiles then run, and are paid for, as the user. */
export const copyOfBoard = (board: DashboardWithWidgets): CreateDashboardBody => ({
  name: `Copy of ${board.name}`,
  description: board.description,
  icon: board.icon,
  accent: board.accent,
  widgets: board.widgets.map((widget) => ({
    widget_type: widget.widget_type,
    title: widget.title,
    config: widget.config,
    x: widget.x,
    y: widget.y,
    w: widget.w,
    h: widget.h,
    position: widget.position,
    refresh_interval_seconds: widget.refresh_interval_seconds,
  })),
});
 
const extractError = (error: unknown): string => {
  const detail = (error as { response?: { data?: { detail?: unknown } } })
    ?.response?.data?.detail;
  if (typeof detail === "string") return detail;
  if (Array.isArray(detail) && detail.length > 0) {
    const first = detail[0] as { msg?: string };
    if (first?.msg) return first.msg;
  }
  return "Something went wrong. Check the fields and try again.";
};
 
const DashboardViewer: React.FC = () => {
  const { dashboardId } = useParams<{ dashboardId: string }>();
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
 
  const [editing, setEditing] = React.useState(false);
  const [picking, setPicking] = React.useState(false);
  const [editorSpec, setEditorSpec] = React.useState<WidgetTypeSpec | null>(null);
  const [editorWidget, setEditorWidget] = React.useState<DashboardWidget | null>(
    null,
  );
  const [editorError, setEditorError] = React.useState<string | null>(null);
  const [settingsOpen, setSettingsOpen] = React.useState(false);
  const [settingsError, setSettingsError] = React.useState<string | null>(null);
  const [copyError, setCopyError] = React.useState<string | null>(null);
 
  const boardQuery = useQuery({
    queryKey: [QUERY_KEYS.GET.DASHBOARD_BY_ID, dashboardId],
    queryFn: () => getApiHandler().dashboard_router.getById(dashboardId ?? ""),
    enabled: Boolean(dashboardId),
    // Poll only while something is actually regenerating, so an idle board
    // costs nothing.
    refetchInterval: (query) => {
      const board = query.state.data as DashboardWithWidgets | null;
      if (!board) return false;
      const busy =
        board.refreshing ||
        board.widgets.some((w) => w.cache_status === "refreshing");
      return busy ? REFRESH_POLL_MS : false;
    },
  });
 
  const typesQuery = useQuery({
    queryKey: [QUERY_KEYS.GET.DASHBOARD_WIDGET_TYPES],
    queryFn: () => getApiHandler().dashboard_router.widgetTypes(),
    staleTime: 5 * 60 * 1000,
  });
 
  const board: DashboardWithWidgets | null =
    (boardQuery.data as DashboardWithWidgets | null) ?? null;
  const specs: WidgetTypeSpec[] = (typesQuery.data as WidgetTypeSpec[]) ?? [];
 
  const specsByType = React.useMemo(
    () => new Map(specs.map((spec) => [spec.type as string, spec])),
    [specs],
  );
 
  const invalidate = () => {
    queryClient.invalidateQueries({
      queryKey: [QUERY_KEYS.GET.DASHBOARD_BY_ID, dashboardId],
    });
    queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.DASHBOARDS] });
  };
 
  // ── Mutations ──────────────────────────────────────────────────────────────
 
  const addWidget = useMutation({
    mutationFn: (body: CreateWidgetBody) =>
      getApiHandler().dashboard_router.addWidget(dashboardId ?? "", body),
    onSuccess: () => {
      closeEditor();
      invalidate();
    },
    onError: (error) => setEditorError(extractError(error)),
  });
 
  const updateWidget = useMutation({
    mutationFn: ({ id, body }: { id: string; body: Partial<CreateWidgetBody> }) =>
      getApiHandler().dashboard_router.updateWidget(dashboardId ?? "", id, body),
    onSuccess: () => {
      closeEditor();
      invalidate();
    },
    onError: (error) => setEditorError(extractError(error)),
  });
 
  const deleteWidget = useMutation({
    mutationFn: (id: string) =>
      getApiHandler().dashboard_router.deleteWidget(dashboardId ?? "", id),
    onSuccess: invalidate,
  });
 
  const refreshWidget = useMutation({
    mutationFn: (id: string) =>
      getApiHandler().dashboard_router.refreshWidget(dashboardId ?? "", id),
    onSuccess: invalidate,
  });
 
  const saveLayout = useMutation({
    mutationFn: (placements: WidgetPlacement[]) =>
      getApiHandler().dashboard_router.saveLayout(dashboardId ?? "", placements),
    onSuccess: invalidate,
  });
 
  const removeItem = useMutation({
    mutationFn: ({ widgetId, itemId }: { widgetId: string; itemId: string }) =>
      getApiHandler().dashboard_router.deleteSavedMessage(
        dashboardId ?? "",
        widgetId,
        itemId,
      ),
    onSuccess: invalidate,
  });
 
  const saveSettings = useMutation({
    mutationFn: (values: BoardSettingsValues) =>
      getApiHandler().dashboard_router.update(dashboardId ?? "", values),
    onSuccess: () => {
      setSettingsOpen(false);
      setSettingsError(null);
      invalidate();
    },
    onError: (error) => setSettingsError(extractError(error)),
  });
 
  const deleteBoard = useMutation({
    mutationFn: () => getApiHandler().dashboard_router.delete(dashboardId ?? ""),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.DASHBOARDS] });
      navigate(APP_ROUTES.USER.dashboards);
    },
  });
 
  const setHome = useMutation({
    mutationFn: () => getApiHandler().dashboard_router.setHome(dashboardId ?? ""),
    onSuccess: invalidate,
  });
 
  const copyBoard = useMutation({
    mutationFn: (source: DashboardWithWidgets) =>
      getApiHandler().dashboard_router.create(copyOfBoard(source)),
    onSuccess: (created: Dashboard | null) => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.DASHBOARDS] });
      Iif (!created) {
        setCopyError("This board could not be copied.");
        return;
      }
      navigate(
        APP_ROUTES.USER.DASHBOARDS.id.replace(
          ROUTE_PARAMS.DASHBOARD.id,
          created.id,
        ),
      );
    },
    onError: (error) => setCopyError(extractError(error)),
  });
 
  // ── Editor plumbing ────────────────────────────────────────────────────────
 
  const closeEditor = () => {
    setEditorSpec(null);
    setEditorWidget(null);
    setEditorError(null);
  };
 
  const openEditorFor = (widget: DashboardWidget) => {
    const spec = specs.find((s) => s.type === widget.widget_type);
    if (!spec) return;
    setEditorWidget(widget);
    setEditorSpec(spec);
    setEditorError(null);
  };
 
  const handleSave = (body: CreateWidgetBody) => {
    setEditorError(null);
    if (editorWidget) {
      updateWidget.mutate({ id: editorWidget.id, body });
    } else {
      addWidget.mutate(body);
    }
  };
 
  // ── Render ─────────────────────────────────────────────────────────────────
 
  if (boardQuery.isLoading) {
    return (
      <MainPage title="Dashboard">
        <div className="flex items-center gap-2 text-sm text-gray-400">
          <Loader2 className="w-4 h-4 animate-spin" /> Loading board…
        </div>
      </MainPage>
    );
  }
 
  if (!board) {
    return (
      <MainPage title="Dashboard">
        <p className="text-sm text-gray-500 dark:text-gray-400">
          This dashboard could not be found.{" "}
          <Link
            to={APP_ROUTES.USER.dashboards}
            className="text-blue-600 dark:text-blue-400 hover:underline"
          >
            Back to dashboards
          </Link>
          .
        </p>
      </MainPage>
    );
  }
 
  const tone = toneOf(board.accent);
  // A built-in board is CHAIN-R's: every write is refused, so none is offered
  // — only a copy the user can change.
  const builtIn = isSystemManaged(board);
 
  return (
    <MainPage title={board.name}>
      <div className="flex flex-wrap items-center justify-between gap-3 -mt-4 mb-4">
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <Link
              to={APP_ROUTES.USER.dashboards}
              className="inline-flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"
            >
              <ArrowLeft className="w-3.5 h-3.5" /> All dashboards
            </Link>
            {builtIn && <BuiltInBadge size="sm" />}
          </div>
          {board.description && (
            <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
              {board.description}
            </p>
          )}
        </div>
 
        {builtIn ? (
          <button
            type="button"
            onClick={() => {
              setCopyError(null);
              copyBoard.mutate(board);
            }}
            disabled={copyBoard.isPending}
            className="inline-flex items-center gap-1.5 rounded-lg bg-gray-900 dark:bg-white px-3 py-1.5 text-xs font-medium text-white dark:text-gray-900 hover:opacity-80 disabled:opacity-50 transition-opacity"
          >
            {copyBoard.isPending ? (
              <Loader2 className="w-3.5 h-3.5 animate-spin" />
            ) : (
              <Copy className="w-3.5 h-3.5" />
            )}
            Copy to my dashboards
          </button>
        ) : (
          <div className="flex items-center gap-2">
            <MoveToShared kind="dashboard" resource={board} />
            {!board.is_home && (
              <button
                type="button"
                onClick={() => setHome.mutate()}
                disabled={setHome.isPending}
                className="inline-flex items-center gap-1.5 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-1.5 text-xs font-medium text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50 disabled:opacity-50 transition-colors"
              >
                <Home className="w-3.5 h-3.5" /> Make home
              </button>
            )}
 
            <button
              type="button"
              title="Rename and restyle this dashboard"
              onClick={() => {
                setSettingsError(null);
                setSettingsOpen(true);
              }}
              className="inline-flex items-center gap-1.5 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-1.5 text-xs font-medium text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
            >
              <Settings2 className="w-3.5 h-3.5" /> Settings
            </button>
 
            <button
              type="button"
              onClick={() => setEditing((on) => !on)}
              className={`inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${
                editing
                  ? "border-emerald-500 bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300"
                  : "border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50"
              }`}
            >
              {editing ? (
                <>
                  <Check className="w-3.5 h-3.5" /> Done
                </>
              ) : (
                <>
                  <Move className="w-3.5 h-3.5" /> Arrange
                </>
              )}
            </button>
 
            <button
              type="button"
              onClick={() => setPicking(true)}
              className="inline-flex items-center gap-1.5 rounded-lg bg-gray-900 dark:bg-white px-3 py-1.5 text-xs font-medium text-white dark:text-gray-900 hover:opacity-80 transition-opacity"
            >
              <Plus className="w-3.5 h-3.5" /> Add widget
            </button>
          </div>
        )}
      </div>
 
      {builtIn && (
        <p className="mb-4 max-w-3xl text-xs text-gray-500 dark:text-gray-400">
          A built-in board, maintained by CHAIN-R. Tiles marked{" "}
          <span className="font-medium">Your data</span> show your own;{" "}
          <span className="font-medium">CHAIN-R benchmark</span> tiles show
          what CHAIN-R measured, and{" "}
          <span className="font-medium">Live source</span> and{" "}
          <span className="font-medium">AI generated</span> tiles refresh on
          their own: all three are the same for everyone. Copy the board to
          make one of your own you can change.
        </p>
      )}
      {copyError && (
        <p className="mb-4 rounded-lg bg-red-50 dark:bg-red-900/20 px-3 py-2 text-xs text-red-700 dark:text-red-300">
          {copyError}
        </p>
      )}
 
      <WorkspaceGuard resource={board} noun="dashboard" copyKind="dashboard" />
      {board.is_ai_generated && (
        <AIProvenance
          resourceLabel="dashboard"
          generationId={board.generation_id}
          resourceId={board.id}
          className="mb-4"
        />
      )}
 
      {board.widgets.length === 0 ? (
        <div className="rounded-xl border border-dashed border-gray-300 dark:border-gray-700 py-16 text-center">
          <LayoutGrid className="mx-auto w-8 h-8 text-gray-300 dark:text-gray-600" />
          <p className="mt-3 text-sm font-medium text-gray-700 dark:text-gray-200">
            This board is empty
          </p>
          <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
            Add a note, a live metric, or an automation that keeps itself
            current.
          </p>
          {!builtIn && (
            <button
              type="button"
              onClick={() => setPicking(true)}
              className="mt-4 inline-flex items-center gap-1.5 rounded-lg bg-gray-900 dark:bg-white px-3 py-1.5 text-xs font-medium text-white dark:text-gray-900 hover:opacity-80 transition-opacity"
            >
              <Plus className="w-3.5 h-3.5" /> Add your first widget
            </button>
          )}
        </div>
      ) : (
        <DashboardCanvas
          widgets={board.widgets}
          tone={tone}
          editing={editing && !builtIn}
          readOnly={builtIn}
          specs={specsByType}
          onLayoutChange={(placements) => saveLayout.mutate(placements)}
          onEditWidget={openEditorFor}
          onDeleteWidget={(widget) => deleteWidget.mutate(widget.id)}
          onRefreshWidget={(widget) => refreshWidget.mutate(widget.id)}
          onRemoveItem={(widget, itemId) =>
            removeItem.mutate({ widgetId: widget.id, itemId })
          }
        />
      )}
 
      {/* Only boards with tiles that call a model have a cost to show — and
          a built-in board's calls are the platform's, not the viewer's. */}
      {!builtIn &&
        board.widgets.some((w) => MODEL_WIDGET_TYPES.has(w.widget_type)) && (
        <ResourceCostCard
          source="dashboard"
          sourceId={board.id}
          noun="dashboard"
          className="mt-6"
        />
      )}
 
      {picking && (
        <WidgetPicker
          specs={specs}
          onCancel={() => setPicking(false)}
          onPick={(spec) => {
            setPicking(false);
            setEditorWidget(null);
            setEditorSpec(spec);
            setEditorError(null);
          }}
        />
      )}
 
      {settingsOpen && (
        <BoardSettings
          board={board}
          saving={saveSettings.isPending}
          error={settingsError}
          onCancel={() => setSettingsOpen(false)}
          onSave={(values) => saveSettings.mutate(values)}
          onDelete={() => deleteBoard.mutate()}
        />
      )}
 
      {editorSpec && (
        <WidgetEditor
          spec={editorSpec}
          widget={editorWidget ?? undefined}
          saving={addWidget.isPending || updateWidget.isPending}
          error={editorError}
          onCancel={closeEditor}
          onSave={handleSave}
        />
      )}
    </MainPage>
  );
};
 
export default DashboardViewer;