improvment: all confirmation promts replaced with a shared confirma dialog component.

This commit is contained in:
2026-10-06 17:30:05 +03:30
parent 0278a1859c
commit 13c1fff61d
22 changed files with 921 additions and 200 deletions

View File

@@ -57,6 +57,7 @@ Reference: `app/.../treatment/page.tsx` + `components/ui/treatment/TreatmentWork
| Need | Use |
|------|-----|
| Date filter / due date field | `AppDateInput` (`ui/shared/`) — not `<input type="date">` |
| Yes/no warning | `useConfirm()` (`ConfirmProvider` in the dashboard layout) — not `window.confirm` / `alert` / `prompt` |
| Filter or inline `<select>` | `FORM_SELECT_CLASS` from `components/shared/formSelectStyles.ts` |
| Tiny select (sort dir, etc.) | `FORM_SELECT_COMPACT_CLASS` |
| Desktop data table | `Table` (`ui/shared/Table.tsx`) — logical alignment only |

View File

@@ -15,8 +15,8 @@ alwaysApply: false
- **Outsource** (`POST /cases/:id/outsource`, label `cases.sendCase`): one linked lab, checked in-progress prosthesis-job steps, one `LAB_OUTSOURCE` child case. The child stores the sending lab as `referringClinicName` and clears dentist and partner clinic. Those parent steps leave Tasks until the child completes them (written back with no actor). Sender detail shows only that direct lab. The sender chart stays the full plan; the child chart is the selected jobs plus pontics on that bridge. Recall before any of those steps is completed. Received child cases have Outsource, not Start, Delete, or Edit. Case-level steps stay on the owning lab.
- **Share link:** QR + URL when the case is sent **or** a lab-origin case is started; token API + focus page — see `.cursor/skills/lab-case-share-link/SKILL.md`.
- **One plan:** a live case has one prosthesis plan. Clinic send still uses `treatmentDetailId` as `sourceKey`. Lab-origin and outsource children use the case id. `LabCaseLine` is gone. Detail and New case use `UnderlineTabs`: Details, Files, Messages. Origin is one combobox of linked clinics and labs, or a typed name. Dentist/Technician stays optional. Arch jobs (`UA`/`LA`) highlight the read-only FDI chart.
- **Case Sheet PDF:** same layout for portrait and landscape (Download PDF menu). One A4 page, scaled to fit — the chart is never split. Header is a flex row: current organization name (one line, ellipsis), Nudentic lockup aligned with that text, share QR at 88px inside a 96px frame with `fill` off (a stretched SVG is dropped by html2canvas; not a table cell). Print ink is `prosthesisTypePrintColorFromCatalog` (heaviest family swatch). Prosthesis rows are SVG boxes. Chart is 85% of the page width with capped glyph height, shared upper column widths, outline-only unselected teeth, root vs crown fills, a larger gap under the upper caption, and matching tooth/number/midline gaps on both arches. Bridge marks match the FDI chart: 10px `#009cae` dots on the column boundary in the tooth-to-number gap. `onclone` sizes only the lockup SVGs. Hex inline styles only. Optional `externalCode` replaces the order number.
- **Detail chrome:** **Mark as important** is centered in the header. Edit and Outsource are at the top of the end column. External code sits under the progress bar in the start column, same width as the bar; billed price is under that. Comments and Get PDF are a matching pair, wide enough for the icon and the full label. The sent-date line reads “Outsource {date}”.
- **Case Sheet PDF:** same layout for portrait and landscape (Download PDF menu). One A4 page, scaled to fit — the chart is never split. Header is a flex row: current organization name (one line, 48px line box so html2canvas does not clip the glyphs), Nudentic lockup aligned with that text, share QR at 88px inside a 96px frame with `fill` off (a stretched SVG is dropped by html2canvas; not a table cell). Print ink is `prosthesisTypePrintColorFromCatalog` (heaviest family swatch). Prosthesis rows are SVG boxes. Chart is 85% of the page width with capped glyph height, shared upper column widths, outline-only unselected teeth, root vs crown fills, a larger gap under the upper caption, and matching tooth/number/midline gaps on both arches. Bridge marks match the FDI chart: 10px `#009cae` dots on the column boundary in the tooth-to-number gap. `onclone` sizes the lockup SVGs and the organization-name line box. Hex inline styles only. Optional `externalCode` replaces the order number.
- **Detail chrome:** **Mark as important** is centered in the header. Edit and Outsource are at the top of the end column. External code sits under the progress bar in the start column, same width as the bar; billed price is under that. Get PDF, Add case, and Add files are primary `CaseLifecycleButton`s with no icon, the same width as Outsource. There is no Comments button, and opening Messages does not scroll the page. File cards: name at the start and checkbox at the end, then a clipped preview, then size over date at the start with the View/Download menu centered at the end. The sent-date line reads “Outsource {date}”.
- **Drafts rail:** unstarted lab-origin cases sit in a collapsed `TreatmentRailSection`; expands on click or **Add case**. Main list is received + started cases (`drafts=exclude` / `drafts=only`), newest first by `listedAt` (`LAB_CASE_LIST_ORDER_BY`; trigger `lab_cases_listed_at_sync` = `COALESCE(startedAt, sentAt)`). Never `orderBy startedAt, sentAt` and never a `GENERATED ALWAYS` `listedAt`.
- **Add case / Start / Delete draft:** `TAB_CASES_EDIT`. Delete only unstarted lab-origin drafts (`origin === LAB_INTERNAL && !startedAt`). Comments on Cases accept `TAB_CASES_*` (owners are not blocked by Tasks opt-in).

View File

