The chat responses are generated using Generative AI technology for intuitive search and may not be entirely accurate. They are not intended as professional advice. For full details, including our use rights, privacy practices and potential export control restrictions, please refer to our Generative AI Service Privacy Information. As this is a test version, please let us know if something irritating comes up. Like you get recommended a chocolate fudge ice cream instead of an energy managing application. If that occurs, please use the feedback button in our contact form!
Skip to content

Project dashboard

2612

The Project dashboard page with a query box, stat tiles, three bar charts and a table

AspectDetails
Folderexamples/project-dashboard
Identifiercom.example.dashboard
Viewnavigation topic dashboard with icon
Placement<applicationView id="com.example.dashboard.dashboard"/> in the project's Topics configuration
UsesfetchContext(), REST GET …/workitems?query=…&fields[workitems]=…,assignee&page[size]=100

What it does

  1. Fetches the context for projectId.
  2. Loads up to 100 work items with id, title, status, type, created and the assignee relationship, optionally filtered by a Lucene query the user types.
  3. Renders four tiles (items loaded, not resolved, distinct types, unassigned), three bar charts built from plain <div>s (by status, by type, by assignee), and a table of the ten most recently created items with links.
  4. Apply runs the typed query and Reset goes back to all work items; Refresh repeats the applied query, shows Refreshing… while it runs and the time of the last refresh afterwards.

Files

  • project-dashboard/
    • manifest.json
    • public/
      • icon30.png navigation icon (30 × 30 px)
    • src/
      • App.tsx
      • polarion.ts
      • types.ts
      • main.tsx
      • styles.css
    • …

manifest.json

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.dashboard",
  "title": "Project dashboard",
  "description": "A navigation topic that summarises the work items of the current project.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.2.1",
  "views": {
    "navigationTopics": [
      {
        "identifier": "dashboard",
        "title": "Project dashboard",
        "icon": "icon30.png",
        "rootDirectory": "dashboard",
        "document": "index.html"
      }
    ]
  }
}

src/types.ts

The assignee is a relationship, not an attribute. Asking for it in fields[workitems] makes the API include relationships.assignee.data, a list of user references.

src/types.ts
/** Minimal JSON:API shapes used by this example. */

export interface WorkItemResource {
  /** "PROJECT/WI-ID" */
  id: string;
  type: "workitems";
  attributes: { title: string; status: string; type: string; created?: string };
  /** Relationships are only present when requested through `fields[workitems]`. */
  relationships?: {
    assignee?: { data?: { id: string; type: "users" }[] };
  };
}

export interface WorkItemListResponse {
  data: WorkItemResource[];
  meta?: { totalCount?: number };
}

src/App.tsx

