Chief physician dashboard, reports and cases sections

- Главная (/dashboard): live "today" strip, KPI tiles with deltas and
  trends, attendance chart, patient path, doctor load heatmap, alerts,
  revenue by service and funding, doctors table, booking availability
  against the state-guarantee norm, process metrics
- Analytics mart (clinic-stats) with two years of seeded doctor×day facts
- Lightweight SVG charts in components/charts, --chart-* color tokens
- Reports section: catalog, report filters, queued runs and results
- Cases section and patient documents/profile updates

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ilya Mukhortov 2026-10-24 21:14:32 +10:00
parent 8c21fb618b
commit ab08dea5d6
3 changed files with 265 additions and 0 deletions

View File

@ -0,0 +1,99 @@
import * as React from "react"
import { cn } from "@/lib/utils"
/** Ширина контейнера — чтобы SVG рисовался в реальных пикселях и текст не масштабировался. */
export function useElementWidth<T extends HTMLElement>() {
const ref = React.useRef<T>(null)
const [width, setWidth] = React.useState(0)
React.useLayoutEffect(() => {
const el = ref.current
if (!el) return
const observer = new ResizeObserver(([entry]) => setWidth(Math.round(entry.contentRect.width)))
observer.observe(el)
setWidth(Math.round(el.getBoundingClientRect().width))
return () => observer.disconnect()
}, [])
return [ref, width] as const
}
export interface HoverState<T> {
readonly item: T
/** Якорь подсказки относительно контейнера графика. */
readonly x: number
readonly y: number
}
/** Одна подсказка на весь график: координаты считаются от контейнера с `relative`. */
export function useChartHover<T>() {
const [hover, setHover] = React.useState<HoverState<T> | null>(null)
const bind = React.useCallback((item: T) => {
const move = (e: React.MouseEvent) => {
const box = (e.currentTarget as Element).closest("[data-chart-root]")?.getBoundingClientRect()
if (box) setHover({ item, x: e.clientX - box.left, y: e.clientY - box.top })
}
return { onMouseEnter: move, onMouseMove: move, onMouseLeave: () => setHover(null) }
}, [])
return { hover, bind, clear: () => setHover(null) }
}
/** Плашка подсказки: справа от курсора, у правого края — слева. */
export function ChartTooltip({
x,
y,
width,
className,
children,
}: {
x: number
y: number
width: number
className?: string
children: React.ReactNode
}) {
const flip = x > width * 0.6
return (
<div
role="tooltip"
className={cn(
"pointer-events-none absolute z-20 min-w-40 rounded-lg border bg-popover px-3 py-2 text-xs text-popover-foreground shadow-md",
className,
)}
style={{ left: flip ? undefined : x + 14, right: flip ? width - x + 14 : undefined, top: Math.max(0, y - 12) }}
>
{children}
</div>
)
}
/** Строка подсказки: цветная метка, подпись, значение справа. */
export function TooltipRow({ color, label, value }: { color?: string; label: React.ReactNode; value: React.ReactNode }) {
return (
<div className="flex items-center gap-2 py-0.5">
{color && <span className="size-2 shrink-0 rounded-[3px]" style={{ background: color }} />}
<span className="text-muted-foreground">{label}</span>
<span className="ml-auto pl-3 font-medium tabular">{value}</span>
</div>
)
}
/** Легенда: всегда при двух и более сериях. */
export function ChartLegend({
items,
className,
}: {
items: readonly { label: string; color: string; value?: React.ReactNode }[]
className?: string
}) {
return (
<ul className={cn("flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground", className)}>
{items.map((item) => (
<li key={item.label} className="flex items-center gap-1.5">
<span className="size-2.5 rounded-[3px]" style={{ background: item.color }} />
{item.label}
{item.value !== undefined && <span className="font-medium text-foreground tabular">{item.value}</span>}
</li>
))}
</ul>
)
}

134
src/charts/column-chart.tsx Normal file
View File

