improvement: all demo bugs fixed. give me more baby.

This commit is contained in:
2026-07-08 02:53:47 +03:30
parent 86b1e3afff
commit 8d334833ff
23 changed files with 876 additions and 626 deletions

View File

@@ -0,0 +1,245 @@
'use client';
import { useMemo, useState, type ReactNode } from 'react';
import { useTranslations } from 'next-intl';
import { MessageSquare } from 'lucide-react';
import { Badge } from '@/components/ui/shared/Badge';
import { Button } from '@/components/ui/shared/Button';
import { Checkbox } from '@/components/ui/shared/Checkbox';
import { CaseToothChartPanel } from '@/components/ui/lab/CaseToothChartPanel';
import { LabCaseAttachmentPreview } from '@/components/ui/lab/LabCaseAttachmentPreview';
import { LabCaseAttachmentsDialog } from '@/components/ui/lab/LabCaseAttachmentsDialog';
import { labTaskStatusVariant } from '@/components/ui/lab/labTaskStatusDisplay';
import {
formatToothList,
prosthesisTypeBadgeStyle,
} from '@/components/ui/treatment/prosthesisTypeDisplay';
import {
buildCaseProsthesisRows,
formatCaseDateTime,
formatPatientName,
latestCaseAttachment,
} from '@/components/ui/lab/caseDetailUtils';
import type { LabCaseDetail, LabTaskStatus } from '@/types/cases';
function CaseTaskProgressBar({ completed, total }: { completed: number; total: number }) {
const pct = total > 0 ? Math.round((completed / total) * 100) : 0;
return (
<div className="space-y-1">
<div className="flex items-center justify-between text-xs text-text-muted">
<span>
{completed}/{total}
</span>
<span>{pct}%</span>
</div>
<div className="h-1.5 rounded-full bg-border overflow-hidden">
<div
className="h-full rounded-full bg-primary transition-all duration-300"
style={{ width: `${pct}%` }}
/>
</div>
</div>
);
}
export interface CaseDetailPanelProps {
labCase: LabCaseDetail;
locale: string;
treatmentLabel: (type: string) => string;
statusOptions: { value: LabTaskStatus; label: string }[];
loadAttachmentBlob: (caseId: string, attachmentId: string) => Promise<Blob>;
/** Extra lines below patient mobile (e.g. connection-specific clinic/lab line). */
headerMetaLines?: ReactNode;
showCommentsButton?: boolean;
commentCount?: number;
onCommentsClick?: () => void;
canEditImportant?: boolean;
updatingImportant?: boolean;
onImportantChange?: (checked: boolean) => void;
commentsSection?: ReactNode;
}
export function CaseDetailPanel({
labCase,
locale,
treatmentLabel,
statusOptions,
loadAttachmentBlob,
headerMetaLines,
showCommentsButton = false,
commentCount = 0,
onCommentsClick,
canEditImportant = false,
updatingImportant = false,
onImportantChange,
commentsSection,
}: CaseDetailPanelProps) {
const t = useTranslations('cases');
const [attachmentsDialogOpen, setAttachmentsDialogOpen] = useState(false);
const prosthesisRows = useMemo(() => buildCaseProsthesisRows(labCase), [labCase]);
const previewAttachment = useMemo(() => latestCaseAttachment(labCase), [labCase]);
return (
<div className="space-y-4">
<header className="flex flex-wrap items-start justify-between gap-4 border-b border-border pb-3">
<div className="min-w-0 flex-1 space-y-1">
<h2 className="text-lg font-semibold text-text-primary">
{formatPatientName(labCase.patient)}
</h2>
{!canEditImportant && labCase.isImportant ? (
<Badge variant="warning" fixedWidth={false} className="mt-1">
{t('importantLabel')}
</Badge>
) : null}
<p className="text-sm text-text-muted">
{t('patientMobile')}: {labCase.patient.mobile}
</p>
{headerMetaLines}
<p className="text-sm text-text-muted">
{t('sentAt', { date: formatCaseDateTime(labCase.sentAt, locale) })}
</p>
<div className="pt-1 max-w-xs">
<p className="text-sm text-text-muted mb-1">
{t('taskProgressLabel', {
completed: labCase.taskProgress.completed,
total: labCase.taskProgress.total,
})}
</p>
<CaseTaskProgressBar
completed={labCase.taskProgress.completed}
total={labCase.taskProgress.total}
/>
</div>
</div>
<div className="flex shrink-0 flex-col items-end gap-2">
{showCommentsButton && onCommentsClick ? (
<Button type="button" variant="outline" size="sm" onClick={onCommentsClick}>
<MessageSquare className="h-4 w-4 me-1.5" />
{commentCount > 0
? t('commentsCount', { count: commentCount })
: t('showComments')}
</Button>
) : null}
{canEditImportant ? (
<Checkbox
checked={labCase.isImportant ?? false}
disabled={updatingImportant}
label={t('markCaseImportant')}
className="shrink-0"
onChange={(checked) => onImportantChange?.(checked)}
/>
) : null}
{previewAttachment && labCase.attachments.length > 0 ? (
<button
type="button"
onClick={() => setAttachmentsDialogOpen(true)}
className="aspect-square w-32 cursor-pointer rounded-[var(--radius-md)] border border-border/60 overflow-hidden transition-colors hover:border-primary/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
title={previewAttachment.fileName}
aria-label={t('viewAttachments')}
>
<LabCaseAttachmentPreview
caseId={labCase.id}
attachment={previewAttachment}
loadBlob={loadAttachmentBlob}
className="h-full w-full"
/>
</button>
) : null}
</div>
</header>
<CaseToothChartPanel
details={labCase.details}
prosthesisRows={prosthesisRows}
className="w-full"
/>
{labCase.details.length > 0 ? (
<div className="space-y-2">
<h3 className="text-sm font-medium text-text-primary">{t('treatmentDetails')}</h3>
<ul className="space-y-2 text-sm">
{labCase.details.map((detail) => (
<li key={detail.id} className="rounded-md bg-background border border-border p-2">
<div className="font-medium">{treatmentLabel(detail.treatmentType)}</div>
<div className="text-text-muted">
{t('teethLabel')}: {detail.teeth.join(', ') || '—'}
</div>
{detail.comment ? (
<div className="text-text-muted mt-1">{detail.comment}</div>
) : null}
</li>
))}
</ul>
</div>
) : null}
<div className="space-y-3">
<h3 className="text-sm font-medium text-text-primary">{t('tasksByTooth')}</h3>
{labCase.tasksByTooth.length === 0 ? (
<p className="text-sm text-text-muted">{t('noTasks')}</p>
) : (
labCase.tasksByTooth.map((group, groupIndex) => (
<div
key={`${group.treatmentDetailId}-${group.prosthesisTypeCode}`}
className="rounded-md border border-border p-3 space-y-2"
>
<div className="flex flex-wrap items-center gap-2">
<Badge
truncate
title={group.prosthesisTypeLabel}
style={prosthesisTypeBadgeStyle(group.prosthesisTypeCode, groupIndex)}
>
{group.prosthesisTypeLabel}
</Badge>
<span className="text-sm font-medium text-text-primary">
{t('toothGroupTitle', {
teeth: formatToothList(group.teeth),
prosthesis: group.prosthesisTypeLabel,
})}
</span>
</div>
<ul className="space-y-2">
{group.tasks.map((task) => (
<li key={task.id} className="rounded bg-background p-2 text-sm space-y-1">
<div className="flex flex-wrap items-center gap-2">
<span className="min-w-0 flex-1">
{task.stepOrder}. {task.stepLabel}
</span>
<Badge variant={labTaskStatusVariant(task.status)} fixedWidth={false}>
{statusOptions.find((opt) => opt.value === task.status)?.label ??
task.status}
</Badge>
</div>
<p className="text-[11px] text-text-muted">
{task.lastStatusChangedBy
? t('lastUpdatedBy', { name: task.lastStatusChangedBy.name })
: t('lastUpdatedUnknown')}
{task.lastStatusChangedAt
? ` · ${formatCaseDateTime(task.lastStatusChangedAt, locale)}`
: ''}
</p>
</li>
))}
</ul>
</div>
))
)}
</div>
{commentsSection}
<LabCaseAttachmentsDialog
open={attachmentsDialogOpen}
onClose={() => setAttachmentsDialogOpen(false)}
caseId={labCase.id}
attachments={labCase.attachments}
loadBlob={loadAttachmentBlob}
/>
</div>
);
}
export { CaseTaskProgressBar };