src/App.tsx
import { useCallback, useEffect, useRef, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import { restFetch } from "./polarion";
import type { WorkItemListResponse, WorkItemResource } from "./types";

const CLOSED_STATUSES = new Set(["resolved", "done", "closed", "verified", "rejected"]);

/** First assignee id, or "unassigned". The relationship is absent when the field was not requested. */
function assigneeOf(item: WorkItemResource): string {
  const data = item.relationships?.assignee?.data;
  return data && data.length > 0 ? data[0].id : "unassigned";
}

function countBy(items: WorkItemResource[], key: (item: WorkItemResource) => string): [string, number][] {
  const counts = new Map<string, number>();
  for (const item of items) {
    const k = key(item);
    counts.set(k, (counts.get(k) ?? 0) + 1);
  }
  return [...counts.entries()].sort((a, b) => b[1] - a[1]);
}

/** A horizontal bar chart made of plain <div>s. */
function Bars({ title, data }: { title: string; data: [string, number][] }) {
  const max = Math.max(1, ...data.map(([, n]) => n));
  return (
    <div className="panel">
      <h2>{title}</h2>
      {data.length === 0 && <p className="muted">No data.</p>}
      {data.map(([label, n]) => (
        <div className="bar-row" key={label}>
          <span className="bar-label" title={label}>
            {label}
          </span>
          <div className="bar-track">
            <div className="bar" style={{ width: `${(n / max) * 100}%` }} />
          </div>
          <span className="bar-value">{n}</span>
        </div>
      ))}
    </div>
  );
}

export default function App() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [items, setItems] = useState<WorkItemResource[] | null>(null);
  const [total, setTotal] = useState<number | undefined>(undefined);
  const [query, setQuery] = useState("");
  const [appliedQuery, setAppliedQuery] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [loadedAt, setLoadedAt] = useState<Date | null>(null);

  // Apply and Refresh can start a load while another one runs; only the latest may update the page.
  const requestRef = useRef(0);

  const load = useCallback(async (ctx: PolarionContext, lucene: string) => {
    if (!ctx.projectId) {
      setError("No project in context. This view is meant to be opened inside a project.");
      return;
    }
    const params = new URLSearchParams({
      "fields[workitems]": "id,title,status,type,created,assignee",
      "page[size]": "100",
    });
    if (lucene.trim() !== "") {
      params.set("query", lucene.trim());
    }
    const request = ++requestRef.current;
    const isCurrent = () => request === requestRef.current;
    setLoading(true);
    try {
      // `no-store` makes Refresh always reach the server instead of a cached response.
      const response = await restFetch<WorkItemListResponse>(ctx, `/projects/${ctx.projectId}/workitems?${params}`, { cache: "no-store" });
      if (!isCurrent()) return;
      // The query counts as applied only once it has loaded, so a failed Apply never labels old data.
      setAppliedQuery(lucene);
      setItems(response.data);
      setTotal(response.meta?.totalCount);
      setLoadedAt(new Date());
      setError(null);
    } catch (error) {
      if (!isCurrent()) return;
      console.error("Unable to load the work items:", error);
      const message = error instanceof Error ? error.message : String(error);
      setError(`Unable to load the work items: ${message}`);
    } finally {
      if (isCurrent()) setLoading(false);
    }
  }, []);

  useEffect(() => {
    let cancelled = false;

    fetchContext()
      .then((ctx) => {
        if (cancelled) {
          return;
        }
        setContext(ctx);
        return load(ctx, "");
      })
      .catch((error: unknown) => {
        if (cancelled) {
          return;
        }
        console.error("Unable to fetch the Polarion context:", error);
        const message = error instanceof Error ? error.message : String(error);
        setError(`Unable to fetch the Polarion context: ${message}`);
      });

    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      destroy();
    };
  }, [load]);

  function apply() {
    if (!context) return;
    void load(context, query);
  }

  /** Back to the initial state: no query, all work items of the project. */
  function reset() {
    if (!context) return;
    setQuery("");
    void load(context, "");
  }

  if (!context || !context.projectId) {
    return error ? <div className="panel error">{error}</div> : <p className="muted">Loading work items…</p>;
  }
  if (!items && !error) {
    return <p className="muted">Loading work items…</p>;
  }
  // After a failed query or request the dashboard stays mounted, so the user can
  // correct the query or press Refresh; the error is shown inline below the query row.
  const loaded = items ?? [];

  const open = loaded.filter((i) => !CLOSED_STATUSES.has((i.attributes.status ?? "").toLowerCase())).length;
  const types = new Set(loaded.map((i) => i.attributes.type)).size;
  const unassigned = loaded.filter((i) => assigneeOf(i) === "unassigned").length;
  const recent = [...loaded].sort((a, b) => (b.attributes.created ?? "").localeCompare(a.attributes.created ?? "")).slice(0, 10);
  const origin = window.location.origin;

  return (
    <div className="page">
      <header>
        <h1>Project {context.projectId}</h1>
        {/* Refresh repeats the applied query; the time below shows that it ran even when nothing changed. */}
        <button onClick={() => load(context, appliedQuery)} disabled={loading}>
          {loading ? "Refreshing…" : "Refresh"}
        </button>
      </header>

      {/* Any Lucene query that works in the Work Items table works here too. */}
      <div className="query-row">
        <input value={query} onChange={(e) => setQuery(e.target.value)} onKeyDown={(e) => e.key === "Enter" && apply()} placeholder="Lucene query, for example: type:task AND NOT status:done" />
        <button onClick={apply}>Apply</button>
        <button onClick={reset} disabled={query === "" && appliedQuery === ""}>
          Reset
        </button>
      </div>
      {error && <div className="panel error">{error}</div>}
      <p className="muted small">
        {loaded.length} loaded{total !== undefined ? ` of ${total}` : ""}
        {appliedQuery ? ` for "${appliedQuery}"` : ""} (first 100 shown)
        {loadedAt ? `, refreshed at ${loadedAt.toLocaleTimeString()}` : ""}
      </p>

      <div className="tiles">
        <div className="tile">
          <span className="value">{loaded.length}</span>
          <span className="label">work items loaded</span>
        </div>
        <div className="tile">
          <span className="value">{open}</span>
          <span className="label">not resolved</span>
        </div>
        <div className="tile">
          <span className="value">{unassigned}</span>
          <span className="label">unassigned</span>
        </div>
        <div className="tile">
          <span className="value">{types}</span>
          <span className="label">distinct types</span>
        </div>
      </div>

      <div className="charts">
        <Bars title="By status" data={countBy(loaded, (i) => i.attributes.status)} />
        <Bars title="By type" data={countBy(loaded, (i) => i.attributes.type)} />
        <Bars title="By assignee" data={countBy(loaded, assigneeOf)} />
      </div>

      <div className="panel">
        <h2>Most recently created</h2>
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>Title</th>
              <th>Type</th>
              <th>Status</th>
              <th>Assignee</th>
              <th>Created</th>
            </tr>
          </thead>
          <tbody>
            {recent.map((item) => {
              const [project, id] = item.id.split("/");
              return (
                <tr key={item.id}>
                  <td>
                    <a href={`${origin}/polarion/#/project/${project}/workitem?id=${id}`} target="_top">
                      {id}
                    </a>
                  </td>
                  <td>{item.attributes.title}</td>
                  <td>{item.attributes.type}</td>
                  <td>{item.attributes.status}</td>
                  <td>{assigneeOf(item)}</td>
                  <td>{item.attributes.created?.slice(0, 10)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Points worth noting:

  • The query box passes the Lucene syntax through. type:requirement AND status:open works exactly as in the Work Items table.
  • No chart library. The Bars component scales widths relative to the largest value. For richer charts, bundle a library; do not load it from a CDN (Content Security Policy).
  • "Not resolved" is a heuristic. The set of closed status ids depends on the project's workflow; adapt CLOSED_STATUSES or derive it from the status enumeration through REST.
  • Page size. For projects with more than 100 items, either page through page[number] or move the aggregation into an endpoint; the dashboard shows "N loaded of total" so the user knows.
  • Only the latest request counts. Apply and Refresh can start a load while another one runs; a request number makes sure that an older response never overwrites a newer query. The query counts as applied only when it has loaded, so after a failed Apply the page keeps the previous data under its own query.
  • Refresh must be visible. When nothing changed, a reload looks exactly like no reload. The button state and the refreshed at time show that the request ran, and cache: "no-store" makes sure it reaches the server.
  • Links use target="_top" so that clicking a row leaves the dashboard and opens the work item in Polarion.

Build and deploy

cd examples/project-dashboard
npm install
npm run package          # → com.example.dashboard.zip

Upload the ZIP. In the project, open Administration → Portal → Topics, choose the View (Default), add the applicationView element among the topics, save, and reload the project. Project dashboard appears in the navigation panel.

Topics configuration with the dashboard added

Things to try

  • Move the aggregation into a stats endpoint that counts across all items on the server, and keep the REST list only for the table.
  • Resolve assignee ids to names with include=assignee&fields[users]=name.
  • Show the data time stamp in the header and auto-refresh every minute.