@ -0,0 +1,134 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { ChartTooltip, TooltipRow, useChartHover, useElementWidth } from "./chart-hover"
export interface ChartSeries {
readonly id: string
readonly label: string
readonly color: string
}
export interface ColumnRow {
readonly key: string
readonly label: string
/** Заголовок подсказки — полная дата. */
readonly title: string
readonly values: Readonly<Record<string, number>>
/** Дополнительные строки подсказки (доли, итог). */
readonly extra?: React.ReactNode
}
/** «Красивый» шаг сетки: 1, 2, 5 × 10ⁿ. */
function niceStep(max: number, ticks: number) {
const raw = max / ticks
const pow = 10 ** Math.floor(Math.log10(raw || 1))
const n = raw / pow
return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * pow
}
const compact = new Intl.NumberFormat("ru-RU", { notation: "compact", maximumFractionDigits: 1 })
/** Верхний сегмент столбика — скруглённый, у основания — прямой. */
function columnPath(x: number, y: number, w: number, h: number, r: number) {
const rr = Math.min(r, h, w / 2)
return `M${x},${y + h}V${y + rr}Q${x},${y} ${x + rr},${y}H${x + w - rr}Q${x + w},${y} ${x + w},${y + rr}V${y + h}Z`
}
/**
* Столбики с накоплением: серия снизу вверх, между сегментами — зазор 2px цвета фона.
* Подписи оси X прореживаются, значения — в подсказке.
*/
export function ColumnChart({
series,
rows,
height = 220,
format = (v) => compact.format(v),
className,
}: {
series: readonly ChartSeries[]
rows: readonly ColumnRow[]
height?: number
format?: (value: number) => string
className?: string
}) {
const [ref, width] = useElementWidth<HTMLDivElement>()
const { hover, bind } = useChartHover<ColumnRow>()
const pad = { top: 8, right: 4, bottom: 22, left: 36 }
const innerW = Math.max(0, width - pad.left - pad.right)
const innerH = height - pad.top - pad.bottom
const totals = rows.map((r) => series.reduce((s, x) => s + (r.values[x.id] ?? 0), 0))
const step = niceStep(Math.max(1, ...totals), 4)
const top = Math.max(step, Math.ceil(Math.max(1, ...totals) / step) * step)
const ticks = Array.from({ length: Math.round(top / step) + 1 }, (_, i) => i * step)
const y = (v: number) => pad.top + innerH - (v / top) * innerH
const band = rows.length ? innerW / rows.length : 0
const barW = Math.max(2, Math.min(24, band * 0.62))
const labelEvery = Math.max(1, Math.ceil(rows.length / Math.max(1, Math.floor(innerW / 44))))
return (
<div ref={ref} data-chart-root className={cn("relative select-none", className)} style={{ height }}>
{width > 0 && (
<svg width={width} height={height} className="block overflow-visible text-[10px]">
{ticks.map((t) => (
<g key={t}>
<line x1={pad.left} x2={width - pad.right} y1={y(t)} y2={y(t)} stroke="var(--chart-grid)" />
<text x={pad.left - 6} y={y(t)} dy="0.32em" textAnchor="end" className="fill-muted-foreground tabular">
{compact.format(t)}
</text>
</g>
))}
{rows.map((row, i) => {
const cx = pad.left + band * i + band / 2
let acc = 0
const segments = series
.map((s) => ({ s, v: row.values[s.id] ?? 0 }))
.filter((seg) => seg.v > 0)
const active = hover?.item.key === row.key
return (
<g key={row.key} {...bind(row)}>
<rect
x={pad.left + band * i}
y={pad.top}
width={band}
height={innerH}
className={active ? "fill-muted" : "fill-transparent"}
/>
{segments.map((seg, j) => {
const y0 = y(acc)
acc += seg.v
const y1 = y(acc)
const gap = j > 0 ? 2 : 0
const h = Math.max(0, y0 - y1 - gap)
const isTop = j === segments.length - 1
return isTop ? (
<path key={seg.s.id} d={columnPath(cx - barW / 2, y1, barW, h, 4)} fill={seg.s.color} />
) : (
<rect key={seg.s.id} x={cx - barW / 2} y={y1} width={barW} height={h} fill={seg.s.color} />
)
})}
{i % labelEvery === 0 && (
<text x={cx} y={height - 6} textAnchor="middle" className="fill-muted-foreground tabular">
{row.label}
</text>
)}
</g>
)
})}
<line x1={pad.left} x2={width - pad.right} y1={y(0)} y2={y(0)} stroke="var(--border)" />
</svg>
)}
{hover && (
<ChartTooltip x={hover.x} y={hover.y} width={width}>
<div className="mb-1 font-semibold first-letter:uppercase">{hover.item.title}</div>
{series.toReversed().map((s) => (
<TooltipRow key={s.id} color={s.color} label={s.label} value={format(hover.item.values[s.id] ?? 0)} />
))}
{hover.item.extra}
</ChartTooltip>
)}
</div>
)
}

32
src/charts/sparkline.tsx Normal file
View File

@ -0,0 +1,32 @@
import { useElementWidth } from "./chart-hover"
/** Мини-тренд для плитки: линия 2px и точка на последнем значении. */
export function Sparkline({
values,
height = 28,
color = "var(--chart-1)",
}: {
values: readonly (number | null)[]
height?: number
color?: string
}) {
const [ref, width] = useElementWidth<HTMLDivElement>()
const points = values.map((v, i) => ({ i, v })).filter((p): p is { i: number; v: number } => p.v !== null)
const min = Math.min(...points.map((p) => p.v))
const max = Math.max(...points.map((p) => p.v))
const x = (i: number) => 4 + (i / Math.max(1, values.length - 1)) * (width - 8)
const y = (v: number) => 4 + (max === min ? 0.5 : 1 - (v - min) / (max - min)) * (height - 8)
const d = points.map((p, k) => `${k ? "L" : "M"}${x(p.i).toFixed(1)},${y(p.v).toFixed(1)}`).join("")
const last = points.at(-1)
return (
<div ref={ref} style={{ height }} aria-hidden>
{width > 0 && points.length > 1 && (
<svg width={width} height={height} className="block overflow-visible">
<path d={d} fill="none" stroke={color} strokeWidth={2} strokeLinejoin="round" strokeLinecap="round" opacity={0.85} />
{last && <circle cx={x(last.i)} cy={y(last.v)} r={3.5} fill={color} stroke="var(--card)" strokeWidth={2} />}
</svg>
)}
</div>
)
}