View File

@@ -19,6 +19,7 @@ interface CaseToothChartPanelProps {
/** Prosthesis mapping from case tasks or toothProsthesis rows. */
prosthesisRows: CaseToothChartProsthesisRow[];
scale?: number;
compact?: boolean;
className?: string;
}
@@ -26,7 +27,8 @@ interface CaseToothChartPanelProps {
export function CaseToothChartPanel({
details,
prosthesisRows,
scale = 0.5,
scale = 1,
compact = true,
className = '',
}: CaseToothChartPanelProps) {
const selected = useMemo(() => {
@@ -56,7 +58,7 @@ export function CaseToothChartPanel({
readOnly
scale={scale}
toothColors={toothColors}
compact
compact={compact}
className={className}
/>
);

View File

@@ -15,7 +15,7 @@ export function LabCaseAttachmentPreview({
caseId,
attachment,
loadBlob,
className = 'aspect-square w-full max-w-[11rem]',
className = 'h-full w-full',
}: LabCaseAttachmentPreviewProps) {
const [url, setUrl] = useState<string | null>(null);
const [failed, setFailed] = useState(false);

View File

@@ -0,0 +1,211 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Download, FileText } from 'lucide-react';
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
import { Button } from '@/components/ui/shared/Button';
import type { LabCaseAttachmentMeta } from '@/types/cases';
interface LabCaseAttachmentsDialogProps {
open: boolean;
onClose: () => void;
caseId: string;
attachments: LabCaseAttachmentMeta[];
loadBlob: (caseId: string, attachmentId: string) => Promise<Blob>;
}
function downloadBlob(blob: Blob, fileName: string) {
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = fileName;
anchor.click();
URL.revokeObjectURL(url);
}
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
const kb = bytes / 1024;
if (kb < 1024) return `${kb.toFixed(1)} KB`;
return `${(kb / 1024).toFixed(1)} MB`;
}
function AttachmentPreviewTile({
caseId,
attachment,
loadBlob,
onDownload,
}: {
caseId: string;
attachment: LabCaseAttachmentMeta;
loadBlob: (caseId: string, attachmentId: string) => Promise<Blob>;
onDownload: (blob: Blob, fileName: string) => void;
}) {
const t = useTranslations('cases');
const [url, setUrl] = useState<string | null>(null);
const [blob, setBlob] = useState<Blob | null>(null);
const [failed, setFailed] = useState(false);
const [downloading, setDownloading] = useState(false);
useEffect(() => {
let cancelled = false;
let objectUrl: string | null = null;
void (async () => {
try {
const loaded = await loadBlob(caseId, attachment.id);
if (cancelled) return;
objectUrl = URL.createObjectURL(loaded);
setBlob(loaded);
setUrl(objectUrl);
setFailed(false);
} catch {
if (!cancelled) setFailed(true);
}
})();
return () => {
cancelled = true;
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
}, [caseId, attachment.id, loadBlob]);
const isImage = attachment.mimeType.startsWith('image/');
const isPdf = attachment.mimeType === 'application/pdf';
return (
<article className="rounded-md border border-border bg-background p-3 space-y-3">
<div className="aspect-[4/3] w-full overflow-hidden rounded-md border border-border/60 bg-background-secondary">
{url && isImage ? (
<img src={url} alt={attachment.fileName} className="h-full w-full object-contain" />
) : url && isPdf ? (
<iframe src={url} title={attachment.fileName} className="h-full w-full border-0" />
) : (
<div className="flex h-full w-full flex-col items-center justify-center gap-2 p-4 text-text-muted">
<FileText className="h-10 w-10 shrink-0 icon-flat" aria-hidden />
<span className="line-clamp-2 text-center text-xs">
{failed ? t('attachmentPreviewUnavailable') : attachment.fileName}
</span>
</div>
)}
</div>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="text-sm font-medium text-text-primary truncate" title={attachment.fileName}>
{attachment.fileName}
</p>
<p className="text-xs text-text-muted mt-0.5">
{formatFileSize(attachment.sizeBytes)}
</p>
</div>
<Button
type="button"
variant="outline"
size="sm"
className="shrink-0"
disabled={!blob || downloading}
onClick={() => {
if (!blob) return;
setDownloading(true);
try {
onDownload(blob, attachment.fileName);
} finally {
setDownloading(false);
}
}}
>
<Download className="h-4 w-4 me-1.5" />
{t('downloadAttachment')}
</Button>
</div>
</article>
);
}
export function LabCaseAttachmentsDialog({
open,
onClose,
caseId,
attachments,
loadBlob,
}: LabCaseAttachmentsDialogProps) {
const t = useTranslations('cases');
const sortedAttachments = [...attachments].sort(
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
);
const handleDownload = useCallback((blob: Blob, fileName: string) => {
downloadBlob(blob, fileName);
}, []);
const [downloadingAll, setDownloadingAll] = useState(false);
const handleDownloadAll = useCallback(async () => {
if (sortedAttachments.length === 0) return;
setDownloadingAll(true);
try {
for (const attachment of sortedAttachments) {
const blob = await loadBlob(caseId, attachment.id);
downloadBlob(blob, attachment.fileName);
}
} finally {
setDownloadingAll(false);
}
}, [caseId, loadBlob, sortedAttachments]);
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
<div
className="w-full max-w-3xl max-h-[90vh] overflow-y-auto rounded-[var(--radius-md)] border border-border bg-background-secondary p-6 shadow-xl space-y-4"
role="dialog"
aria-modal="true"
aria-labelledby="case-attachments-title"
>
<div className="flex items-start justify-between gap-3">
<div>
<h2 id="case-attachments-title" className="text-lg font-semibold text-text-primary">
{t('attachmentsDialogTitle')}
</h2>
<p className="text-sm text-text-muted mt-1">{t('attachmentsDialogSubtitle')}</p>
</div>
<div className="flex items-center gap-2 shrink-0">
{sortedAttachments.length > 1 ? (
<Button
type="button"
variant="outline"
size="sm"
disabled={downloadingAll}
onClick={() => void handleDownloadAll()}
>
<Download className="h-4 w-4 me-1.5" />
{t('downloadAllAttachments')}
</Button>
) : null}
<DialogCloseButton onClick={onClose} />
</div>
</div>
{sortedAttachments.length === 0 ? (
<p className="text-sm text-text-muted">{t('noAttachments')}</p>
) : (
<div className="grid gap-4 sm:grid-cols-2">
{sortedAttachments.map((attachment) => (
<AttachmentPreviewTile
key={attachment.id}
caseId={caseId}
attachment={attachment}
loadBlob={loadBlob}
onDownload={handleDownload}
/>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -1,10 +1,9 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useState, type KeyboardEvent } from 'react';
import { useTranslations } from 'next-intl';
import { Eye, EyeOff } from 'lucide-react';
import { Eye, EyeOff, Send } from 'lucide-react';
import { formatApiErrorMessage } from '@/components/shared/formatApiError';
import { Button } from '@/components/ui/shared/Button';
import type { LabCaseComment } from '@/types/cases';
interface LabCaseCommentsPanelProps {
@@ -15,6 +14,13 @@ interface LabCaseCommentsPanelProps {
onPost: (body: string, visibleToClinic?: boolean) => Promise<LabCaseComment>;
onToggleVisibility?: (commentId: string, visible: boolean) => Promise<LabCaseComment>;
onError?: (message: string) => void;
/**
* Deferred composer: the parent owns the draft value and triggers the post
* elsewhere (e.g. the "Send to lab" button). No send icon is shown.
*/
deferSubmit?: boolean;
composerValue?: string;
onComposerValueChange?: (value: string) => void;
}
export function LabCaseCommentsPanel({
@@ -25,6 +31,9 @@ export function LabCaseCommentsPanel({
onPost,
onToggleVisibility,
onError,
deferSubmit = false,
composerValue,
onComposerValueChange,
}: LabCaseCommentsPanelProps) {
const t = useTranslations('caseComments');
const [comments, setComments] = useState<LabCaseComment[]>([]);
@@ -51,7 +60,7 @@ export function LabCaseCommentsPanel({
async function handlePost() {
const trimmed = body.trim();
if (!trimmed || !canPost) return;
if (!trimmed || !canPost || posting) return;
setPosting(true);
try {
const created = await onPost(trimmed, visibleToClinic);
@@ -65,6 +74,13 @@ export function LabCaseCommentsPanel({
}
}
function handleComposerKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
void handlePost();
}
}
async function handleToggle(comment: LabCaseComment) {
if (!onToggleVisibility || !canToggleVisibility) return;
try {
@@ -112,12 +128,8 @@ export function LabCaseCommentsPanel({
type="button"
onClick={() => void handleToggle(comment)}
className="shrink-0 p-1 rounded hover:bg-border text-text-muted"
title={
comment.visibleToClinic ? t('makeHidden') : t('makeVisible')
}
aria-label={
comment.visibleToClinic ? t('makeHidden') : t('makeVisible')
}
title={comment.visibleToClinic ? t('makeHidden') : t('makeVisible')}
aria-label={comment.visibleToClinic ? t('makeHidden') : t('makeVisible')}
>
{comment.visibleToClinic ? (
<Eye className="h-4 w-4" />
@@ -132,33 +144,54 @@ export function LabCaseCommentsPanel({
</ul>
)}
{canPost ? (
<div className="space-y-2 border-t border-border pt-2">
{canPost && deferSubmit ? (
<div className="border-t border-border pt-2">
<textarea
value={body}
onChange={(e) => setBody(e.target.value)}
value={composerValue ?? ''}
onChange={(e) => onComposerValueChange?.(e.target.value)}
placeholder={t('placeholder')}
rows={2}
className="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm resize-none"
/>
{canToggleVisibility ? (
<label className="flex items-center gap-2 text-xs text-text-muted cursor-pointer">
<input
type="checkbox"
checked={visibleToClinic}
onChange={(e) => setVisibleToClinic(e.target.checked)}
/>
{t('visibleToClinicToggle')}
</label>
) : null}
<Button
type="button"
size="sm"
disabled={posting || !body.trim()}
onClick={() => void handlePost()}
>
{t('post')}
</Button>
</div>
) : canPost ? (
<div className="flex items-end gap-2 border-t border-border pt-2">
<textarea
value={body}
onChange={(e) => setBody(e.target.value)}
onKeyDown={handleComposerKeyDown}
placeholder={t('placeholder')}
rows={2}
className="min-w-0 flex-1 rounded-md border border-border bg-surface px-3 py-2 text-sm resize-none"
/>
<div className="flex items-center gap-1 pb-1">
{canToggleVisibility ? (
<button
type="button"
onClick={() => setVisibleToClinic((v) => !v)}
className={`shrink-0 p-2 rounded-md border transition-colors ${
visibleToClinic
? 'border-primary/40 bg-primary/10 text-primary'
: 'border-border text-text-muted hover:text-text-primary'
}`}
title={visibleToClinic ? t('composerVisible') : t('composerHidden')}
aria-label={visibleToClinic ? t('composerVisible') : t('composerHidden')}
aria-pressed={visibleToClinic}
>
{visibleToClinic ? <Eye className="h-4 w-4" /> : <EyeOff className="h-4 w-4" />}
</button>
) : null}
<button
type="button"
onClick={() => void handlePost()}
disabled={posting || !body.trim()}
className="shrink-0 p-2 rounded-md bg-primary text-white transition-colors hover:opacity-90 disabled:opacity-40 disabled:cursor-not-allowed"
title={t('send')}
aria-label={t('send')}
>
<Send className="h-4 w-4" />
</button>
</div>
</div>
) : null}
</div>

View File

@@ -0,0 +1,40 @@
import type { LabCaseDetail } from '@/types/cases';
import type { CaseToothChartProsthesisRow } from '@/components/ui/lab/CaseToothChartPanel';
export function formatPatientName(patient: { firstName: string; lastName: string }) {
return `${patient.firstName} ${patient.lastName}`.trim();
}
export function formatCaseDateTime(value: string | null, locale: string) {
if (!value) return '—';
return new Intl.DateTimeFormat(locale, {
dateStyle: 'medium',
timeStyle: 'short',
}).format(new Date(value));
}
export function buildCaseProsthesisRows(labCase: LabCaseDetail): CaseToothChartProsthesisRow[] {
if (labCase.toothProsthesis.length > 0) {
const byCode = new Map<string, string[]>();
for (const row of labCase.toothProsthesis) {
const teeth = byCode.get(row.prosthesisTypeCode) ?? [];
if (!teeth.includes(row.tooth)) teeth.push(row.tooth);
byCode.set(row.prosthesisTypeCode, teeth);
}
return [...byCode.entries()].map(([prosthesisTypeCode, teeth]) => ({
prosthesisTypeCode,
teeth,
}));
}
return labCase.tasksByTooth.map((g) => ({
prosthesisTypeCode: g.prosthesisTypeCode,
teeth: g.teeth,
}));
}
export function latestCaseAttachment(labCase: LabCaseDetail) {
if (!labCase.attachments.length) return null;
return [...labCase.attachments].sort(
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
)[0];
}