222 lines
8.6 KiB
TypeScript
222 lines
8.6 KiB
TypeScript
import * as React from "react"
|
||
import { CheckIcon } from "lucide-react"
|
||
|
||
import { cn } from "../lib/utils"
|
||
import { formatMoney } from "../lib/format"
|
||
import { Button } from "../ui/button"
|
||
import { Checkbox } from "../ui/checkbox"
|
||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog"
|
||
import { ScrollArea } from "../ui/scroll-area"
|
||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select"
|
||
import { ContentTabs } from "./content-tabs"
|
||
import { SearchInput } from "./search-input"
|
||
|
||
export interface ServiceOption {
|
||
readonly code: string
|
||
readonly name: string
|
||
readonly category: string
|
||
readonly price: number
|
||
readonly funding?: string
|
||
}
|
||
|
||
export interface ServiceScope<T extends ServiceOption = ServiceOption> {
|
||
readonly id: string
|
||
readonly label: string
|
||
readonly match: (item: T) => boolean
|
||
}
|
||
|
||
const ANY = "__any"
|
||
|
||
/**
|
||
* Диалог «Выбор услуг» как в МИС: набор (услуги врача / внутренние / все),
|
||
* источник финансирования, категория, поиск, отметки и итог выбранного.
|
||
* Уже добавленные услуги показаны отмеченными и недоступны.
|
||
*/
|
||
export function ServicePicker<T extends ServiceOption>({
|
||
open,
|
||
onOpenChange,
|
||
items,
|
||
scopes,
|
||
defaultScope,
|
||
defaultFunding,
|
||
added = [],
|
||
onAdd,
|
||
title = "Выбор услуг",
|
||
}: {
|
||
open: boolean
|
||
onOpenChange: (open: boolean) => void
|
||
items: readonly T[]
|
||
scopes: readonly ServiceScope<T>[]
|
||
defaultScope?: string
|
||
defaultFunding?: string | null
|
||
/** Коды уже выбранных услуг. */
|
||
added?: readonly string[]
|
||
onAdd: (items: T[]) => void
|
||
title?: string
|
||
}) {
|
||
const [scope, setScope] = React.useState(defaultScope ?? scopes[0]?.id ?? "")
|
||
const [funding, setFunding] = React.useState<string>(defaultFunding ?? ANY)
|
||
const [category, setCategory] = React.useState<string>(ANY)
|
||
const [query, setQuery] = React.useState("")
|
||
const [selected, setSelected] = React.useState<Set<string>>(new Set())
|
||
|
||
// Каждое открытие — с чистого листа и с фильтрами по умолчанию.
|
||
React.useEffect(() => {
|
||
if (!open) return
|
||
setScope(defaultScope ?? scopes[0]?.id ?? "")
|
||
setFunding(defaultFunding ?? ANY)
|
||
setCategory(ANY)
|
||
setQuery("")
|
||
setSelected(new Set())
|
||
}, [open, defaultScope, defaultFunding, scopes])
|
||
|
||
const fundings = [...new Set(items.map((i) => i.funding).filter(Boolean))] as string[]
|
||
const scoped = items.filter((i) => scopes.find((s) => s.id === scope)?.match(i) ?? true)
|
||
const categories = [...new Set(scoped.map((i) => i.category))]
|
||
const q = query.trim().toLowerCase()
|
||
const visible = scoped.filter(
|
||
(i) =>
|
||
(funding === ANY || i.funding === funding) &&
|
||
(category === ANY || i.category === category) &&
|
||
(!q || `${i.code} ${i.name}`.toLowerCase().includes(q)),
|
||
)
|
||
const picked = items.filter((i) => selected.has(i.code))
|
||
const pickedSum = picked.reduce((sum, i) => sum + i.price, 0)
|
||
|
||
const toggle = (code: string) =>
|
||
setSelected((set) => {
|
||
const next = new Set(set)
|
||
if (next.has(code)) next.delete(code)
|
||
else next.add(code)
|
||
return next
|
||
})
|
||
|
||
const submit = () => {
|
||
if (!picked.length) return
|
||
onAdd(picked)
|
||
onOpenChange(false)
|
||
}
|
||
|
||
return (
|
||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||
<DialogContent className="flex max-h-[88vh] flex-col gap-0 p-0 sm:max-w-3xl">
|
||
<DialogHeader className="border-b px-5 py-4">
|
||
<DialogTitle>{title}</DialogTitle>
|
||
<DialogDescription className="sr-only">Отметьте услуги и нажмите «Добавить услуги»</DialogDescription>
|
||
</DialogHeader>
|
||
|
||
<div className="space-y-2.5 border-b px-5 py-3">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<ContentTabs
|
||
variant="pill"
|
||
tabs={scopes.map((s) => ({ id: s.id, label: s.label, count: items.filter(s.match).length }))}
|
||
value={scope}
|
||
onValueChange={(v) => {
|
||
setScope(v)
|
||
setCategory(ANY)
|
||
}}
|
||
/>
|
||
<Select value={funding} onValueChange={setFunding}>
|
||
<SelectTrigger size="sm" className="min-w-48 flex-1" aria-label="Источник финансирования">
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
<SelectItem value={ANY}>Любой источник финансирования</SelectItem>
|
||
{fundings.map((f) => (
|
||
<SelectItem key={f} value={f}>
|
||
{f}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
</div>
|
||
<div className="flex flex-wrap gap-2">
|
||
<Select value={category} onValueChange={setCategory}>
|
||
<SelectTrigger size="sm" className="w-56" aria-label="Категория услуг">
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
<SelectItem value={ANY}>Все категории</SelectItem>
|
||
{categories.map((c) => (
|
||
<SelectItem key={c} value={c}>
|
||
{c}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
<SearchInput
|
||
autoFocus
|
||
size="sm"
|
||
className="min-w-56 flex-1"
|
||
value={query}
|
||
onValueChange={setQuery}
|
||
placeholder="Поиск по коду или названию"
|
||
/>
|
||
</div>
|
||
</div>
|
||
|
||
<ScrollArea className="h-[52vh]">
|
||
<ul className="divide-y divide-border/60">
|
||
{visible.map((item) => {
|
||
const already = added.includes(item.code)
|
||
const checked = already || selected.has(item.code)
|
||
return (
|
||
<li key={item.code}>
|
||
<label
|
||
className={cn(
|
||
"flex cursor-pointer items-start gap-3 px-5 py-2.5 transition",
|
||
already ? "cursor-default opacity-60" : "hover:bg-muted/50",
|
||
selected.has(item.code) && "bg-accent/40",
|
||
)}
|
||
>
|
||
<Checkbox
|
||
checked={checked}
|
||
disabled={already}
|
||
onCheckedChange={() => toggle(item.code)}
|
||
className="mt-0.5"
|
||
aria-label={item.name}
|
||
/>
|
||
<span className="min-w-0 flex-1 text-sm">
|
||
<span className="font-mono text-xs text-muted-foreground">{item.code}</span>{" "}
|
||
<span className="font-medium">{item.name}</span>
|
||
<span className="mt-0.5 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
|
||
{item.funding}
|
||
<span className="rounded bg-muted px-1.5 py-px text-[11px] font-medium">{item.category}</span>
|
||
{already && (
|
||
<span className="inline-flex items-center gap-0.5 text-primary">
|
||
<CheckIcon className="size-3" /> уже добавлена
|
||
</span>
|
||
)}
|
||
</span>
|
||
</span>
|
||
<span className="shrink-0 text-sm font-medium tabular">
|
||
{item.price ? formatMoney(item.price) : <span className="text-success">бесплатно</span>}
|
||
</span>
|
||
</label>
|
||
</li>
|
||
)
|
||
})}
|
||
{!visible.length && <li className="px-5 py-12 text-center text-sm text-muted-foreground">Услуги не найдены</li>}
|
||
</ul>
|
||
</ScrollArea>
|
||
|
||
<DialogFooter className="items-center border-t px-5 py-3 sm:justify-between">
|
||
<span className="text-sm text-muted-foreground">
|
||
{picked.length ? (
|
||
<>
|
||
Выбрано <b className="text-foreground tabular">{picked.length}</b> на{" "}
|
||
<b className="text-foreground tabular">{formatMoney(pickedSum)}</b>
|
||
</>
|
||
) : (
|
||
"Отметьте услуги в списке"
|
||
)}
|
||
</span>
|
||
<Button disabled={!picked.length} onClick={submit}>
|
||
Добавить услуги{picked.length ? ` (${picked.length})` : ""}
|
||
</Button>
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
)
|
||
}
|