@@ -47,13 +47,13 @@ List item shape: `prosthesisGroups: { prosthesisTypeCode, teeth[], ponticTeeth?
- Comments: shared `LabCaseCommentsPanel` + `tasksApi` comment routes (`viewerSide="LAB"`). Newest-first; sent/received use logical start/end alignment (RTL-safe). Compact `h-9` composer with primary send + visibility controls. Lab-origin cases (`LAB_INTERNAL`, including after Start) are visible to lab comments/mark-read — do not require `sentAt` / `LabCaseSend`. Generated cases hide the eye until a linked clinic is selected; that eye publishes the comment to the clinic. A linked lab reads the thread on the share page and does not use the eye. Received cases use it for the clinic. Lab-to-lab cases use the same eye button for the sending lab: off keeps the comment on this lab, on shows it in that lab's handoff and notifies them. Comments that already existed on a lab-to-lab case stay shared.
- Mark read: `POST /notifications/mark-case-read` on select (Cases tab badge)
- FDI chart (`CaseToothChartPanel`): prosthesis colors + **connected bridge dots** from `selectionGroupId` (`buildCaseConnectedTeeth` / `buildCaseProsthesisRows` in `caseDetailUtils.ts`).
- **Important + external code** (`TAB_CASES_EDIT`): **Mark as important** is centered in the header. External code is under the progress bar in the start column, same width as the bar (no title; placeholder only); billed price is under that. Save code on blur → `PATCH /cases/:id/external-code`. Edit and Outsource use `CaseLifecycleButton` width (Treatment Lab dispatch / Chart / Add detail). Comments and Get PDF are a wider matching pair so the icon and full label stay visible. Start and Delete on a draft use that same width. The sent-date line is `cases.sentAt` (“Outsource {date}”).
- **Important + external code** (`TAB_CASES_EDIT`): **Mark as important** is centered in the header. External code is under the progress bar in the start column, same width as the bar (no title; placeholder only); billed price is under that. Save code on blur → `PATCH /cases/:id/external-code`. Edit, Outsource, Get PDF, Add case, and Add files use `CaseLifecycleButton` (primary, no icon; Treatment Lab dispatch / Chart / Add detail width). There is no Comments button. Opening Messages does not scroll the page. Start and Delete on a draft use that same width. The sent-date line is `cases.sentAt` (“Outsource {date}”). File cards (`CaseFilesPanel`): name at the start and checkbox at the end, a clipped preview between them and the footer, then size over date at the start with the View/Download menu centered at the end.
- **Case Sheet PDF** — see below.
- **Share link (sent cases):** `shareUrl` on detail; attachment preview left + QR thumb right; `LabCaseShareQrDialog` (`react-qr-code`). Full flow: `.cursor/skills/lab-case-share-link/SKILL.md`.
## Case Sheet PDF
**Entry:** Get PDF beside Comments on `CaseDetailPanel` — menu chooses portrait or landscape.
**Entry:** Get PDF on `CaseDetailPanel` (primary, same width as Outsource, no icon) — menu chooses portrait or landscape. Organization name uses a 48px line box so the glyphs are not clipped.
**Builder:** [`caseSheetPdf.ts`](frontend/src/components/lab/caseSheetPdf.ts) → off-screen [`CaseSheetPrintLayout.tsx`](frontend/src/components/ui/lab/CaseSheetPrintLayout.tsx) wrapped in `NextIntlClientProvider` → `html2canvas` → `jspdf` A4 (ISO √2 — prints cleanly onto A3–A6).
### html2canvas + Tailwind v4 (required)

View File

@@ -15,6 +15,8 @@
"or": "Or",
"and": "and",
"close": "Close",
"confirmTitle": "Please confirm",
"confirmAction": "Confirm",
"redirecting": "Redirecting…",
"readOnlyAccess": "Read-only access for this organization.",
"errorGeneric": "Something went wrong",
@@ -565,6 +567,9 @@
"filesAdd": "Add files",
"filesEmpty": "No files on this case.",
"filesRemove": "Remove",
"filesView": "View",
"filesMenu": "File actions",
"filesPreviewUnavailable": "This file cannot be previewed.",
"partnerClinicNone": "None",
"dueDateField": "Due date",
"caseLinesTitle": "Work lines",

View File

@@ -15,6 +15,8 @@
"or": "یا",
"and": "و",
"close": "بستن",
"confirmTitle": "لطفاً تأیید کنید",
"confirmAction": "تأیید",
"redirecting": "در حال انتقال...",
"readOnlyAccess": "دسترسی فقط خواندنی برای این سازمان.",
"errorGeneric": "خطایی رخ داده است",
@@ -566,6 +568,9 @@
"filesAdd": "افزودن فایل",
"filesEmpty": "فایلی روی این پرونده نیست.",
"filesRemove": "حذف",
"filesView": "مشاهده",
"filesMenu": "عملیات فایل",
"filesPreviewUnavailable": "پیش‌نمایش این فایل ممکن نیست.",
"partnerClinicNone": "هیچ‌کدام",
"dueDateField": "موعد",
"caseLinesTitle": "خطوط کار",

View File

@@ -15,6 +15,8 @@
"or": "Of",
"and": "en",
"close": "Sluiten",
"confirmTitle": "Bevestig dit",
"confirmAction": "Bevestigen",
"redirecting": "Bezig met doorsturen...",
"readOnlyAccess": "Alleen-lezen toegang voor deze organisatie.",
"errorGeneric": "Er is iets misgegaan",
@@ -566,6 +568,9 @@
"filesAdd": "Bestanden toevoegen",
"filesEmpty": "Geen bestanden bij deze case.",
"filesRemove": "Verwijderen",
"filesView": "Bekijken",
"filesMenu": "Bestandsacties",
"filesPreviewUnavailable": "Dit bestand kan niet worden bekeken.",
"partnerClinicNone": "Geen",
"dueDateField": "Vervaldatum",
"caseLinesTitle": "Werklijnen",

View File

@@ -10,6 +10,7 @@ import Sidebar from '@/components/ui/shared/Sidebar';
import { TopBarControls } from '@/components/ui/shared/TopBarControls';
import { DashboardAccountMenu } from '@/components/ui/dashboard/DashboardAccountMenu';
import { NotificationBell } from '@/components/ui/notifications/NotificationBell';
import { ConfirmProvider } from '@/components/ui/shared/ConfirmProvider';
import { ToastProvider } from '@/components/ui/shared/ToastProvider';
import { RealtimeProvider } from '@/lib/realtime/RealtimeProvider';
import {
@@ -89,6 +90,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
return (
<ToastProvider>
<ConfirmProvider>
<RealtimeProvider>
<div className="app-dashboard-shell flex h-[100dvh] app-web-bg text-text-primary">
{sidebarOpen ? (
@@ -116,6 +118,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
</div>
</div>
</RealtimeProvider>
</ConfirmProvider>
</ToastProvider>
);
}

View File

@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest';
import { caseFilePreviewKind, caseFilePreviewMime } from './caseFilePreview';
describe('caseFilePreviewKind', () => {
it('treats common images, pdf, and text as previewable', () => {
expect(caseFilePreviewKind('scan.jpg', 'application/octet-stream')).toBe('image');
expect(caseFilePreviewKind('note.TXT', '')).toBe('text');
expect(caseFilePreviewKind('sheet.pdf', 'application/pdf')).toBe('pdf');
expect(caseFilePreviewKind('scan.stl', 'model/stl')).toBeNull();
expect(caseFilePreviewKind('photo.heic', 'image/heic')).toBeNull();
});
it('stamps a browser mime when the stored type is generic', () => {
expect(caseFilePreviewMime('a.pdf', 'application/octet-stream', 'pdf')).toBe('application/pdf');
expect(caseFilePreviewMime('a.png', 'application/octet-stream', 'image')).toBe('image/png');
expect(caseFilePreviewMime('a.txt', 'text/plain; charset=utf-8', 'text')).toBe('text/plain');
});
});

View File

@@ -0,0 +1,53 @@
export type CaseFilePreviewKind = 'image' | 'pdf' | 'text';
const IMAGE_EXT = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg']);
const TEXT_EXT = new Set(['txt', 'csv', 'log', 'md', 'json']);
function extensionOf(fileName: string): string {
const base = fileName.trim().toLowerCase();
const dot = base.lastIndexOf('.');
if (dot <= 0 || dot === base.length - 1) return '';
return base.slice(dot + 1);
}
function mimeOf(mimeType: string): string {
return mimeType.toLowerCase().split(';')[0]?.trim() ?? '';
}
/** Browser-readable types we can show in a card or a view dialog. */
export function caseFilePreviewKind(
fileName: string,
mimeType: string,
): CaseFilePreviewKind | null {
const mime = mimeOf(mimeType);
if (mime.startsWith('image/') && mime !== 'image/heic' && mime !== 'image/heif') {
return 'image';
}
if (mime === 'application/pdf') return 'pdf';
if (mime.startsWith('text/')) return 'text';
const ext = extensionOf(fileName);
if (IMAGE_EXT.has(ext)) return 'image';
if (ext === 'pdf') return 'pdf';
if (TEXT_EXT.has(ext)) return 'text';
return null;
}
/** Mime to stamp on a preview blob when the stored type is generic. */
export function caseFilePreviewMime(
fileName: string,
mimeType: string,
kind: CaseFilePreviewKind,
): string {
const mime = mimeOf(mimeType);
if (kind === 'pdf') return 'application/pdf';
if (kind === 'text') return mime.startsWith('text/') ? mime : 'text/plain';
if (mime.startsWith('image/') && mime !== 'image/heic' && mime !== 'image/heif') return mime;
const ext = extensionOf(fileName);
if (ext === 'png') return 'image/png';
if (ext === 'gif') return 'image/gif';
if (ext === 'webp') return 'image/webp';
if (ext === 'svg') return 'image/svg+xml';
if (ext === 'bmp') return 'image/bmp';
return 'image/jpeg';
}

View File

@@ -112,6 +112,23 @@ export async function downloadCaseSheetPdf({
});
// Brand mark viewBoxes are thousands of units. Without an explicit
// pixel size, html2canvas lays them out huge and pads the page.
clonedDoc.querySelectorAll('[data-case-sheet-org]').forEach((node) => {
if (!(node instanceof HTMLElement)) return;
node.style.display = 'flex';
node.style.alignItems = 'center';
node.style.height = '48px';
node.style.lineHeight = '48px';
node.style.overflow = 'hidden';
const text = node.firstElementChild;
if (!(text instanceof HTMLElement)) return;
text.style.display = 'block';
text.style.minWidth = '0';
text.style.maxWidth = '100%';
text.style.overflow = 'visible';
text.style.lineHeight = '48px';
text.style.paddingTop = '0';
text.style.paddingBottom = '0';
});
clonedDoc.querySelectorAll('[data-case-sheet-lockup]').forEach((node) => {
if (!(node instanceof HTMLElement)) return;
node.style.height = '28px';

View File

@@ -17,6 +17,7 @@ import { AppointmentBookingModal } from '@/components/ui/appointments/Appointmen
import { AppointmentScheduleGrid } from '@/components/ui/appointments/AppointmentScheduleGrid';
import { AppointmentScheduleLegend } from '@/components/ui/appointments/AppointmentScheduleLegend';
import { ScheduleDayPicker } from '@/components/ui/shared/ScheduleDayPicker';
import { useConfirm } from '@/components/ui/shared/ConfirmProvider';
import { useToast } from '@/lib/hooks/useToast';
import type { AppointmentPurpose } from '@/types/appointment';
import { getUserFacingError } from '@/components/shared/formatApiError';
@@ -26,6 +27,7 @@ export function AppointmentsPage() {
const t = useTranslations('appointments');
const tErrors = useTranslations('errors');
const tCommon = useTranslations('common');
const confirm = useConfirm();
const router = useRouter();
const { currentOrganization } = useAuth();
const [scheduleDate, setScheduleDate] = useState(() => startOfLocalDay(new Date()));
@@ -199,7 +201,13 @@ export function AppointmentsPage() {
if (!activeEditingAppointment) {
return;
}
if (!window.confirm(t('confirmRemove'))) {
if (
!(await confirm({
message: t('confirmRemove'),
confirmLabel: tCommon('delete'),
tone: 'danger',
}))
) {
return;
}
setDeletingAppointment(true);

View File

@@ -12,6 +12,7 @@ import { BillingSheetEditor } from '@/components/ui/billing/BillingSheetEditor';
import { isCommissionSheetKind } from '@/components/billing/billingSheetKind';
import { billingApi } from '@/lib/api/billing';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { useConfirm } from '@/components/ui/shared/ConfirmProvider';
import { useToast } from '@/lib/hooks/useToast';
import { useAppFormatters } from '@/lib/hooks/useAppFormatters';
import { toDateInputValue } from '@/components/appointments/appointmentTime';
@@ -47,6 +48,7 @@ export function BillingSheetsPanel({
const t = useTranslations('billing');
const tCommon = useTranslations('common');
const tErrors = useTranslations('errors');
const confirm = useConfirm();
const toast = useToast();
const { formatTableDate } = useAppFormatters();
const commission = isCommissionSheetKind(kind);
@@ -163,7 +165,15 @@ export function BillingSheetsPanel({
}
async function handleDelete(sheet: BillingSheet) {
if (!window.confirm(t('confirmDeleteSheet'))) return;
if (
!(await confirm({
message: t('confirmDeleteSheet'),
confirmLabel: tCommon('delete'),
tone: 'danger',
}))
) {
return;
}
try {
await billingApi.deleteSheet(sheet.id);
toast.showSuccess(t('sheetDeleted'));

View File

@@ -9,6 +9,7 @@ import {
isArchSentinel,
toothJobRowsForDetail,
} from '@/components/treatment/prosthesisTree';
import { useConfirm } from '@/components/ui/shared/ConfirmProvider';
import { CaseFilesPanel } from '@/components/ui/lab/CaseFilesPanel';
import { CaseHistoryRounds } from '@/components/ui/lab/CaseHistoryRounds';
import { LabCaseCommentsPanel } from '@/components/ui/lab/LabCaseCommentsPanel';
@@ -156,6 +157,7 @@ export function CaseCreatePanel({
const tTreatment = useTranslations('treatment');
const tErrors = useTranslations('errors');
const tCommon = useTranslations('common');
const confirm = useConfirm();
const locale = useLocale();
const [referringClinicName, setReferringClinicName] = useState(
@@ -386,7 +388,15 @@ export function CaseCreatePanel({
async function handleDelete() {
if (!canEdit) return;
if (!window.confirm(t('confirmDeleteDraftCase'))) return;
if (
!(await confirm({
message: t('confirmDeleteDraftCase'),
confirmLabel: tCommon('delete'),
tone: 'danger',
}))
) {
return;
}
deletingRef.current = true;
skipSaveRef.current = true;
setDeleting(true);

View File

@@ -2,7 +2,6 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useLocale, useMessages, useTranslations } from 'next-intl';
import { Download, MessageSquare } from 'lucide-react';
import { Badge } from '@/components/ui/shared/Badge';
import { Button } from '@/components/ui/shared/Button';
import { CaseLifecycleButton } from '@/components/ui/lab/CaseLifecycleButton';
@@ -196,9 +195,6 @@ export interface CaseDetailPanelProps {
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;
@@ -232,9 +228,6 @@ export function CaseDetailPanel({
statusOptions,
loadAttachmentBlob,
headerMetaLines,
showCommentsButton = false,
commentCount = 0,
onCommentsClick,
canEditImportant = false,
updatingImportant = false,
onImportantChange,
@@ -280,11 +273,6 @@ export function CaseDetailPanel({
setExternalCodeDraft(labCase.externalCode ?? '');
}, [labCase.id, labCase.externalCode]);
useEffect(() => {
if (section !== 'messages') return;
document.getElementById('case-comments')?.scrollIntoView({ behavior: 'smooth' });
}, [section]);
useEffect(() => {
if (!sheetMenuOpen) return;
function onPointerDown(event: MouseEvent) {
@@ -393,10 +381,7 @@ export function CaseDetailPanel({
}
}
const commentsLabel =
commentCount > 0 ? t('commentsCount', { count: commentCount }) : t('showComments');
const pdfLabel = t('downloadCaseSheet');
const secondaryActionLabels = [commentsLabel, pdfLabel];
const legacySharedTasks = labCase.tasksByTooth.find(
(group) => group.prosthesisTypeCode === CASE_TASK_SCOPE,
)?.tasks ?? [];
@@ -528,24 +513,10 @@ export function CaseDetailPanel({
</div>
) : null}
<div className="flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto">
{showCommentsButton && onCommentsClick ? (
<CaseLifecycleButton
variant="outline"
icon={<MessageSquare className="h-4 w-4 shrink-0" />}
label={commentsLabel}
matchLabels={secondaryActionLabels}
onClick={() => {
setSection('messages');
onCommentsClick?.();
}}
/>
) : null}
<div ref={sheetMenuRef} className="relative">
<CaseLifecycleButton
variant="outline"
icon={<Download className="h-4 w-4 shrink-0" />}
variant="primary"
label={pdfLabel}
matchLabels={secondaryActionLabels}
isLoading={downloadingPdf}
ariaExpanded={sheetMenuOpen}
ariaHaspopup="menu"
@@ -601,11 +572,7 @@ export function CaseDetailPanel({
/>
) : null}
{section === 'messages' ? (
<div id="case-comments" className="scroll-mt-4">
{commentsSection}
</div>
) : null}
{section === 'messages' ? commentsSection : null}
{section === 'details' ? (
<>

View File

@@ -1,12 +1,39 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { Download, Plus } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { File as FileIcon, MoreVertical } from 'lucide-react';
import { useLocale, useTranslations } from 'next-intl';
import { CaseLifecycleButton } from '@/components/ui/lab/CaseLifecycleButton';
import { Button } from '@/components/ui/shared/Button';
import { Checkbox } from '@/components/ui/shared/Checkbox';
import { WORKSPACE_ACTION_BTN_CLASS } from '@/components/ui/shared/WorkspaceActionLabel';
import {
caseFilePreviewKind,
caseFilePreviewMime,
type CaseFilePreviewKind,
} from '@/components/lab/caseFilePreview';
import { formatAppDateTime, formatAppNumber } from '@/lib/i18n/format';
import type { LabCaseAttachmentMeta } from '@/types/cases';
/** Skip automatic thumbnails above this size. View still loads the file on demand. */
const PREVIEW_BYTE_CAP = 25 * 1024 * 1024;
type CardPreview = {
status: 'loading' | 'ready' | 'error';
kind: CaseFilePreviewKind | null;
url?: string;
text?: string;
};
type ViewerState = {
fileName: string;
kind: CaseFilePreviewKind | null;
status: 'loading' | 'ready' | 'unavailable';
url?: string;
text?: string;
ownedUrl: boolean;
};
function downloadBlob(blob: Blob, fileName: string) {
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
@@ -16,10 +43,30 @@ function downloadBlob(blob: Blob, fileName: string) {
URL.revokeObjectURL(url);
}
function formatBytes(size: number): string {
if (size < 1024) return `${size} B`;
if (size < 1024 * 1024) return `${Math.round(size / 1024)} KB`;
return `${(size / (1024 * 1024)).toFixed(1)} MB`;
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`;
}
/** Card titles stay short. The full name remains on the checkbox and in View. */
function shortFileName(fileName: string, max = 16): string {
if (fileName.length <= max) return fileName;
return `${fileName.slice(0, max).trimEnd()}…`;
}
function fileExtension(fileName: string): string {
const base = fileName.trim();
const dot = base.lastIndexOf('.');
if (dot <= 0 || dot === base.length - 1) return '';
return base.slice(dot + 1).toUpperCase();
}
function blobForKind(blob: Blob, file: LabCaseAttachmentMeta, kind: CaseFilePreviewKind): Blob {
const type = caseFilePreviewMime(file.fileName, file.mimeType, kind);
if (blob.type === type) return blob;
return new Blob([blob], { type });
}
export function CaseFilesPanel({
@@ -42,14 +89,120 @@ export function CaseFilesPanel({
onRemove?: (attachmentId: string) => void;
}) {
const t = useTranslations('cases');
const tCommon = useTranslations('common');
const locale = useLocale();
const inputRef = useRef<HTMLInputElement>(null);
const onDownloadRef = useRef(onDownload);
onDownloadRef.current = onDownload;
const menuRef = useRef<HTMLDivElement>(null);
const viewGen = useRef(0);
const [selected, setSelected] = useState<string[]>([]);
const [busy, setBusy] = useState(false);
const [menuId, setMenuId] = useState<string | null>(null);
const [previews, setPreviews] = useState<Record<string, CardPreview>>({});
const [viewer, setViewer] = useState<ViewerState | null>(null);
const attachmentKey = attachments.map((file) => file.id).join('\n');
useEffect(() => {
setSelected((prev) => prev.filter((id) => attachments.some((file) => file.id === id)));
}, [attachments]);
useEffect(() => {
let cancelled = false;
const urls: string[] = [];
const next: Record<string, CardPreview> = {};
const jobs = attachments.filter((file) => {
const kind = caseFilePreviewKind(file.fileName, file.mimeType);
if (!kind || file.sizeBytes > PREVIEW_BYTE_CAP) return false;
next[file.id] = { status: 'loading', kind };
return true;
});
setPreviews(next);
void Promise.all(
jobs.map(async (file) => {
const kind = caseFilePreviewKind(file.fileName, file.mimeType);
if (!kind) return;
try {
const raw = await onDownloadRef.current(file);
if (cancelled) return;
if (kind === 'text') {
const text = await blobForKind(raw, file, kind).text();
if (cancelled) return;
setPreviews((prev) => ({
...prev,
[file.id]: { status: 'ready', kind, text },
}));
return;
}
const url = URL.createObjectURL(blobForKind(raw, file, kind));
if (cancelled) {
URL.revokeObjectURL(url);
return;
}
urls.push(url);
setPreviews((prev) => ({
...prev,
[file.id]: { status: 'ready', kind, url },
}));
} catch {
if (!cancelled) {
setPreviews((prev) => ({
...prev,
[file.id]: { status: 'error', kind },
}));
}
}
}),
);
return () => {
cancelled = true;
for (const url of urls) URL.revokeObjectURL(url);
};
// attachmentKey is the stable identity of the current file list.
// eslint-disable-next-line react-hooks/exhaustive-deps -- refetch only when the files change
}, [attachmentKey]);
useEffect(() => {
if (!menuId) return;
function onPointerDown(event: MouseEvent) {
if (!menuRef.current?.contains(event.target as Node)) setMenuId(null);
}
function onKeyDown(event: KeyboardEvent) {
if (event.key === 'Escape') setMenuId(null);
}
document.addEventListener('mousedown', onPointerDown);
document.addEventListener('keydown', onKeyDown);
return () => {
document.removeEventListener('mousedown', onPointerDown);
document.removeEventListener('keydown', onKeyDown);
};
}, [menuId]);
useEffect(() => {
if (!viewer) return;
function onKeyDown(event: KeyboardEvent) {
if (event.key === 'Escape') closeViewer();
}
document.addEventListener('keydown', onKeyDown);
return () => document.removeEventListener('keydown', onKeyDown);
}, [viewer]);
function showViewer(next: ViewerState | null) {
setViewer((current) => {
if (current?.ownedUrl && current.url && current.url !== next?.url) {
URL.revokeObjectURL(current.url);
}
return next;
});
}
function closeViewer() {
viewGen.current += 1;
showViewer(null);
}
function toggle(id: string, checked: boolean) {
setSelected((prev) => (checked ? [...prev, id] : prev.filter((item) => item !== id)));
}
@@ -70,101 +223,300 @@ export function CaseFilesPanel({
}
}
async function openView(file: LabCaseAttachmentMeta) {
setMenuId(null);
const gen = ++viewGen.current;
const kind = caseFilePreviewKind(file.fileName, file.mimeType);
const cached = previews[file.id];
if (cached?.status === 'ready' && (cached.url || cached.text != null)) {
showViewer({
fileName: file.fileName,
kind,
status: 'ready',
url: cached.url,
text: cached.text,
ownedUrl: false,
});
return;
}
if (!kind) {
showViewer({
fileName: file.fileName,
kind: null,
status: 'unavailable',
ownedUrl: false,
});
return;
}
showViewer({
fileName: file.fileName,
kind,
status: 'loading',
ownedUrl: false,
});
try {
const raw = await onDownload(file);
if (viewGen.current !== gen) return;
const typed = blobForKind(raw, file, kind);
if (kind === 'text') {
const text = await typed.text();
if (viewGen.current !== gen) return;
showViewer({
fileName: file.fileName,
kind,
status: 'ready',
text,
ownedUrl: false,
});
return;
}
const url = URL.createObjectURL(typed);
if (viewGen.current !== gen) {
URL.revokeObjectURL(url);
return;
}
showViewer({
fileName: file.fileName,
kind,
status: 'ready',
url,
ownedUrl: true,
});
} catch (error: unknown) {
if (viewGen.current === gen) closeViewer();
onDownloadError?.(error);
}
}
const working = busy || downloading || adding;
return (
<div className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-medium text-text-primary">{t('filesShared')}</p>
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
disabled={working || selected.length === 0}
onClick={() => void downloadMany(selected)}
>
{t('filesSaveToStorage')}
</Button>
{canAdd ? (
<>
<Button
type="button"
variant="primary"
size="sm"
isLoading={adding}
disabled={working}
onClick={() => inputRef.current?.click()}
>
<Plus className="h-4 w-4" aria-hidden />
{t('filesAdd')}
</Button>
<input
ref={inputRef}
type="file"
multiple
className="hidden"
onChange={(event) => {
const files = event.target.files ? Array.from(event.target.files) : [];
if (files.length) onAdd(files);
event.target.value = '';
}}
/>
</>
) : null}
</div>
<div className="flex flex-wrap items-center justify-end gap-2">
<p className="me-auto text-sm font-medium text-text-primary">
{attachments.length > 0
? `${t('filesShared')} (${formatAppNumber(attachments.length, locale)})`
: t('filesShared')}
</p>
<Button
type="button"
variant="outline"
size="sm"
className={WORKSPACE_ACTION_BTN_CLASS}
disabled={working || selected.length === 0}
onClick={() => void downloadMany(selected)}
>
{t('filesSaveToStorage')}
</Button>
{canAdd ? (
<>
<CaseLifecycleButton
variant="primary"
label={t('filesAdd')}
isLoading={adding}
disabled={working}
onClick={() => inputRef.current?.click()}
/>
<input
ref={inputRef}
type="file"
multiple
className="hidden"
onChange={(event) => {
const files = event.target.files ? Array.from(event.target.files) : [];
if (files.length) onAdd(files);
event.target.value = '';
}}
/>
</>
) : null}
</div>
{attachments.length === 0 ? (
<p className="text-sm text-text-muted">{t('filesEmpty')}</p>
) : (
<ul className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
<ul className="grid gap-4 [grid-template-columns:repeat(auto-fill,minmax(220px,1fr))]">
{attachments.map((file) => {
const checked = selected.includes(file.id);
const preview = previews[file.id];
const extension = fileExtension(file.fileName);
return (
<li
key={file.id}
className="flex min-w-0 flex-col gap-2 rounded-[var(--radius-md)] border border-border bg-background p-3"
className="flex min-w-0 flex-col overflow-hidden rounded-xl border border-border bg-background-card"
>
<Checkbox
checked={checked}
onChange={(next) => toggle(file.id, next)}
label={
<span className="min-w-0">
<span className="block truncate text-sm font-medium text-text-primary">
{file.fileName}
<div className="flex items-center gap-2 px-3 py-2">
<p
className="min-w-0 flex-1 truncate text-start text-sm font-medium text-text-primary"
title={file.fileName}
>
{shortFileName(file.fileName)}
</p>
<Checkbox
checked={checked}
onChange={(next) => toggle(file.id, next)}
className="!gap-0 shrink-0"
label={<span className="sr-only">{file.fileName}</span>}
/>
</div>
<div className="h-40 shrink-0 overflow-hidden bg-background-secondary [contain:paint]">
<div
className="flex h-full w-full cursor-pointer items-center justify-center overflow-hidden"
onClick={() => void openView(file)}
>
<span className="sr-only">{t('filesView')}</span>
{preview?.status === 'ready' && preview.kind === 'image' && preview.url ? (
// Blob URLs are created in this panel and revoked on change.
// eslint-disable-next-line @next/next/no-img-element
<img
src={preview.url}
alt=""
className="max-h-full max-w-full object-contain"
/>
) : preview?.status === 'ready' && preview.kind === 'pdf' && preview.url ? (
<iframe
title={file.fileName}
src={preview.url}
className="pointer-events-none h-full w-full border-0 bg-white"
/>
) : preview?.status === 'ready' && preview.kind === 'text' && preview.text != null ? (
<pre className="h-full w-full overflow-hidden whitespace-pre-wrap break-words p-3 text-start text-xs leading-4 text-text-secondary">
{preview.text.slice(0, 600)}
</pre>
) : preview?.status === 'loading' ? (
<span className="block h-full w-full animate-pulse bg-background-secondary" />
) : (
<span className="flex h-full w-full flex-col items-center justify-center gap-2 text-text-muted">
<FileIcon className="h-8 w-8" aria-hidden />
{extension ? (
<span className="text-xs font-medium tracking-wide">{extension}</span>
) : null}
</span>
<span className="block text-xs font-normal text-text-muted">
{formatBytes(file.sizeBytes)}
</span>
</span>
}
/>
<div className="flex items-center justify-end gap-2">
{onRemove ? (
)}
</div>
</div>
<div className="flex items-center gap-2 px-3 py-2">
<div className="min-w-0 flex-1 text-start">
<p className="truncate text-xs text-text-secondary">
{formatFileSize(file.sizeBytes)}
</p>
<p className="mt-0.5 truncate text-xs text-text-muted">
{formatAppDateTime(file.createdAt, locale)}
</p>
</div>
<div
className="relative shrink-0 self-center"
ref={menuId === file.id ? menuRef : undefined}
>
<button
type="button"
className="text-xs text-text-muted hover:text-red-600"
onClick={() => onRemove(file.id)}
className="inline-flex h-5 w-5 items-center justify-end rounded-md text-text-secondary hover:bg-background-secondary hover:text-text-primary"
aria-label={t('filesMenu')}
aria-haspopup="menu"
aria-expanded={menuId === file.id}
onClick={() => setMenuId((current) => (current === file.id ? null : file.id))}
>
{t('filesRemove')}
<MoreVertical className="h-4 w-4" aria-hidden />
</button>
) : null}
<button
type="button"
className="inline-flex items-center gap-1 text-xs text-primary hover:underline"
disabled={working}
onClick={() => void downloadMany([file.id])}
>
<Download className="h-3.5 w-3.5" aria-hidden />
{t('downloadAttachment')}
</button>
{menuId === file.id ? (
<div
role="menu"
className="absolute end-0 bottom-full z-30 mb-1 min-w-36 overflow-hidden rounded-[var(--radius-md)] border border-border bg-background-card py-1 shadow-md"
>
<button
type="button"
role="menuitem"
className="block w-full px-3 py-2 text-start text-sm text-text-primary hover:bg-background-secondary"
onClick={() => void openView(file)}
>
{t('filesView')}
</button>
<button
type="button"
role="menuitem"
className="block w-full px-3 py-2 text-start text-sm text-text-primary hover:bg-background-secondary"
disabled={working}
onClick={() => {
setMenuId(null);
void downloadMany([file.id]);
}}
>
{t('downloadAttachment')}
</button>
{onRemove ? (
<button
type="button"
role="menuitem"
className="block w-full px-3 py-2 text-start text-sm text-red-600 hover:bg-background-secondary"
onClick={() => {
setMenuId(null);
onRemove(file.id);
}}
>
{t('filesRemove')}
</button>
) : null}
</div>
) : null}
</div>
</div>
</li>
);
})}
</ul>
)}
{viewer ? (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
onClick={closeViewer}
>
<div
role="dialog"
aria-modal="true"
aria-label={viewer.fileName}
className="flex max-h-[85vh] w-full max-w-4xl flex-col overflow-hidden rounded-xl border border-border bg-background-card shadow-lg"
onClick={(event) => event.stopPropagation()}
>
<div className="flex items-center justify-between gap-3 border-b border-border px-4 py-3">
<p className="min-w-0 truncate text-sm font-medium text-text-primary">
{viewer.fileName}
</p>
<button
type="button"
className="shrink-0 text-sm text-text-secondary hover:text-text-primary"
onClick={closeViewer}
>
{tCommon('close')}
</button>
</div>
<div className="min-h-48 overflow-auto bg-background p-4">
{viewer.status === 'loading' ? (
<p className="text-sm text-text-muted">{tCommon('loading')}</p>
) : viewer.status === 'ready' && viewer.kind === 'image' && viewer.url ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={viewer.url}
alt=""
className="mx-auto max-h-[70vh] w-full object-contain"
/>
) : viewer.status === 'ready' && viewer.kind === 'pdf' && viewer.url ? (
<iframe
title={viewer.fileName}
src={viewer.url}
className="h-[70vh] w-full border-0 bg-white"
/>
) : viewer.status === 'ready' && viewer.kind === 'text' && viewer.text != null ? (
<pre className="whitespace-pre-wrap break-words text-start text-sm text-text-primary">
{viewer.text}
</pre>
) : (
<p className="text-sm text-text-muted">{t('filesPreviewUnavailable')}</p>
)}
</div>
</div>
</div>
) : null}
</div>
);
}

View File

@@ -178,17 +178,22 @@ export function CaseSheetPrintLayout({
}}
>
<div
data-case-sheet-org
style={{
margin: 0,
minWidth: 0,
flex: 1,
alignSelf: 'center',
display: 'flex',
alignItems: 'center',
// Taller than the 22px glyphs. html2canvas clips the bottoms of
// letters when this box is only as tall as the lockup (28px).
height: 48,
overflow: 'hidden',
fontSize: 22,
fontWeight: 600,
lineHeight: '28px',
lineHeight: '48px',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
...(rtl
? {
direction: 'rtl' as const,
@@ -199,7 +204,17 @@ export function CaseSheetPrintLayout({
: {}),
}}
>
{organizationName || labels.title}
<span
style={{
display: 'block',
minWidth: 0,
maxWidth: '100%',
overflow: 'visible',
lineHeight: '48px',
}}
>
{organizationName || labels.title}
</span>
</div>
<div
data-case-sheet-lockup

View File

@@ -28,6 +28,8 @@ import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
import { prosthesisJobPathLabel } from '@/components/treatment/prosthesisJobPath';
import { treatmentTypeLabelFromCatalog } from '@/components/shared/treatmentTypeDisplay';
import { useConfirm } from '@/components/ui/shared/ConfirmProvider';
import { CaseLifecycleButton } from '@/components/ui/lab/CaseLifecycleButton';
import { Badge } from '@/components/ui/shared/Badge';
import { Button } from '@/components/ui/shared/Button';
import { MobileDetailBackButton } from '@/components/ui/shared/MobileDetailBackButton';
@@ -68,6 +70,7 @@ export function CasesPage() {
const tProsthesis = useTranslations('prosthesis');
const tErrors = useTranslations('errors');
const tCommon = useTranslations('common');
const confirm = useConfirm();
const { currentOrganization, user } = useAuth();
const toast = useToast();
const searchParams = useSearchParams();
@@ -111,7 +114,6 @@ export function CasesPage() {
const [linkedLabsLoading, setLinkedLabsLoading] = useState(false);
const [sendingCase, setSendingCase] = useState(false);
const [recallingChildCaseId, setRecallingChildCaseId] = useState<string | null>(null);
const [commentCount, setCommentCount] = useState(0);
const [creatingCase, setCreatingCase] = useState(false);
const selectedCaseIdRef = useRef<string | null>(null);
selectedCaseIdRef.current = selectedCaseId;
@@ -366,20 +368,8 @@ export function CasesPage() {
),
);
}).catch(() => undefined);
const selectedIsDraft =
drafts.some((item) => item.id === selectedCaseId) ||
(selectedCase?.id === selectedCaseId && isDraftLabCase(selectedCase));
if (selectedIsDraft) {
setCommentCount(0);
} else {
void caseCommentsApi
.list(selectedCaseId)
.then((r) => setCommentCount(r.data.length))
.catch(() => setCommentCount(0));
}
} else {
setSelectedCase(null);
setCommentCount(0);
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- reload when selection changes
}, [selectedCaseId]);
@@ -416,10 +406,6 @@ export function CasesPage() {
}
}
function scrollToComments() {
document.getElementById('case-comments')?.scrollIntoView({ behavior: 'smooth' });
}
const loadCaseAttachmentBlob = useCallback(
(caseId: string, attachmentId: string) => casesApi.getAttachmentFileBlob(caseId, attachmentId),
[],
@@ -458,7 +444,14 @@ export function CasesPage() {
async function handleStopCase() {
if (!selectedCaseId || !canEdit || !selectedCase) return;
if (!window.confirm(t('confirmStopCase'))) return;
if (
!(await confirm({
message: t('confirmStopCase'),
confirmLabel: t('stopCase'),
}))
) {
return;
}
setStoppingCase(true);
toast.setError('');
try {
@@ -516,7 +509,14 @@ export function CasesPage() {
async function handleRecallOutsource(childCaseId: string) {
if (!selectedCaseId || !canEdit) return;
if (!window.confirm(t('confirmRecallOutsource'))) return;
if (
!(await confirm({
message: t('confirmRecallOutsource'),
confirmLabel: t('outsourceRecall'),
}))
) {
return;
}
setRecallingChildCaseId(childCaseId);
toast.setError('');
try {
@@ -678,15 +678,15 @@ export function CasesPage() {
}`}
>
{canEdit ? (
<Button
type="button"
size="lg"
fullWidth
disabled={creatingCase}
onClick={() => void handleAddCase()}
>
{t('addCase')}
</Button>
<div className="self-start">
<CaseLifecycleButton
variant="primary"
label={t('addCase')}
isLoading={creatingCase}
disabled={creatingCase}
onClick={() => void handleAddCase()}
/>
</div>
) : null}
<SearchBar
embedded
@@ -927,9 +927,6 @@ export function CasesPage() {
treatmentLabel={treatmentDetailLabel}
statusOptions={statusOptions}
loadAttachmentBlob={loadCaseAttachmentBlob}
showCommentsButton
commentCount={commentCount}
onCommentsClick={scrollToComments}
canEditImportant={canEdit}
updatingImportant={updatingImportant}
onImportantChange={(checked) => void handleCaseImportantToggle(checked)}
@@ -970,37 +967,33 @@ export function CasesPage() {
}
commentsSection={
selectedCaseId ? (
<section className="scroll-mt-4">
<LabCaseCommentsPanel
caseId={selectedCaseId}
viewerSide="LAB"
canPost={canEdit}
canToggleVisibility={canEdit}
{...commentVisibilityProps(
selectedCase.origin,
selectedCase.partnerOrganizationType,
)}
loadComments={async () => {
const r = await caseCommentsApi.list(selectedCaseId);
setCommentCount(r.data.length);
return r.data;
}}
onPost={async (body, visibleToClinic) => {
const r = await caseCommentsApi.add(selectedCaseId, {
body,
visibleToClinic,
});
setCommentCount((n) => n + 1);
notifyTabBadgesChanged();
return r.data;
}}
<LabCaseCommentsPanel
caseId={selectedCaseId}
viewerSide="LAB"
canPost={canEdit}
canToggleVisibility={canEdit}
{...commentVisibilityProps(
selectedCase.origin,
selectedCase.partnerOrganizationType,
)}
loadComments={async () => {
const r = await caseCommentsApi.list(selectedCaseId);
return r.data;
}}
onPost={async (body, visibleToClinic) => {
const r = await caseCommentsApi.add(selectedCaseId, {
body,
visibleToClinic,
});
notifyTabBadgesChanged();
return r.data;
}}
onToggleVisibility={async (commentId, visible) => {
const r = await caseCommentsApi.setVisibility(commentId, visible);
return r.data;
}}
onError={toast.showError}
/>
</section>
) : null
}
/>

View File

@@ -0,0 +1,79 @@
'use client';
import { useEffect, useId } from 'react';
import { useTranslations } from 'next-intl';
import { Button } from '@/components/ui/shared/Button';
import {
ResponsiveDialogOverlay,
ResponsiveDialogPanel,
} from '@/components/ui/shared/ResponsiveDialog';
export type ConfirmTone = 'primary' | 'danger';
type ConfirmDialogProps = {
message: string;
title?: string;
confirmLabel?: string;
cancelLabel?: string;
tone?: ConfirmTone;
onConfirm: () => void;
onCancel: () => void;
};
/** In-app replacement for the browser confirm prompt. */
export function ConfirmDialog({
message,
title,
confirmLabel,
cancelLabel,
tone = 'primary',
onConfirm,
onCancel,
}: ConfirmDialogProps) {
const t = useTranslations('common');
const titleId = useId();
const messageId = useId();
useEffect(() => {
function onKeyDown(event: KeyboardEvent) {
if (event.key !== 'Escape') return;
event.preventDefault();
event.stopPropagation();
onCancel();
}
document.addEventListener('keydown', onKeyDown, true);
return () => document.removeEventListener('keydown', onKeyDown, true);
}, [onCancel]);
return (
<ResponsiveDialogOverlay onBackdropClick={onCancel} zIndexClass="z-[80]">
<ResponsiveDialogPanel
role="alertdialog"
aria-modal="true"
aria-labelledby={titleId}
aria-describedby={messageId}
maxWidthClass="sm:max-w-md"
>
<h2 id={titleId} className="text-base font-semibold text-text-primary">
{title ?? t('confirmTitle')}
</h2>
<p id={messageId} className="mt-2 text-start text-sm text-text-secondary">
{message}
</p>
<div className="mt-5 flex flex-wrap justify-end gap-2">
<Button type="button" variant="outline" onClick={onCancel}>
{cancelLabel ?? t('cancel')}
</Button>
<Button
type="button"
variant={tone === 'danger' ? 'danger' : 'primary'}
autoFocus
onClick={onConfirm}
>
{confirmLabel ?? t('confirmAction')}
</Button>
</div>
</ResponsiveDialogPanel>
</ResponsiveDialogOverlay>
);
}

View File

@@ -0,0 +1,99 @@
'use client';
import {
createContext,
useCallback,
useContext,
useEffect,
useRef,
useState,
type ReactNode,
} from 'react';
import {
ConfirmDialog,
type ConfirmTone,
} from '@/components/ui/shared/ConfirmDialog';
export type ConfirmOptions = {
message: string;
title?: string;
confirmLabel?: string;
cancelLabel?: string;
tone?: ConfirmTone;
};
type PendingConfirm = ConfirmOptions & {
resolve: (accepted: boolean) => void;
settled: boolean;
};
const ConfirmContext = createContext<
((options: ConfirmOptions) => Promise<boolean>) | null
>(null);
export function ConfirmProvider({ children }: { children: ReactNode }) {
const queueRef = useRef<PendingConfirm[]>([]);
const currentRef = useRef<PendingConfirm | null>(null);
const settleLockRef = useRef(false);
const [current, setCurrent] = useState<PendingConfirm | null>(null);
const confirm = useCallback((options: ConfirmOptions) => {
return new Promise<boolean>((resolve) => {
const pending: PendingConfirm = { ...options, resolve, settled: false };
if (currentRef.current) {
queueRef.current.push(pending);
return;
}
currentRef.current = pending;
setCurrent(pending);
});
}, []);
const settle = useCallback((accepted: boolean) => {
const active = currentRef.current;
if (!active || active.settled || settleLockRef.current) return;
active.settled = true;
settleLockRef.current = true;
active.resolve(accepted);
const next = queueRef.current.shift() ?? null;
currentRef.current = next;
setCurrent(next);
window.setTimeout(() => {
settleLockRef.current = false;
}, 250);
}, []);
useEffect(() => {
return () => {
currentRef.current?.resolve(false);
queueRef.current.forEach((item) => item.resolve(false));
queueRef.current = [];
currentRef.current = null;
};
}, []);
return (
<ConfirmContext.Provider value={confirm}>
{children}
{current ? (
<ConfirmDialog
title={current.title}
message={current.message}
confirmLabel={current.confirmLabel}
cancelLabel={current.cancelLabel}
tone={current.tone}
onConfirm={() => settle(true)}
onCancel={() => settle(false)}
/>
) : null}
</ConfirmContext.Provider>
);
}
export function useConfirm() {
const confirm = useContext(ConfirmContext);
if (!confirm) {
throw new Error('useConfirm must be used within ConfirmProvider');
}
return confirm;
}

View File

@@ -16,6 +16,7 @@ type ResponsiveDialogPanelProps = {
role?: string;
'aria-modal'?: boolean | 'true' | 'false';
'aria-labelledby'?: string;
'aria-describedby'?: string;
};
export function ResponsiveDialogOverlay({
@@ -46,6 +47,7 @@ export function ResponsiveDialogPanel({
role,
'aria-modal': ariaModal,
'aria-labelledby': ariaLabelledby,
'aria-describedby': ariaDescribedby,
}: ResponsiveDialogPanelProps) {
return (
<div
@@ -53,6 +55,7 @@ export function ResponsiveDialogPanel({
role={role}
aria-modal={ariaModal}
aria-labelledby={ariaLabelledby}
aria-describedby={ariaDescribedby}
onMouseDown={(e) => e.stopPropagation()}
>
{children}

View File

@@ -5,6 +5,7 @@ import { useTranslations } from 'next-intl';
import type { FdiToothId, LabCaseToothProsthesisDraft, ToothSelectionGroup } from '@/types/treatment';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import { FdiToothChart } from '@/components/ui/treatment/FdiToothChart';
import { useConfirm } from '@/components/ui/shared/ConfirmProvider';
import { useToast } from '@/lib/hooks/useToast';
import {
ProsthesisJobPopover,
@@ -74,7 +75,9 @@ export function ProsthesisAssignChart({
onChange,
}: ProsthesisAssignChartProps) {
const tTreatment = useTranslations('treatment');
const tCommon = useTranslations('common');
const tProsthesis = useTranslations('prosthesis');
const confirm = useConfirm();
const { showError } = useToast();
const [open, setOpen] = useState(false);
const [mobile, setMobile] = useState(false);
@@ -131,6 +134,8 @@ export function ProsthesisAssignChart({
);
const archHighlight = open && scope === 'arch' ? lockedArch : persistedArch;
const archWork = hasArchJobs(toothProsthesis, detailClientId);
const resetSnapshotRef = useRef({ groups, toothProsthesis, selected, archWork });
resetSnapshotRef.current = { groups, toothProsthesis, selected, archWork };
const jobCodes =
scope === 'arch'
@@ -353,11 +358,21 @@ export function ProsthesisAssignChart({
setOpen(false);
}
function handleReset() {
async function handleReset() {
if (disabled || (selected.size === 0 && !archWork)) return;
if (!window.confirm(tTreatment('confirmResetChart'))) return;
const fdiTeeth = [...selected];
const withoutFdi = clearJobsForTeeth(toothProsthesis, detailClientId, fdiTeeth);
if (
!(await confirm({
message: tTreatment('confirmResetChart'),
confirmLabel: tCommon('confirmAction'),
tone: 'danger',
}))
) {
return;
}
const snap = resetSnapshotRef.current;
if (snap.selected.size === 0 && !snap.archWork) return;
const fdiTeeth = [...snap.selected];
const withoutFdi = clearJobsForTeeth(snap.toothProsthesis, detailClientId, fdiTeeth);
const nextRows = withoutFdi.filter(
(row) => !(row.detailClientId === detailClientId && isArchSentinel(row.tooth)),
);

View File

@@ -3,6 +3,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from '@/i18n/navigation';
import { useConfirm } from '@/components/ui/shared/ConfirmProvider';
import { Button } from '@/components/ui/shared/Button';
import { MobileDetailBackButton } from '@/components/ui/shared/MobileDetailBackButton';
import { PatientSearchCombobox } from '@/components/ui/patient/PatientSearchCombobox';
@@ -459,7 +460,9 @@ export function TreatmentWorkspace({
}: TreatmentWorkspaceProps) {
const locale = useLocale();
const t = useTranslations('treatment');
const tCommon = useTranslations('common');
const tErrors = useTranslations('errors');
const confirm = useConfirm();
const tPatients = useTranslations('patients');
const router = useRouter();
const { user } = useAuth();
@@ -1753,9 +1756,13 @@ export function TreatmentWorkspace({
await runDraftSave();
return true;
} catch {
return window.confirm(t('confirmDiscard'));
return confirm({
message: t('confirmDiscard'),
confirmLabel: tCommon('continue'),
tone: 'danger',
});
}
}, [hasLiveContext, canEditTreatmentForDay, runDraftSave, t]);
}, [hasLiveContext, canEditTreatmentForDay, runDraftSave, t, tCommon, confirm]);
useEffect(() => {
if (draftHydratingRef.current || !canEditTreatmentForDay || !hasLiveContext) {
@@ -1874,7 +1881,15 @@ export function TreatmentWorkspace({
const deleteStandaloneTreatment = useCallback(
async (item: DayStripItem) => {
if (!canEdit || item.kind !== 'unscheduled' || !item.canDelete) return;
if (!window.confirm(t('confirmDeleteEmptyTreatment'))) return;
if (
!(await confirm({
message: t('confirmDeleteEmptyTreatment'),
confirmLabel: tCommon('delete'),
tone: 'danger',
}))
) {
return;
}
if (autosaveTimerRef.current) {
clearTimeout(autosaveTimerRef.current);
autosaveTimerRef.current = null;
@@ -1906,10 +1921,12 @@ export function TreatmentWorkspace({
},
[
canEdit,
confirm,
resetToLiveContext,
selectedStandaloneId,
showError,
t,
tCommon,
tErrors,
],
);
@@ -2394,7 +2411,7 @@ export function TreatmentWorkspace({
);
const handleRemoveDetail = useCallback(
(detailClientId: string) => {
async (detailClientId: string) => {
if (!canEditTreatmentForDay) return;
const idx = details.findIndex((d) => d.clientId === detailClientId);
if (idx < 0) return;
@@ -2407,14 +2424,31 @@ export function TreatmentWorkspace({
) {
return;
}
if (!window.confirm(
details.length <= 1 ? t('confirmRemoveLastDetail') : t('confirmRemoveDetail'),
)) return;
const accepted = await confirm({
message: details.length <= 1 ? t('confirmRemoveLastDetail') : t('confirmRemoveDetail'),
confirmLabel: details.length <= 1 ? tCommon('continue') : tCommon('delete'),
tone: 'danger',
});
if (!accepted) return;
const nextDetails = details.filter((d) => d.clientId !== detailClientId);
const latestDetails = detailsRef.current;
const latestIdx = latestDetails.findIndex((d) => d.clientId === detailClientId);
const latest = latestDetails[latestIdx];
if (
!latest ||
latest.sentAt ||
labCaseDraftsRef.current.some(
(lc) => lc.sentAt && lc.detailClientId === latest.clientId,
) ||
isDetailLocked(latest)
) {
return;
}
const nextDetails = latestDetails.filter((d) => d.clientId !== detailClientId);
const nextActive =
activeDetailId === detailClientId
? (nextDetails[Math.min(idx, nextDetails.length - 1)]?.clientId ?? '')
? (nextDetails[Math.min(latestIdx, nextDetails.length - 1)]?.clientId ?? '')
: activeDetailId;
// Sync ref before any persist triggered by lab-case cleanup (same tick).
@@ -2422,10 +2456,11 @@ export function TreatmentWorkspace({
setDetails(nextDetails);
setActiveDetailId(nextActive);
if (labCaseDrafts.some((lc) => lc.detailClientId === detailClientId)) {
const drafts = labCaseDraftsRef.current;
if (drafts.some((lc) => lc.detailClientId === detailClientId)) {
handleLabCasesChange(
withoutEmptyLabCaseDrafts(
labCaseDrafts.filter((lc) => lc.detailClientId !== detailClientId),
drafts.filter((lc) => lc.detailClientId !== detailClientId),
),
);
}
@@ -2433,16 +2468,18 @@ export function TreatmentWorkspace({
[
activeDetailId,
canEditTreatmentForDay,
confirm,
details,
handleLabCasesChange,
isDetailLocked,
labCaseDrafts,
t,
tCommon,
],
);
const handleTreatmentTypeChange = useCallback(
(nextType: string) => {
async (nextType: string) => {
if (!canEditTreatmentForDay) return;
const detail = details.find((d) => d.clientId === activeDetailId);
if (!detail || isDetailLocked(detail)) return;
@@ -2457,13 +2494,26 @@ export function TreatmentWorkspace({
detail.toothSelectionGroups.some((g) => g.teeth.length > 0) ||
jobs.length > 0;
if (leavingLab && hasWork && !window.confirm(t('confirmLeaveProsthesis'))) {
if (
leavingLab &&
hasWork &&
!(await confirm({
message: t('confirmLeaveProsthesis'),
confirmLabel: tCommon('continue'),
}))
) {
return;
}
const nextDetails = details.map((d) => {
const latestDetails = detailsRef.current;
const current = latestDetails.find((d) => d.clientId === activeDetailId);
if (!current || isDetailLocked(current) || current.treatmentType === nextType) return;
const leavingNow = labDependentCodes.has(current.treatmentType);
const enteringNow = labDependentCodes.has(nextType);
const nextDetails = latestDetails.map((d) => {
if (d.clientId !== activeDetailId) return d;
if (leavingLab || enteringLab) {
if (leavingNow || enteringNow) {
return {
...d,
treatmentType: nextType,
@@ -2476,11 +2526,12 @@ export function TreatmentWorkspace({
detailsRef.current = nextDetails;
setDetails(nextDetails);
if (leavingLab) {
const nextDrafts = labCaseDrafts.filter(
if (leavingNow) {
const drafts = labCaseDraftsRef.current;
const nextDrafts = drafts.filter(
(lc) => lc.detailClientId !== activeDetailId || Boolean(lc.sentAt),
);
if (nextDrafts.length !== labCaseDrafts.length) {
if (nextDrafts.length !== drafts.length) {
handleLabCasesChange(nextDrafts);
}
}
@@ -2488,12 +2539,14 @@ export function TreatmentWorkspace({
[
activeDetailId,
canEditTreatmentForDay,
confirm,
details,
handleLabCasesChange,
isDetailLocked,
labCaseDrafts,
labDependentCodes,
t,
tCommon,
],
);
@@ -3296,6 +3349,7 @@ export function TreatmentWorkspace({
!activeTypeSelected
}
onReset={() => {
void (async () => {
if (
!canEditTreatmentForDay ||
activeLocked ||
@@ -3312,7 +3366,15 @@ export function TreatmentWorkspace({
? detail.toothSelectionGroups
: groupsFromFlatTeeth(detail.teeth);
if (deriveTeethFromGroups(currentGroups).length === 0) return;
if (!window.confirm(t('confirmResetChart'))) return;
if (
!(await confirm({
message: t('confirmResetChart'),
confirmLabel: tCommon('confirmAction'),
tone: 'danger',
}))
) {
return;
}
const nextGroups = groupsFromFlatTeeth([]);
setDetails((prev) =>
prev.map((d) =>
@@ -3338,6 +3400,7 @@ export function TreatmentWorkspace({
};
}),
);
})();
}}
/>
)