From f9eddb4275f83ea641e0f864fd77225edebd8f08 Mon Sep 17 00:00:00 2001 From: Admin Date: Sat, 10 Oct 2026 00:59:29 +0330 Subject: [PATCH 1/3] improvment: progression bar added to cases attachment card. upload size restrictions removed. --- .cursor/rules/lab-cases.mdc | 3 +- .cursor/skills/lab-cases/SKILL.md | 3 +- backend/src/common/org-disk-storage.ts | 30 +++++ backend/src/modules/cases/cases.controller.ts | 4 +- backend/src/modules/cases/cases.service.ts | 55 ++++---- .../treatments/treatments.controller.ts | 8 +- .../modules/treatments/treatments.service.ts | 81 ++++++------ frontend/messages/en.json | 2 + frontend/messages/fa.json | 2 + frontend/messages/nl.json | 2 + .../src/components/ui/lab/CaseCreatePanel.tsx | 11 +- .../src/components/ui/lab/CaseDetailPanel.tsx | 120 ++++++++++-------- .../src/components/ui/lab/CaseFilesPanel.tsx | 101 ++++++++++++++- .../components/ui/lab/CaseLifecycleButton.tsx | 13 +- frontend/src/components/ui/lab/CasesPage.tsx | 4 +- .../ui/lab/LabCaseShareQrDialog.tsx | 20 ++- frontend/src/components/ui/lab/TasksPage.tsx | 1 - .../ui/shared/MobileDetailBackButton.tsx | 2 +- .../components/ui/shared/UnderlineTabs.tsx | 2 +- frontend/src/lib/api/cases.ts | 22 +++- frontend/src/lib/api/treatments.ts | 24 +++- infrastructure/nginx/http-only.conf | 8 +- infrastructure/nginx/http-only.dev.conf | 8 +- infrastructure/nginx/nginx.conf | 8 +- infrastructure/nginx/nginx.ssl.conf.template | 8 +- infrastructure/nginx/windows-edge-http.conf | 36 +++++- 26 files changed, 411 insertions(+), 167 deletions(-) create mode 100644 backend/src/common/org-disk-storage.ts diff --git a/.cursor/rules/lab-cases.mdc b/.cursor/rules/lab-cases.mdc index b87ec05..d0127fc 100644 --- a/.cursor/rules/lab-cases.mdc +++ b/.cursor/rules/lab-cases.mdc @@ -16,7 +16,8 @@ alwaysApply: false - **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 cases use the case id. Outsource children use the child case id, or `childId:parentSourceKey` when two selected steps would collide (see Outsource). `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, 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). The page stays LTR in every locale. On `fa`, the org name is a shrink-wrapped `inline-block` (`direction: ltr` unless the name itself contains Arabic script) with `letter-spacing` and `word-spacing` `0px` — a full-width RTL box gaps Latin words. Party and meta values use `printRtlValueStyle` (Arabic script stays RTL; Latin stays LTR and right-aligned). `FA_RULE_DROP` (6px) clears Persian descenders. `onclone` must not overwrite the name span’s direction. 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}”. +- **Detail chrome:** **Mark as important** is centered in the header on `lg`. Below that, the header is one compact stack: name and a 56px QR on the first row, mobile/from/date on one wrapping line, the progress bar without a separate “tasks completed” sentence, important and billed on one row, and Edit / Outsource / Get PDF sharing one row (`responsiveFill`). External code sits under the progress bar in the start column, same width as the bar; billed price is under important on `lg`. Get PDF, Add case, and Add files are primary `CaseLifecycleButton`s with no icon, the same width as Outsource from `lg` up. 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. An in-progress upload is its own card with a progress bar. The sent-date line reads “Outsource {date}”. +- **Attachments:** no size cap. One file per request, streamed with `orgDiskStorage` (not memory). The client has no axios timeout. Nginx `/api` uses `client_max_body_size 0`. Do not set `Content-Type: multipart/form-data` by hand. - **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). diff --git a/.cursor/skills/lab-cases/SKILL.md b/.cursor/skills/lab-cases/SKILL.md index ee9c84e..6c36004 100644 --- a/.cursor/skills/lab-cases/SKILL.md +++ b/.cursor/skills/lab-cases/SKILL.md @@ -47,7 +47,8 @@ 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, 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. +- **Important + external code** (`TAB_CASES_EDIT`): **Mark as important** is centered in the header on `lg`. Below `lg` the header is one compact stack: name and a 56px QR on the first row, mobile / from / date on one wrapping line, the progress bar (no separate “tasks completed” sentence), important and billed on one row, and Edit / Outsource / Get PDF sharing one row (`CaseLifecycleButton` `responsiveFill`). External code is under the progress bar in the start column, same width as the bar (no title; placeholder only); billed price is under important on `lg`. 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 from `lg` up). 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. Each file being uploaded is its own card with a progress bar (one request per file). +- **Attachment uploads:** no size limit in multer, axios, or nginx `/api` (`client_max_body_size 0`, `client_body_timeout 3600s`, `proxy_request_buffering off`). Files stream to disk via `orgDiskStorage` under `uploads/lab-cases/{orgId}` (treatment uploads use `uploads/treatments`). Do not buffer the file in memory and do not set `Content-Type: multipart/form-data` yourself — that drops the boundary. A previous 50MB nginx cap, a 120s axios timeout, and `memoryStorage` are why scans around 80MB failed. - **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`. diff --git a/backend/src/common/org-disk-storage.ts b/backend/src/common/org-disk-storage.ts new file mode 100644 index 0000000..5e65b93 --- /dev/null +++ b/backend/src/common/org-disk-storage.ts @@ -0,0 +1,30 @@ +import { randomUUID } from 'crypto'; +import { mkdirSync } from 'fs'; +import { join } from 'path'; +import type { Request } from 'express'; +import { diskStorage } from 'multer'; + +/** + * Stream an upload onto disk under uploads/{folder}/{organizationId}. + * There is no file-size cap. Memory storage was holding the whole file in RAM, + * which dropped large scans once the process ran out of memory. + */ +export function orgDiskStorage(folder: 'lab-cases' | 'treatments') { + return diskStorage({ + destination(req, _file, cb) { + const orgId = (req as Request & { user?: { organizationId?: string } }).user + ?.organizationId; + if (!orgId) { + cb(new Error('missing organization'), ''); + return; + } + const dir = join(process.cwd(), 'uploads', folder, orgId); + mkdirSync(dir, { recursive: true }); + cb(null, dir); + }, + filename(_req, file, cb) { + const safe = file.originalname.replace(/[^\w.\-()+]/g, '_'); + cb(null, `${randomUUID()}-${safe}`); + }, + }); +} diff --git a/backend/src/modules/cases/cases.controller.ts b/backend/src/modules/cases/cases.controller.ts index 35031b0..53a0935 100644 --- a/backend/src/modules/cases/cases.controller.ts +++ b/backend/src/modules/cases/cases.controller.ts @@ -15,7 +15,7 @@ import { UseInterceptors, } from '@nestjs/common'; import { FilesInterceptor } from '@nestjs/platform-express'; -import { memoryStorage } from 'multer'; +import { orgDiskStorage } from '../../common/org-disk-storage'; import type { Response } from 'express'; import { ApiBearerAuth, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger'; import { LabOrgGuard } from '../../common/guards/lab-org.guard'; @@ -157,7 +157,7 @@ export class CasesController { @ApiConsumes('multipart/form-data') @UseInterceptors( FilesInterceptor('files', 20, { - storage: memoryStorage(), + storage: orgDiskStorage('lab-cases'), }), ) uploadAttachments( diff --git a/backend/src/modules/cases/cases.service.ts b/backend/src/modules/cases/cases.service.ts index 6d47ebc..1270149 100644 --- a/backend/src/modules/cases/cases.service.ts +++ b/backend/src/modules/cases/cases.service.ts @@ -3,8 +3,7 @@ import { Injectable, } from '@nestjs/common'; import { AppException, ErrorCode } from '../../common/errors'; -import { randomUUID } from 'crypto'; -import { createReadStream, existsSync, mkdirSync, unlinkSync } from 'fs'; +import { createReadStream, existsSync, unlinkSync } from 'fs'; import { join, resolve, sep } from 'path'; import { CatalogEntityKind, LabCaseActivityType, LabCaseOrigin, LabTaskStatus, LinkStatus, Prisma, UserNotificationType } from '@prisma/client'; import { PrismaService } from '../../../prisma/prisma.service'; @@ -1046,9 +1045,6 @@ export class CasesService { throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST); } - const orgDir = join(this.uploadRoot, labOrganizationId); - mkdirSync(orgDir, { recursive: true }); - const created: { id: string; fileName: string; @@ -1057,29 +1053,34 @@ export class CasesService { }[] = []; for (const file of files) { - const storageName = `${randomUUID()}-${file.originalname.replace(/[^\w.\-()+]/g, '_')}`; - const storagePath = join(orgDir, storageName); - const { writeFileSync } = await import('fs'); - writeFileSync(storagePath, file.buffer); + const storagePath = file.path; + if (!storagePath) { + throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST); + } - const attachment = await this.prisma.treatmentDetailAttachment.create({ - data: { - detailClientKey: null, - fileName: file.originalname, - mimeType: file.mimetype || 'application/octet-stream', - sizeBytes: file.size, - storagePath, - }, - }); - await this.prisma.labCaseAttachment.create({ - data: { labCaseId, attachmentId: attachment.id }, - }); - created.push({ - id: attachment.id, - fileName: attachment.fileName, - mimeType: attachment.mimeType, - sizeBytes: attachment.sizeBytes, - }); + try { + const attachment = await this.prisma.treatmentDetailAttachment.create({ + data: { + detailClientKey: null, + fileName: file.originalname, + mimeType: file.mimetype || 'application/octet-stream', + sizeBytes: file.size, + storagePath, + }, + }); + await this.prisma.labCaseAttachment.create({ + data: { labCaseId, attachmentId: attachment.id }, + }); + created.push({ + id: attachment.id, + fileName: attachment.fileName, + mimeType: attachment.mimeType, + sizeBytes: attachment.sizeBytes, + }); + } catch (error) { + this.removeStoredFiles([storagePath]); + throw error; + } } return { success: true, data: created }; diff --git a/backend/src/modules/treatments/treatments.controller.ts b/backend/src/modules/treatments/treatments.controller.ts index d6e4788..8d2b55d 100644 --- a/backend/src/modules/treatments/treatments.controller.ts +++ b/backend/src/modules/treatments/treatments.controller.ts @@ -17,7 +17,7 @@ import { } from '@nestjs/common'; import { FilesInterceptor } from '@nestjs/platform-express'; import { ApiBearerAuth, ApiBody, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger'; -import { memoryStorage } from 'multer'; +import { orgDiskStorage } from '../../common/org-disk-storage'; import type { Response } from 'express'; import { ClinicOrgGuard } from '../../common/guards/clinic-org.guard'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; @@ -177,7 +177,7 @@ export class TreatmentsController { }) @UseInterceptors( FilesInterceptor('files', 20, { - storage: memoryStorage(), + storage: orgDiskStorage('treatments'), }), ) uploadDetailAttachments( @@ -202,7 +202,7 @@ export class TreatmentsController { @ApiConsumes('multipart/form-data') @UseInterceptors( FilesInterceptor('files', 20, { - storage: memoryStorage(), + storage: orgDiskStorage('treatments'), }), ) uploadDetailAttachmentsLegacy( @@ -372,7 +372,7 @@ export class TreatmentsController { @ApiConsumes('multipart/form-data') @UseInterceptors( FilesInterceptor('files', 20, { - storage: memoryStorage(), + storage: orgDiskStorage('treatments'), }), ) uploadDetailAttachmentsByTreatment( diff --git a/backend/src/modules/treatments/treatments.service.ts b/backend/src/modules/treatments/treatments.service.ts index f84bf55..1e018df 100644 --- a/backend/src/modules/treatments/treatments.service.ts +++ b/backend/src/modules/treatments/treatments.service.ts @@ -4,9 +4,8 @@ import { } from '@nestjs/common'; import { AppException, ErrorCode } from '../../common/errors'; import { LabCaseActivityType, LabTaskStatus, LinkStatus, Prisma, UserNotificationType } from '@prisma/client'; -import { createReadStream, existsSync, mkdirSync } from 'fs'; +import { createReadStream, existsSync, unlinkSync } from 'fs'; import { join } from 'path'; -import { randomUUID } from 'crypto'; import { buildLabCaseShareUrl, generateLabCaseAccessToken, @@ -1349,9 +1348,6 @@ export class TreatmentsService { throw new AppException(ErrorCode.TREATMENT_DETAIL_SENT, HttpStatus.CONFLICT); } - const orgDir = join(this.uploadRoot, organizationId); - mkdirSync(orgDir, { recursive: true }); - const created: { id: string; fileName: string; @@ -1360,23 +1356,27 @@ export class TreatmentsService { }[] = []; for (const file of files) { - const storageName = `${randomUUID()}-${file.originalname.replace(/[^\w.\-()+]/g, '_')}`; - const storagePath = join(orgDir, storageName); - const { writeFileSync } = await import('fs'); - writeFileSync(storagePath, file.buffer); + const storagePath = file.path; + if (!storagePath) { + throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST); + } - const attachment = await this.prisma.treatmentDetailAttachment.create({ - data: { - appointmentId, - detailClientKey, - fileName: file.originalname, - mimeType: file.mimetype || 'application/octet-stream', - sizeBytes: file.size, - storagePath, - }, - }); - - created.push(this.mapAttachment(attachment)); + try { + const attachment = await this.prisma.treatmentDetailAttachment.create({ + data: { + appointmentId, + detailClientKey, + fileName: file.originalname, + mimeType: file.mimetype || 'application/octet-stream', + sizeBytes: file.size, + storagePath, + }, + }); + created.push(this.mapAttachment(attachment)); + } catch (error) { + if (existsSync(storagePath)) unlinkSync(storagePath); + throw error; + } } return { success: true, data: created }; @@ -1419,9 +1419,6 @@ export class TreatmentsService { throw new AppException(ErrorCode.TREATMENT_DETAIL_SENT, HttpStatus.CONFLICT); } - const orgDir = join(this.uploadRoot, organizationId); - mkdirSync(orgDir, { recursive: true }); - const created: { id: string; fileName: string; @@ -1430,23 +1427,27 @@ export class TreatmentsService { }[] = []; for (const file of files) { - const storageName = `${randomUUID()}-${file.originalname.replace(/[^\w.\-()+]/g, '_')}`; - const storagePath = join(orgDir, storageName); - const { writeFileSync } = await import('fs'); - writeFileSync(storagePath, file.buffer); + const storagePath = file.path; + if (!storagePath) { + throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST); + } - const attachment = await this.prisma.treatmentDetailAttachment.create({ - data: { - treatmentId, - detailClientKey, - fileName: file.originalname, - mimeType: file.mimetype || 'application/octet-stream', - sizeBytes: file.size, - storagePath, - }, - }); - - created.push(this.mapAttachment(attachment)); + try { + const attachment = await this.prisma.treatmentDetailAttachment.create({ + data: { + treatmentId, + detailClientKey, + fileName: file.originalname, + mimeType: file.mimetype || 'application/octet-stream', + sizeBytes: file.size, + storagePath, + }, + }); + created.push(this.mapAttachment(attachment)); + } catch (error) { + if (existsSync(storagePath)) unlinkSync(storagePath); + throw error; + } } return { success: true, data: created }; diff --git a/frontend/messages/en.json b/frontend/messages/en.json index e3e8863..b215fff 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -577,6 +577,8 @@ "filesView": "View", "filesMenu": "File actions", "filesPreviewUnavailable": "This file cannot be previewed.", + "filesUploadProgress": "Uploading", + "filesUploadFailed": "Upload failed", "partnerClinicNone": "None", "dueDateField": "Due date", "caseLinesTitle": "Work lines", diff --git a/frontend/messages/fa.json b/frontend/messages/fa.json index 25865fc..3e8cf91 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -578,6 +578,8 @@ "filesView": "مشاهده", "filesMenu": "عملیات فایل", "filesPreviewUnavailable": "پیش‌نمایش این فایل ممکن نیست.", + "filesUploadProgress": "در حال بارگذاری", + "filesUploadFailed": "بارگذاری انجام نشد", "partnerClinicNone": "هیچ‌کدام", "dueDateField": "موعد", "caseLinesTitle": "خطوط کار", diff --git a/frontend/messages/nl.json b/frontend/messages/nl.json index cbef722..d4634ff 100644 --- a/frontend/messages/nl.json +++ b/frontend/messages/nl.json @@ -578,6 +578,8 @@ "filesView": "Bekijken", "filesMenu": "Bestandsacties", "filesPreviewUnavailable": "Dit bestand kan niet worden bekeken.", + "filesUploadProgress": "Uploaden", + "filesUploadFailed": "Uploaden mislukt", "partnerClinicNone": "Geen", "dueDateField": "Vervaldatum", "caseLinesTitle": "Werklijnen", diff --git a/frontend/src/components/ui/lab/CaseCreatePanel.tsx b/frontend/src/components/ui/lab/CaseCreatePanel.tsx index 19c52d6..ec30499 100644 --- a/frontend/src/components/ui/lab/CaseCreatePanel.tsx +++ b/frontend/src/components/ui/lab/CaseCreatePanel.tsx @@ -435,17 +435,17 @@ export function CaseCreatePanel({ } } - async function handleUpload(files: File[]) { - if (!files.length || !canEdit) return; + async function handleUploadFile(file: File, onProgress: (percent: number) => void) { + if (!canEdit) return; uploadLockRef.current = true; cancelScheduledPersistRef.current(); setUploadBusy(true); try { await persist(); - const response = await casesApi.uploadAttachments(labCase.id, files); + const response = await casesApi.uploadAttachments(labCase.id, [file], onProgress); attachmentIdsRef.current = [ ...attachmentIdsRef.current, - ...response.data.map((file) => file.id), + ...response.data.map((item) => item.id), ]; persistAfterUploadRef.current = true; updatePlan((line) => ({ @@ -454,6 +454,7 @@ export function CaseCreatePanel({ })); } catch (error: unknown) { onError(getUserFacingError(error, tErrors, t('errorSaveCase'))); + throw error; } finally { uploadLockRef.current = false; setUploadBusy(false); @@ -633,7 +634,7 @@ export function CaseCreatePanel({ attachments={plan.attachments} canAdd={canEdit} adding={uploadBusy} - onAdd={(files) => void handleUpload(files)} + onUploadFile={(file, onProgress) => handleUploadFile(file, onProgress)} onDownload={(file) => casesApi.getAttachmentFileBlob(labCase.id, file.id)} onDownloadError={(error) => onError(getUserFacingError(error, tErrors, t('errorDownloadFile'))) diff --git a/frontend/src/components/ui/lab/CaseDetailPanel.tsx b/frontend/src/components/ui/lab/CaseDetailPanel.tsx index 23be803..731f228 100644 --- a/frontend/src/components/ui/lab/CaseDetailPanel.tsx +++ b/frontend/src/components/ui/lab/CaseDetailPanel.tsx @@ -260,7 +260,6 @@ export function CaseDetailPanel({ const messages = useMessages(); const toast = useToast(); const [section, setSection] = useState<'details' | 'files' | 'messages'>('details'); - const [uploadingFiles, setUploadingFiles] = useState(false); const [prosthesisCatalog, setProsthesisCatalog] = useState( prosthesisCatalogProp ?? [], ); @@ -316,17 +315,15 @@ export function CaseDetailPanel({ }, ); - async function handleAddFiles(files: File[]) { - if (!files.length || !canAddFiles) return; - setUploadingFiles(true); + async function handleUploadFile(file: File, onProgress: (percent: number) => void) { + if (!canAddFiles) return; try { - await casesApi.uploadAttachments(labCase.id, files); + await casesApi.uploadAttachments(labCase.id, [file], onProgress); const refreshed = await casesApi.getOne(labCase.id); onCaseUpdated?.(refreshed.data); - } catch { + } catch (error: unknown) { toast.showError(t('errorSaveCase')); - } finally { - setUploadingFiles(false); + throw error; } } @@ -412,39 +409,50 @@ export function CaseDetailPanel({ return (
-
-
-
-

- {formatPatientName(labCase.patient, t('walkIn'))} -

- - -
-

- {t('patientMobile')}: {formatPatientMobile(labCase.patient)} -

- {headerMetaLines} - {(labCase.sentAt || labCase.startedAt) ? ( -

- {labCase.sentAt - ? t('sentAt', { date: formatCaseDateTime(labCase.sentAt, locale) }) - : t('startedAt', { date: formatCaseDateTime(labCase.startedAt ?? null, locale) })} -

- ) : null} -
-
-

- {t('taskProgressLabel', { - completed: labCase.taskProgress.completed, - total: labCase.taskProgress.total, - })} -

- +
+
+
+
+
+

+ {formatPatientName(labCase.patient, t('walkIn'))} +

+ + +
+
+ + {t('patientMobile')}: {formatPatientMobile(labCase.patient)} + + {headerMetaLines ? ( + <> + + {headerMetaLines} + + ) : null} + {labCase.sentAt || labCase.startedAt ? ( + <> + + + {labCase.sentAt + ? t('sentAt', { date: formatCaseDateTime(labCase.sentAt, locale) }) + : t('startedAt', { date: formatCaseDateTime(labCase.startedAt ?? null, locale) })} + + + ) : null} +
+ {labCase.shareUrl ? ( +
+ +
+ ) : null} +
+
+ {canEditImportant ? (
-
+
{canEditImportant ? ( ) : null} {labCase.billedAmount != null || labCase.calculatedAmount != null ? ( -

+

{t('billedLead')} {' '} {t('billedCurrencyNote')} @@ -493,31 +501,34 @@ export function CaseDetailPanel({

- {canStop || canSend ? ( -
- {canStop && onStop ? ( +
+ {canStop && onStop ? ( +
- ) : null} - {canSend && onSend ? ( +
+ ) : null} + {canSend && onSend ? ( +
- ) : null} -
- ) : null} -
-
+
+ ) : null} +
setSheetMenuOpen((open) => !open)} @@ -543,7 +554,7 @@ export function CaseDetailPanel({
{labCase.shareUrl ? ( -
+
) : null} @@ -565,8 +576,7 @@ export function CaseDetailPanel({ void handleAddFiles(files)} + onUploadFile={(file, onProgress) => handleUploadFile(file, onProgress)} onDownload={(file) => loadAttachmentBlob(labCase.id, file.id)} onDownloadError={() => toast.showError(t('errorDownloadFile'))} /> diff --git a/frontend/src/components/ui/lab/CaseFilesPanel.tsx b/frontend/src/components/ui/lab/CaseFilesPanel.tsx index 81fa880..fcafc23 100644 --- a/frontend/src/components/ui/lab/CaseFilesPanel.tsx +++ b/frontend/src/components/ui/lab/CaseFilesPanel.tsx @@ -25,6 +25,14 @@ type CardPreview = { text?: string; }; +type PendingUpload = { + id: string; + fileName: string; + sizeBytes: number; + percent: number; + failed: boolean; +}; + type ViewerState = { fileName: string; kind: CaseFilePreviewKind | null; @@ -74,7 +82,7 @@ export function CaseFilesPanel({ canAdd, adding = false, downloading = false, - onAdd, + onUploadFile, onDownload, onDownloadError, onRemove, @@ -83,7 +91,7 @@ export function CaseFilesPanel({ canAdd: boolean; adding?: boolean; downloading?: boolean; - onAdd: (files: File[]) => void; + onUploadFile?: (file: File, onProgress: (percent: number) => void) => Promise; onDownload: (attachment: LabCaseAttachmentMeta) => Promise; onDownloadError?: (error: unknown) => void; onRemove?: (attachmentId: string) => void; @@ -101,6 +109,7 @@ export function CaseFilesPanel({ const [menuId, setMenuId] = useState(null); const [previews, setPreviews] = useState>({}); const [viewer, setViewer] = useState(null); + const [uploads, setUploads] = useState([]); const attachmentKey = attachments.map((file) => file.id).join('\n'); useEffect(() => { @@ -288,7 +297,34 @@ export function CaseFilesPanel({ } } - const working = busy || downloading || adding; + const uploading = uploads.some((item) => !item.failed); + const working = busy || downloading || adding || uploading; + + function patchUpload(id: string, patch: Partial) { + setUploads((prev) => prev.map((item) => (item.id === id ? { ...item, ...patch } : item))); + } + + async function enqueueUploads(files: File[]) { + if (!onUploadFile || files.length === 0) return; + const pending: PendingUpload[] = files.map((file) => ({ + id: `${file.name}-${file.size}-${file.lastModified}-${Math.random().toString(36).slice(2)}`, + fileName: file.name, + sizeBytes: file.size, + percent: 0, + failed: false, + })); + setUploads((prev) => [...pending, ...prev]); + for (let index = 0; index < files.length; index += 1) { + const item = pending[index]; + const file = files[index]; + try { + await onUploadFile(file, (percent) => patchUpload(item.id, { percent })); + setUploads((prev) => prev.filter((row) => row.id !== item.id)); + } catch { + patchUpload(item.id, { failed: true }); + } + } + } return (
@@ -313,7 +349,7 @@ export function CaseFilesPanel({ inputRef.current?.click()} /> @@ -324,7 +360,7 @@ export function CaseFilesPanel({ className="hidden" onChange={(event) => { const files = event.target.files ? Array.from(event.target.files) : []; - if (files.length) onAdd(files); + if (files.length) void enqueueUploads(files); event.target.value = ''; }} /> @@ -332,10 +368,63 @@ export function CaseFilesPanel({ ) : null}
- {attachments.length === 0 ? ( + {attachments.length === 0 && uploads.length === 0 ? (

{t('filesEmpty')}

) : (
    + {uploads.map((item) => ( +
  • +
    +

    + {shortFileName(item.fileName)} +

    +
    +
    + {item.failed ? ( +

    {t('filesUploadFailed')}

    + ) : ( + <> +
    +
    +
    +

    + {formatAppNumber(item.percent, locale)}% +

    + + )} +
    +
    +

    + {formatFileSize(item.sizeBytes)} +

    + {item.failed ? ( + + ) : null} +
    +
  • + ))} {attachments.map((file) => { const checked = selected.includes(file.id); const preview = previews[file.id]; diff --git a/frontend/src/components/ui/lab/CaseLifecycleButton.tsx b/frontend/src/components/ui/lab/CaseLifecycleButton.tsx index 076056a..fa205c2 100644 --- a/frontend/src/components/ui/lab/CaseLifecycleButton.tsx +++ b/frontend/src/components/ui/lab/CaseLifecycleButton.tsx @@ -15,6 +15,8 @@ type CaseLifecycleButtonProps = { isLoading?: boolean; ariaExpanded?: boolean; ariaHaspopup?: 'menu'; + /** Fill the row below the lg breakpoint. Desktop keeps the shared label width. */ + responsiveFill?: boolean; onClick: () => void; }; @@ -27,6 +29,7 @@ export function CaseLifecycleButton({ isLoading, ariaExpanded, ariaHaspopup, + responsiveFill = false, onClick, }: CaseLifecycleButtonProps) { const t = useTranslations('cases'); @@ -48,7 +51,7 @@ export function CaseLifecycleButton({ type="button" variant={variant} size="sm" - className={WORKSPACE_ACTION_BTN_CLASS} + className={`${WORKSPACE_ACTION_BTN_CLASS}${responsiveFill ? ' w-full min-w-0 lg:w-auto' : ''}`} disabled={disabled} isLoading={isLoading} aria-expanded={ariaExpanded} @@ -61,13 +64,17 @@ export function CaseLifecycleButton({ {widthLabels.map((text, index) => ( ))} - {label} + + {label} + diff --git a/frontend/src/components/ui/lab/CasesPage.tsx b/frontend/src/components/ui/lab/CasesPage.tsx index 06eb01f..84713b7 100644 --- a/frontend/src/components/ui/lab/CasesPage.tsx +++ b/frontend/src/components/ui/lab/CasesPage.tsx @@ -961,9 +961,7 @@ export function CasesPage() { canAddFiles={canEdit} onCaseUpdated={setSelectedCase} headerMetaLines={ -

    - {t('fromClinic', { name: selectedCase.clinic.name })} -

    + {t('fromClinic', { name: selectedCase.clinic.name })} } commentsSection={ selectedCaseId ? ( diff --git a/frontend/src/components/ui/lab/LabCaseShareQrDialog.tsx b/frontend/src/components/ui/lab/LabCaseShareQrDialog.tsx index 7676911..80d409b 100644 --- a/frontend/src/components/ui/lab/LabCaseShareQrDialog.tsx +++ b/frontend/src/components/ui/lab/LabCaseShareQrDialog.tsx @@ -84,18 +84,28 @@ interface LabCaseShareQrThumbProps { onClick: () => void; } -export function LabCaseShareQrThumb({ shareUrl, onClick }: LabCaseShareQrThumbProps) { +export function LabCaseShareQrThumb({ + shareUrl, + onClick, + compact = false, +}: LabCaseShareQrThumbProps & { compact?: boolean }) { const t = useTranslations('cases'); return ( ); } @@ -104,9 +114,11 @@ export function LabCaseShareQrThumb({ shareUrl, onClick }: LabCaseShareQrThumbPr export function LabCaseShareQr({ shareUrl, className, + compact = false, }: { shareUrl: string; className?: string; + compact?: boolean; }) { const [open, setOpen] = useState(false); const url = shareUrl.trim(); @@ -115,7 +127,7 @@ export function LabCaseShareQr({ return ( <>
    - setOpen(true)} /> + setOpen(true)} />
    setOpen(false)} shareUrl={url} /> diff --git a/frontend/src/components/ui/lab/TasksPage.tsx b/frontend/src/components/ui/lab/TasksPage.tsx index ee3a972..449c59e 100644 --- a/frontend/src/components/ui/lab/TasksPage.tsx +++ b/frontend/src/components/ui/lab/TasksPage.tsx @@ -683,7 +683,6 @@ export function TasksPage() { undefined} onDownload={(file) => casesApi.getAttachmentFileBlob(caseGroup.labCaseId, file.id) } diff --git a/frontend/src/components/ui/shared/MobileDetailBackButton.tsx b/frontend/src/components/ui/shared/MobileDetailBackButton.tsx index 9284217..828b15c 100644 --- a/frontend/src/components/ui/shared/MobileDetailBackButton.tsx +++ b/frontend/src/components/ui/shared/MobileDetailBackButton.tsx @@ -24,7 +24,7 @@ export function MobileDetailBackButton({ + ); + } + + const isRecording = voice.phase === 'recording'; + const isBusy = voice.phase !== 'idle'; + const micLabel = isRecording ? stopLabel : startLabel; + + return ( +
    +
    + + +
    + +
    + ); +} diff --git a/frontend/src/components/ui/lab/CaseCreatePanel.tsx b/frontend/src/components/ui/lab/CaseCreatePanel.tsx index ec30499..3f38f85 100644 --- a/frontend/src/components/ui/lab/CaseCreatePanel.tsx +++ b/frontend/src/components/ui/lab/CaseCreatePanel.tsx @@ -2,7 +2,6 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { useLocale, useTranslations } from 'next-intl'; -import { Mic, Square } from 'lucide-react'; import { getUserFacingError } from '@/components/shared/formatApiError'; import { invalidPonticTeethOnDetail, @@ -29,7 +28,6 @@ import { AppDateInput } from '@/components/ui/shared/AppDateInput'; import { CaseLifecycleButton } from '@/components/ui/lab/CaseLifecycleButton'; import { UnderlineTabs } from '@/components/ui/shared/UnderlineTabs'; import { ProsthesisAssignChart } from '@/components/ui/treatment/ProsthesisAssignChart'; -import { VoiceRecordingBar } from '@/components/ui/treatment/VoiceRecordingBar'; import { VoiceReviewSheet } from '@/components/ui/treatment/VoiceReviewSheet'; import { isBlankLine, type LineDraft } from '@/components/lab/caseLineDraft'; import { commentVisibilityProps } from '@/components/lab/labCaseOrigin'; @@ -38,19 +36,14 @@ import { buildLabLineFromVoice } from '@/components/lab/voiceLine'; import { caseCommentsApi } from '@/lib/api/case-comments'; import { casesApi } from '@/lib/api/cases'; import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog'; -import { voiceApi } from '@/lib/api/voice'; -import { isMediaRecorderSupported } from '@/lib/voice/audioFormat'; -import { useVoiceCapture, type VoiceCaptureState } from '@/lib/voice/useVoiceCapture'; +import { useCaseSectionCounts } from '@/lib/hooks/useCaseSectionCounts'; +import { tabBadgesChangedEventName } from '@/lib/tabBadgeUtils'; import type { LabCaseDetail } from '@/types/cases'; import type { FdiToothId } from '@/types/treatment'; import type { LinkedOrganizationOption } from '@/types/treatment'; import type { ToothSelectionGroup } from '@/components/treatment/toothSelectionGroups'; import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; -import type { - VoiceApplySelection, - VoiceAvailability, - VoiceExtractionResult, -} from '@/types/voice'; +import type { VoiceApplySelection, VoiceExtractionResult } from '@/types/voice'; const INPUT_CLASS = 'mt-1 w-full rounded-[var(--radius-md)] border border-border bg-background-secondary/90 text-text-primary text-sm px-3 py-2 placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/35'; @@ -138,6 +131,9 @@ interface CaseCreatePanelProps { labCase: LabCaseDetail; canEdit: boolean; prosthesisCatalog?: ProsthesisCatalogEntry[]; + /** Dictation owned by the Add case control. Applied onto this case's single plan. */ + voiceResult?: VoiceExtractionResult | null; + onVoiceResultHandled?: () => void; onSaved: (detail: LabCaseDetail) => void; onStarted: (detail: LabCaseDetail) => void; onDeleted: () => void; @@ -148,6 +144,8 @@ export function CaseCreatePanel({ labCase, canEdit, prosthesisCatalog, + voiceResult = null, + onVoiceResultHandled, onSaved, onStarted, onDeleted, @@ -178,12 +176,11 @@ export function CaseCreatePanel({ const [dueDate, setDueDate] = useState(toDateInputValue(labCase.dueDate)); const [plan, setPlan] = useState(() => planFromDetail(labCase)); const [section, setSection] = useState<'details' | 'files' | 'messages'>('details'); + const sectionCounts = useCaseSectionCounts(labCase.id, section); const [partners, setPartners] = useState([]); const [prosthesisOptions, setProsthesisOptions] = useState( prosthesisCatalog ?? [], ); - const [voiceAvailability, setVoiceAvailability] = useState(null); - const [voiceResult, setVoiceResult] = useState(null); const [saving, setSaving] = useState(false); const [starting, setStarting] = useState(false); const [deleting, setDeleting] = useState(false); @@ -218,7 +215,6 @@ export function CaseCreatePanel({ useEffect(() => { void casesApi.listLinkedClinics().then((r) => setPartners(r.data)).catch(() => undefined); - void voiceApi.availability().then((r) => setVoiceAvailability(r.data)).catch(() => undefined); }, []); useEffect(() => { @@ -229,24 +225,6 @@ export function CaseCreatePanel({ void prosthesisCatalogApi.list().then((r) => setProsthesisOptions(r.data)).catch(() => undefined); }, [prosthesisCatalog]); - const voice = useVoiceCapture({ - // The locale the lab owner is reading and speaking in, so the ASR hint, the catalog labels - // and the week start all match what the microphone was offered for. - locale, - maxMs: voiceAvailability?.maxRecordingMs ?? null, - onExtracted: setVoiceResult, - onError: (error) => - onError(getUserFacingError(error, tErrors, tTreatment('voiceFailed'))), - }); - - // Absence renders the Add Line button unsplit. Gated on the browser's own recording support - // as well as the server config: without it the control appears on a browser that cannot - // record and fails on tap. - const voiceEnabled = - Boolean(voiceAvailability?.enabled) && - (voiceAvailability?.locales.includes(locale) ?? false) && - isMediaRecorderSupported(); - const groups = plan.toothSelectionGroups.length > 0 ? plan.toothSelectionGroups @@ -346,16 +324,50 @@ export function CaseCreatePanel({ setPlan((prev) => patch(prev)); } + useEffect(() => { + if (section !== 'files') return; + const onChanged = () => { + void casesApi.listAttachments(labCase.id).then((response) => { + setPlan((current) => ({ ...current, attachments: response.data })); + }).catch(() => undefined); + }; + window.addEventListener(tabBadgesChangedEventName(), onChanged); + return () => window.removeEventListener(tabBadgesChangedEventName(), onChanged); + }, [labCase.id, section]); + + async function handleRemoveAttachment(attachmentId: string) { + const accepted = await confirm({ + title: tCommon('confirmTitle'), + message: t('filesRemoveConfirm'), + confirmLabel: t('filesRemove'), + cancelLabel: tCommon('cancel'), + tone: 'danger', + }); + if (!accepted) return; + cancelScheduledPersistRef.current(); + if (persistInFlightRef.current) { + await persistInFlightRef.current.catch(() => null); + } + try { + await casesApi.removeAttachment(labCase.id, attachmentId); + updatePlan((line) => ({ + ...line, + attachments: line.attachments.filter((file) => file.id !== attachmentId), + })); + } catch (error: unknown) { + onError(getUserFacingError(error, tErrors, t('errorSaveCase'))); + } + } + /** - * One dictation is one line. It fills the active line while that line is still blank — a - * fresh draft opens with one, and always appending would leave it above the dictated line - * and ship it to the floor, since `start` only requires that *some* line carries jobs. + * One dictation fills this case's single plan. A blank plan is replaced; a plan that + * already has jobs is merged. A dictated due date and comment still land. */ function applyVoice(selection: VoiceApplySelection, applied: VoiceExtractionResult) { const { line, dueDate: dictatedDueDate } = buildLabLineFromVoice(applied, selection, { prosthesisCatalog: prosthesisOptions, }); - setVoiceResult(null); + onVoiceResultHandled?.(); if (dictatedDueDate) setDueDate(dictatedDueDate); // Null when the dictation carried no line content — a due date on its own still lands. // Without the notice, Apply on a row that lands no job closes the sheet and changes nothing. @@ -555,24 +567,13 @@ export function CaseCreatePanel({ onChange={setSection} tabs={[ { id: 'details', label: t('tabDetails') }, - { id: 'files', label: t('tabFiles') }, - { id: 'messages', label: t('tabMessages') }, + { id: 'files', label: t('tabFiles'), count: sectionCounts.files }, + { id: 'messages', label: t('tabMessages'), count: sectionCounts.messages }, ]} /> {section === 'details' ? (
    - {voiceEnabled ? ( -
    - -
    - ) : null} - {voiceEnabled ? : null} onError(getUserFacingError(error, tErrors, t('errorDownloadFile'))) } - onRemove={ - canEdit - ? (attachmentId) => - updatePlan((line) => ({ - ...line, - attachments: line.attachments.filter((file) => file.id !== attachmentId), - })) - : undefined - } + onRemove={canEdit ? (attachmentId) => void handleRemoveAttachment(attachmentId) : undefined} /> ) : null} @@ -682,7 +675,7 @@ export function CaseCreatePanel({ result={voiceResult} prosthesisCatalog={prosthesisOptions} onApply={(selection, applied) => applyVoice(selection, applied)} - onDiscard={() => setVoiceResult(null)} + onDiscard={() => onVoiceResultHandled?.()} /> ) : null} @@ -698,37 +691,3 @@ export function CaseCreatePanel({
    ); } - -function VoiceCaptureButton({ - startLabel, - stopLabel, - disabled, - voice, -}: { - startLabel: string; - stopLabel: string; - disabled: boolean; - voice: VoiceCaptureState; -}) { - const isRecording = voice.phase === 'recording'; - const micLabel = isRecording ? stopLabel : startLabel; - return ( - - ); -} diff --git a/frontend/src/components/ui/lab/CaseDetailPanel.tsx b/frontend/src/components/ui/lab/CaseDetailPanel.tsx index 731f228..9153368 100644 --- a/frontend/src/components/ui/lab/CaseDetailPanel.tsx +++ b/frontend/src/components/ui/lab/CaseDetailPanel.tsx @@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { useLocale, useMessages, useTranslations } from 'next-intl'; +import { getUserFacingError } from '@/components/shared/formatApiError'; import { Badge } from '@/components/ui/shared/Badge'; import { Button } from '@/components/ui/shared/Button'; import { CaseLifecycleButton } from '@/components/ui/lab/CaseLifecycleButton'; @@ -29,6 +30,8 @@ import type { CaseSheetOrientation } from '@/components/ui/lab/CaseSheetPrintLay import { caseCommentsApi } from '@/lib/api/case-comments'; import { casesApi } from '@/lib/api/cases'; import { UnderlineTabs } from '@/components/ui/shared/UnderlineTabs'; +import { useConfirm } from '@/components/ui/shared/ConfirmProvider'; +import { useCaseSectionCounts } from '@/lib/hooks/useCaseSectionCounts'; import { ConnectedSelectionBadge } from '@/components/ui/treatment/ConnectedSelectionBadge'; import { useToast } from '@/lib/hooks/useToast'; import { formatAppMoney } from '@/lib/i18n/format'; @@ -256,10 +259,14 @@ export function CaseDetailPanel({ const t = useTranslations('cases'); const tTreatment = useTranslations('treatment'); const tComments = useTranslations('caseComments'); + const tErrors = useTranslations('errors'); + const tCommon = useTranslations('common'); const intlLocale = useLocale(); const messages = useMessages(); const toast = useToast(); + const confirm = useConfirm(); const [section, setSection] = useState<'details' | 'files' | 'messages'>('details'); + const sectionCounts = useCaseSectionCounts(labCase.id, section); const [prosthesisCatalog, setProsthesisCatalog] = useState( prosthesisCatalogProp ?? [], ); @@ -327,6 +334,25 @@ export function CaseDetailPanel({ } } + async function handleRemoveFile(attachmentId: string) { + if (!canAddFiles) return; + const accepted = await confirm({ + title: tCommon('confirmTitle'), + message: t('filesRemoveConfirm'), + confirmLabel: t('filesRemove'), + cancelLabel: tCommon('cancel'), + tone: 'danger', + }); + if (!accepted) return; + try { + await casesApi.removeAttachment(labCase.id, attachmentId); + const refreshed = await casesApi.getOne(labCase.id); + onCaseUpdated?.(refreshed.data); + } catch (error: unknown) { + toast.showError(getUserFacingError(error, tErrors, t('errorSaveCase'))); + } + } + async function handleDownloadCaseSheet(orientation: CaseSheetOrientation) { setSheetMenuOpen(false); setDownloadingPdf(true); @@ -444,7 +470,7 @@ export function CaseDetailPanel({
{labCase.shareUrl ? (
- +
) : null}
@@ -567,8 +593,8 @@ export function CaseDetailPanel({ onChange={setSection} tabs={[ { id: 'details', label: t('tabDetails') }, - { id: 'files', label: t('tabFiles') }, - { id: 'messages', label: t('tabMessages') }, + { id: 'files', label: t('tabFiles'), count: sectionCounts.files }, + { id: 'messages', label: t('tabMessages'), count: sectionCounts.messages }, ]} /> @@ -579,6 +605,7 @@ export function CaseDetailPanel({ onUploadFile={(file, onProgress) => handleUploadFile(file, onProgress)} onDownload={(file) => loadAttachmentBlob(labCase.id, file.id)} onDownloadError={() => toast.showError(t('errorDownloadFile'))} + onRemove={canAddFiles ? (attachmentId) => void handleRemoveFile(attachmentId) : undefined} /> ) : null} diff --git a/frontend/src/components/ui/lab/CasesPage.tsx b/frontend/src/components/ui/lab/CasesPage.tsx index 84713b7..5b47b77 100644 --- a/frontend/src/components/ui/lab/CasesPage.tsx +++ b/frontend/src/components/ui/lab/CasesPage.tsx @@ -2,11 +2,12 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useSearchParams } from 'next/navigation'; -import { useTranslations } from 'next-intl'; +import { useLocale, useTranslations } from 'next-intl'; import { getUserFacingError } from '@/components/shared/formatApiError'; import { useAuth } from '@/lib/hooks/useAuth'; import { useToast } from '@/lib/hooks/useToast'; import { canEditCases } from '@/components/shared/permissions'; +import { AddCaseWithVoice } from '@/components/ui/lab/AddCaseWithVoice'; import { CaseDetailPanel, CaseTaskProgressBar } from '@/components/ui/lab/CaseDetailPanel'; import { CaseSendDialog } from '@/components/ui/lab/CaseSendDialog'; import { CaseCreatePanel } from '@/components/ui/lab/CaseCreatePanel'; @@ -29,7 +30,10 @@ 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 { voiceApi } from '@/lib/api/voice'; +import { isMediaRecorderSupported } from '@/lib/voice/audioFormat'; +import { useVoiceCapture } from '@/lib/voice/useVoiceCapture'; +import type { VoiceAvailability, VoiceExtractionResult } from '@/types/voice'; import { Badge } from '@/components/ui/shared/Badge'; import { Button } from '@/components/ui/shared/Button'; import { MobileDetailBackButton } from '@/components/ui/shared/MobileDetailBackButton'; @@ -128,6 +132,39 @@ export function CasesPage() { const canEdit = canEditCases(currentOrganization); const locale = user?.language ?? 'en'; + const pageLocale = useLocale(); + const tTreatment = useTranslations('treatment'); + const [voiceAvailability, setVoiceAvailability] = useState(null); + const [voiceResult, setVoiceResult] = useState(null); + const voiceCaseIdRef = useRef(null); + const onVoiceExtractedRef = useRef<(result: VoiceExtractionResult) => void>(() => {}); + onVoiceExtractedRef.current = (result) => { + if (voiceCaseIdRef.current && voiceCaseIdRef.current === selectedCaseIdRef.current) { + setVoiceResult(result); + } + }; + + useEffect(() => { + void voiceApi.availability().then((response) => setVoiceAvailability(response.data)).catch(() => undefined); + }, []); + + const voice = useVoiceCapture({ + locale: pageLocale, + maxMs: voiceAvailability?.maxRecordingMs ?? null, + onExtracted: (result) => onVoiceExtractedRef.current(result), + onError: (error) => + toast.showError(getUserFacingError(error, tErrors, tTreatment('voiceFailed'))), + }); + const voiceEnabled = + Boolean(voiceAvailability?.enabled) && + (voiceAvailability?.locales.includes(pageLocale) ?? false) && + isMediaRecorderSupported(); + + useEffect(() => { + if (voiceCaseIdRef.current && selectedCaseId !== voiceCaseIdRef.current) { + setVoiceResult(null); + } + }, [selectedCaseId]); const prosthesisLabel = useCallback( (code: string) => @@ -374,8 +411,8 @@ export function CasesPage() { // eslint-disable-next-line react-hooks/exhaustive-deps -- reload when selection changes }, [selectedCaseId]); - async function handleAddCase() { - if (!canEdit || creatingCase) return; + async function handleAddCase(): Promise { + if (!canEdit || creatingCase) return null; setCreatingCase(true); setDraftsExpanded(true); toast.setError(''); @@ -399,13 +436,29 @@ export function CasesPage() { selectedCaseIdRef.current = created.id; setSelectedCaseId(created.id); setDraftsExpanded(true); + return created.id; } catch (error: unknown) { toast.showError(getUserFacingError(error, tErrors, t('errorCreateCase'))); + return null; } finally { setCreatingCase(false); } } + async function handleAddCaseVoice() { + if (voice.phase === 'recording') { + voice.onStop(); + return; + } + if (voice.phase !== 'idle' || creatingCase) return; + const openDraftId = + selectedCase && isDraftLabCase(selectedCase) ? selectedCase.id : null; + const caseId = openDraftId ?? (await handleAddCase()); + if (!caseId) return; + voiceCaseIdRef.current = caseId; + voice.onStart(); + } + const loadCaseAttachmentBlob = useCallback( (caseId: string, attachmentId: string) => casesApi.getAttachmentFileBlob(caseId, attachmentId), [], @@ -678,15 +731,15 @@ export function CasesPage() { }`} > {canEdit ? ( -
- void handleAddCase()} - /> -
+ void handleAddCase()} + onVoice={() => void handleAddCaseVoice()} + /> ) : null} { + setVoiceResult(null); + voiceCaseIdRef.current = null; + }} onSaved={(detail) => { setSelectedCase(detail); const patchItem = (item: LabCaseListItem): LabCaseListItem => diff --git a/frontend/src/components/ui/lab/LabCaseCommentsPanel.tsx b/frontend/src/components/ui/lab/LabCaseCommentsPanel.tsx index 23eb054..12af3ec 100644 --- a/frontend/src/components/ui/lab/LabCaseCommentsPanel.tsx +++ b/frontend/src/components/ui/lab/LabCaseCommentsPanel.tsx @@ -1,6 +1,7 @@ 'use client'; import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'; +import { tabBadgesChangedEventName } from '@/lib/tabBadgeUtils'; import { useTranslations } from 'next-intl'; import { Eye, EyeOff, Send } from 'lucide-react'; import { getUserFacingError } from '@/components/shared/formatApiError'; @@ -77,15 +78,15 @@ export function LabCaseCommentsPanel({ const loadCommentsRef = useRef(loadComments); loadCommentsRef.current = loadComments; - const refresh = useCallback(async () => { - setLoading(true); + const refresh = useCallback(async (options?: { silent?: boolean }) => { + if (!options?.silent) setLoading(true); try { const items = await loadCommentsRef.current(); setComments(sortNewestFirst(items)); } catch (error: unknown) { onError?.(getUserFacingError(error, tErrors, t('errorLoad'))); } finally { - setLoading(false); + if (!options?.silent) setLoading(false); } }, [onError, t, tErrors]); @@ -93,6 +94,14 @@ export function LabCaseCommentsPanel({ void refresh(); }, [caseId, refresh]); + useEffect(() => { + const onChanged = () => { + void refresh({ silent: true }); + }; + window.addEventListener(tabBadgesChangedEventName(), onChanged); + return () => window.removeEventListener(tabBadgesChangedEventName(), onChanged); + }, [refresh]); + async function handlePost() { const trimmed = body.trim(); if (!trimmed || !canPost || posting) return; diff --git a/frontend/src/components/ui/shared/UnderlineTabs.tsx b/frontend/src/components/ui/shared/UnderlineTabs.tsx index 1fa5293..252c425 100644 --- a/frontend/src/components/ui/shared/UnderlineTabs.tsx +++ b/frontend/src/components/ui/shared/UnderlineTabs.tsx @@ -1,5 +1,7 @@ 'use client'; +import { NavBadgePill } from '@/components/ui/shared/NavBadgePill'; + export function UnderlineTabs({ label, tabs, @@ -7,7 +9,7 @@ export function UnderlineTabs({ onChange, }: { label: string; - tabs: Array<{ id: T; label: string }>; + tabs: Array<{ id: T; label: string; count?: number }>; value: T; onChange: (id: T) => void; }) { @@ -22,13 +24,16 @@ export function UnderlineTabs({ role="tab" aria-selected={active} onClick={() => onChange(tab.id)} - className={`-mb-px border-b-2 px-3 py-2 text-base font-bold transition-colors ${ + className={`relative -mb-px border-b-2 px-3 py-2 text-base font-bold transition-colors ${ active ? 'border-primary text-primary' : 'border-transparent text-text-secondary hover:text-text-primary' }`} > {tab.label} + + + ); })} diff --git a/frontend/src/components/ui/treatment/TreatmentDetailsEditor.tsx b/frontend/src/components/ui/treatment/TreatmentDetailsEditor.tsx index eecb461..e91653c 100644 --- a/frontend/src/components/ui/treatment/TreatmentDetailsEditor.tsx +++ b/frontend/src/components/ui/treatment/TreatmentDetailsEditor.tsx @@ -32,6 +32,8 @@ interface TreatmentDetailsEditorProps { onActiveDetailChange: (id: string) => void; onDetailsChange: (details: TreatmentDetailDraft[]) => void; isDetailLocked: (detail: TreatmentDetailDraft) => boolean; + /** Sent to a lab. Distinct from the edit lock, which waits for a completed step. */ + isDetailSent: (detail: TreatmentDetailDraft) => boolean; labDependentCodes: Set; treatmentCatalog: TreatmentCatalogEntry[]; disabled: boolean; @@ -82,6 +84,7 @@ export function TreatmentDetailsEditor({ onActiveDetailChange, onDetailsChange, isDetailLocked, + isDetailSent, labDependentCodes, treatmentCatalog, disabled, @@ -232,6 +235,7 @@ export function TreatmentDetailsEditor({
{details.map((d, idx) => { const detailLocked = isDetailLocked(d); + const detailSent = isDetailSent(d); const isActive = d.clientId === activeDetailId; const showRemoveAction = Boolean(onRemoveDetail); const removeDisabled = !canEdit || disabled || Boolean(d.sentAt) || detailLocked || uploadBusy; @@ -268,12 +272,12 @@ export function TreatmentDetailsEditor({ {showLabStatus ? ( - · {detailLocked ? t('detailSentBadge') : t('detailUnsentBadge')} + · {detailSent ? t('detailSentBadge') : t('detailUnsentBadge')} ) : null} diff --git a/frontend/src/components/ui/treatment/TreatmentWorkspace.tsx b/frontend/src/components/ui/treatment/TreatmentWorkspace.tsx index a04fdbb..898b2df 100644 --- a/frontend/src/components/ui/treatment/TreatmentWorkspace.tsx +++ b/frontend/src/components/ui/treatment/TreatmentWorkspace.tsx @@ -602,6 +602,13 @@ export function TreatmentWorkspace({ [labCaseDrafts], ); + const isDetailSent = useCallback( + (detail: TreatmentDetailDraft) => + Boolean(detail.sentAt) || + labCaseDrafts.some((lc) => Boolean(lc.sentAt) && lc.detailClientId === detail.clientId), + [labCaseDrafts], + ); + const activeSentLabCaseId = useMemo(() => { const match = labCaseDrafts.find( (lc) => lc.detailClientId === activeDetailId && lc.sentAt && lc.id, @@ -1351,7 +1358,52 @@ export function TreatmentWorkspace({ useEffect(() => { const appointmentId = selectedAppointment?.id; const treatmentId = selectedStandalone?.id; - if ((!appointmentId && !treatmentId) || workspaceMode !== 'live') return; + if (workspaceMode !== 'live') return; + + // A day with no visit must match a fresh open of the tab: one blank line, + // no patient, no leftover plan from the day the arrows just left. + if (!appointmentId && !treatmentId) { + const current = detailsRef.current; + const drafts = labCaseDraftsRef.current; + const alreadyBlank = + current.length === 1 && + !isDetailTypeSelected(current[0]) && + current[0].teeth.length === 0 && + current[0].toothSelectionGroups.length === 0 && + current[0].comment.trim() === '' && + current[0].attachmentMetas.length === 0 && + !current[0].sentAt && + drafts.length === 0; + if (alreadyBlank) return; + + const first = newDetail(); + const snap = serializeDetails([first]); + const emptyLab = serializeLabCases([]); + detailsRef.current = [first]; + savedSnapshotRef.current = snap; + labCaseDraftsRef.current = []; + savedLabCasesSnapshotRef.current = emptyLab; + setDetails([first]); + setActiveDetailId(first.clientId); + setSavedSnapshot(snap); + setLabCaseDrafts([]); + setSavedLabCasesSnapshot(emptyLab); + setActiveLabCaseId(null); + setSaveStatus('idle'); + setPlanBilledManual(false); + setPlanBilledAmount(''); + setLabWorkspaceView('chart'); + setShowWholeTreatmentPlan(false); + setOrganizationSearch(''); + setVoiceResult(null); + setSelectedPreviewId(null); + setSelectedRailLabCaseId(null); + if (autosaveTimerRef.current) { + clearTimeout(autosaveTimerRef.current); + autosaveTimerRef.current = null; + } + return; + } if (skipNextGetDraftRef.current) { skipNextGetDraftRef.current = false; @@ -3050,6 +3102,7 @@ export function TreatmentWorkspace({ onDetailsChange={setDetails} onTreatmentTypeChange={handleTreatmentTypeChange} isDetailLocked={isDetailLocked} + isDetailSent={isDetailSent} labDependentCodes={labDependentCodes} treatmentCatalog={treatmentDropdownCatalog} disabled={!canEditTreatmentForDay} diff --git a/frontend/src/lib/api/cases.ts b/frontend/src/lib/api/cases.ts index cc446c4..d304de6 100644 --- a/frontend/src/lib/api/cases.ts +++ b/frontend/src/lib/api/cases.ts @@ -94,6 +94,29 @@ export const casesApi = { return response.data; }, + removeAttachment: async ( + caseId: string, + attachmentId: string, + ): Promise<{ success: boolean }> => { + const response = await apiClient.delete(`/cases/${caseId}/attachments/${attachmentId}`); + return response.data; + }, + + sectionCounts: async ( + caseId: string, + ): Promise<{ success: boolean; data: { files: number; messages: number } }> => { + const response = await apiClient.get(`/cases/${caseId}/section-counts`); + return response.data; + }, + + markSectionRead: async ( + caseId: string, + section: 'FILES' | 'MESSAGES', + ): Promise<{ success: boolean }> => { + const response = await apiClient.post(`/cases/${caseId}/sections/${section}/read`); + return response.data; + }, + uploadAttachments: async ( caseId: string, files: File[], diff --git a/frontend/src/lib/hooks/useCaseSectionCounts.ts b/frontend/src/lib/hooks/useCaseSectionCounts.ts new file mode 100644 index 0000000..d4c7e3c --- /dev/null +++ b/frontend/src/lib/hooks/useCaseSectionCounts.ts @@ -0,0 +1,49 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { casesApi } from '@/lib/api/cases'; +import { tabBadgesChangedEventName } from '@/lib/tabBadgeUtils'; + +export type CasePanelSection = 'details' | 'files' | 'messages'; + +const EMPTY = { files: 0, messages: 0 }; + +/** + * Unread Files and Messages counts for one case. + * Opening Details does not clear either cursor. The open Files or Messages tab is marked read. + */ +export function useCaseSectionCounts(caseId: string, section: CasePanelSection) { + const [counts, setCounts] = useState(EMPTY); + + useEffect(() => { + let cancelled = false; + + async function load() { + try { + const response = await casesApi.sectionCounts(caseId); + if (cancelled) return; + const next = { ...response.data }; + if (section === 'files' || section === 'messages') { + await casesApi.markSectionRead(caseId, section === 'files' ? 'FILES' : 'MESSAGES'); + if (cancelled) return; + next[section] = 0; + } + setCounts(next); + } catch { + if (!cancelled) setCounts(EMPTY); + } + } + + void load(); + const onChanged = () => { + void load(); + }; + window.addEventListener(tabBadgesChangedEventName(), onChanged); + return () => { + cancelled = true; + window.removeEventListener(tabBadgesChangedEventName(), onChanged); + }; + }, [caseId, section]); + + return counts; +} diff --git a/frontend/src/lib/labCaseActivityLabels.ts b/frontend/src/lib/labCaseActivityLabels.ts index 27a3cb8..f1bef0c 100644 --- a/frontend/src/lib/labCaseActivityLabels.ts +++ b/frontend/src/lib/labCaseActivityLabels.ts @@ -47,6 +47,8 @@ export function formatLabCaseActivityLine( return t('activityCaseCompleted', { actor, date }); case 'CASE_AMENDED': return t('activityCaseAmended', { actor, date }); + case 'ATTACHMENT_ADDED': + return t('activityAttachmentAdded', { actor, date }); default: return t('activityGeneric', { date }); } diff --git a/frontend/src/lib/realtime/RealtimeProvider.tsx b/frontend/src/lib/realtime/RealtimeProvider.tsx index f5035b5..5bffbe3 100644 --- a/frontend/src/lib/realtime/RealtimeProvider.tsx +++ b/frontend/src/lib/realtime/RealtimeProvider.tsx @@ -101,6 +101,10 @@ export function RealtimeProvider({ children }: { children: ReactNode }) { setUnreadCount(payload.count); } }); + // File uploads have no inbox card. Refresh open case tabs the same way comments do. + socket.on('case-section.changed', () => { + notifyTabBadgesChanged(); + }); return () => { socket.disconnect(); diff --git a/frontend/src/types/lab-case-activity.ts b/frontend/src/types/lab-case-activity.ts index 8c0fe66..7aa9f49 100644 --- a/frontend/src/types/lab-case-activity.ts +++ b/frontend/src/types/lab-case-activity.ts @@ -6,7 +6,8 @@ export type LabCaseActivityType = | 'CASE_AMENDED' | 'TASK_COMPLETED' | 'TASK_ASSIGNED' - | 'CASE_COMPLETED'; + | 'CASE_COMPLETED' + | 'ATTACHMENT_ADDED'; export interface LabCaseActivityItem { id: string; -- 2.53.0.windows.1 From 3cb579eaac2e8249e91e757f9ae68d6c613eeaf6 Mon Sep 17 00:00:00 2001 From: Admin Date: Sat, 10 Oct 2026 02:28:06 +0330 Subject: [PATCH 3/3] improvment: code reviewd. some bugs when removing an attachment fixed. --- .cursor/rules/adminjs.mdc | 2 +- .cursor/rules/dyolink-overview.mdc | 2 +- .cursor/rules/lab-cases.mdc | 2 +- .cursor/skills/lab-cases/SKILL.md | 6 +- .cursor/skills/notifications-inbox/SKILL.md | 2 + .cursor/skills/tab-badges/SKILL.md | 3 +- .cursor/skills/treatment-workspace/SKILL.md | 4 +- AGENTS.md | 6 +- backend/src/modules/cases/cases.service.ts | 172 +++++++++--------- .../user-notification.service.ts | 19 +- .../src/components/ui/lab/CaseCreatePanel.tsx | 16 +- .../src/components/ui/lab/CaseDetailPanel.tsx | 2 +- .../ui/treatment/TreatmentDetailsEditor.tsx | 3 +- .../ui/treatment/TreatmentWorkspace.tsx | 1 + .../src/lib/hooks/useCaseSectionCounts.ts | 2 +- infrastructure/DEPLOY.md | 6 + infrastructure/STAGING-DEPLOY.md | 2 + infrastructure/nginx/http-only.conf | 1 + infrastructure/nginx/http-only.dev.conf | 1 + infrastructure/nginx/nginx.conf | 1 + infrastructure/nginx/nginx.ssl.conf.template | 1 + infrastructure/nginx/windows-edge-http.conf | 2 + 22 files changed, 147 insertions(+), 109 deletions(-) diff --git a/.cursor/rules/adminjs.mdc b/.cursor/rules/adminjs.mdc index 3579910..ea8c8f8 100644 --- a/.cursor/rules/adminjs.mdc +++ b/.cursor/rules/adminjs.mdc @@ -17,7 +17,7 @@ Ops panel at `/admin` (`backend/src/admin/`). Resources are a **manual allowlist 3. **Renamed / removed model** → update or remove the matching resource (broken `getModelByName` breaks `/admin` boot). 4. **New secret fields** (hashes, tokens, share tokens) → hide via `isVisible: false` (list/filter/show/edit). 5. **Catalog-like reference data** → list/show/edit only; disable `new` / `delete` / `bulkDelete`. -6. **Composite `@@id` only** (no single `@id`) → **do not register** — AdminJS list returns 500 (`Resource does not have an id property`). Examples: `LabCaseDetail`, `LabCaseAttachment`, `MembershipPermission`, read-cursor tables. +6. **Composite `@@id` only** (no single `@id`) → **do not register** — AdminJS list returns 500 (`Resource does not have an id property`). Examples: `LabCaseDetail`, `LabCaseAttachment`, `LabCaseSectionReadState`, `MembershipPermission`, read-cursor tables. 7. Skip pure join/cursor tables unless ops need them and they have a single id. **Do register** single-id models such as `StaffWorkingHoursSchedule` / `StaffWorkingHoursBlock`. Auth: `ADMINJS_EMAIL` / `ADMINJS_PASSWORD` — production login disabled if password missing or still `admin123`. diff --git a/.cursor/rules/dyolink-overview.mdc b/.cursor/rules/dyolink-overview.mdc index d6604a4..866f845 100644 --- a/.cursor/rules/dyolink-overview.mdc +++ b/.cursor/rules/dyolink-overview.mdc @@ -47,4 +47,4 @@ Logical failures: `AppException(ErrorCode.X)` → `errors.X` in en/fa/nl. UI: `g ## Notifications (inbox + live tabs) -Header bell: `UserNotification` + Socket.IO. Same `notification.created` also drives sidebar tab badges and soft list refresh on **currently open** Cases/Tasks/Treatment/Orgs pages. Inbox + Tasks/Treatment badges use **`CASE_COMPLETED`** (every task in the case done); per-step `TASK_COMPLETED` is timeline-only. Skills: `.cursor/skills/notifications-inbox/SKILL.md`, `.cursor/skills/tab-badges/SKILL.md`. +Header bell: `UserNotification` + Socket.IO. Same `notification.created` also drives sidebar tab badges and soft list refresh on **currently open** Cases/Tasks/Treatment/Orgs pages. A case file upload emits `case-section.changed` on that socket (no inbox row) for the case Files/Messages counts. Inbox + Tasks/Treatment badges use **`CASE_COMPLETED`** (every task in the case done); per-step `TASK_COMPLETED` is timeline-only. Skills: `.cursor/skills/notifications-inbox/SKILL.md`, `.cursor/skills/tab-badges/SKILL.md`. diff --git a/.cursor/rules/lab-cases.mdc b/.cursor/rules/lab-cases.mdc index ef00d37..db59536 100644 --- a/.cursor/rules/lab-cases.mdc +++ b/.cursor/rules/lab-cases.mdc @@ -17,7 +17,7 @@ alwaysApply: false - **One plan:** a live case has one prosthesis plan. Clinic send still uses `treatmentDetailId` as `sourceKey`. Lab-origin cases use the case id. Outsource children use the child case id, or `childId:parentSourceKey` when two selected steps would collide (see Outsource). `LabCaseLine` is gone. Detail and New case use `UnderlineTabs`: Details, Files, Messages. Files and Messages show unread counts (`LabCaseSectionReadState`); opening Details does not clear them. `ATTACHMENT_ADDED` is not a sidebar badge. 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, 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). The page stays LTR in every locale. On `fa`, the org name is a shrink-wrapped `inline-block` (`direction: ltr` unless the name itself contains Arabic script) with `letter-spacing` and `word-spacing` `0px` — a full-width RTL box gaps Latin words. Party and meta values use `printRtlValueStyle` (Arabic script stays RTL; Latin stays LTR and right-aligned). `FA_RULE_DROP` (6px) clears Persian descenders. `onclone` must not overwrite the name span’s direction. 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 on `lg`. Below that, the header is one compact stack: name and the same QR thumb as desktop (`w-24 sm:w-32`) on the first row, mobile/from/date on one wrapping line, the progress bar without a separate “tasks completed” sentence, important and billed on one row, and Edit / Outsource / Get PDF sharing one row (`responsiveFill`). External code sits under the progress bar in the start column, same width as the bar; billed price is under important on `lg`. Get PDF and Add files are primary `CaseLifecycleButton`s with no icon, the same width as Outsource from `lg` up. **Add case** is a full-width `px-6 py-3 text-base` split (label + mic) matching New treatment and Add detail voice. 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. Remove is on that menu (`DELETE /cases/:id/attachments/:attachmentId`, confirm first). An in-progress upload is its own card with a progress bar. The sent-date line reads “Outsource {date}”. -- **Attachments:** no size cap. One file per request, streamed with `orgDiskStorage` (not memory). The client has no axios timeout. Nginx `/api` uses `client_max_body_size 0`. Do not set `Content-Type: multipart/form-data` by hand. +- **Attachments:** no size cap. One file per request, streamed with `orgDiskStorage` (not memory). The client has no axios timeout. Nginx `/api` uses `client_max_body_size 0`, `send_timeout 3600s`, and `proxy_request_buffering off`. JSON bodies stay on the Express limit; only multipart is unlimited. Production must recreate nginx from the SSL template. Staging also needs the Windows host nginx reloaded. Do not set `Content-Type: multipart/form-data` by hand. - **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`. The rail button is full width. Its mic uses the existing lab voice apply on that case’s one plan (blank plan replaced, existing jobs merged). No draft yet → create the draft, then record. Delete only unstarted lab-origin drafts (`origin === LAB_INTERNAL && !startedAt`). Comments on Cases accept `TAB_CASES_*` (owners are not blocked by Tasks opt-in). diff --git a/.cursor/skills/lab-cases/SKILL.md b/.cursor/skills/lab-cases/SKILL.md index a538a86..93125af 100644 --- a/.cursor/skills/lab-cases/SKILL.md +++ b/.cursor/skills/lab-cases/SKILL.md @@ -47,9 +47,9 @@ 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 on `lg`. Below `lg` the header is one compact stack: name and the desktop QR thumb (`w-24 sm:w-32`, not the 56px compact thumb) on the first row, mobile / from / date on one wrapping line, the progress bar (no separate “tasks completed” sentence), important and billed on one row, and Edit / Outsource / Get PDF sharing one row (`CaseLifecycleButton` `responsiveFill`). External code is under the progress bar in the start column, same width as the bar (no title; placeholder only); billed price is under important on `lg`. Save code on blur → `PATCH /cases/:id/external-code`. Edit, Outsource, Get PDF, and Add files use `CaseLifecycleButton` (primary, no icon; Treatment Lab dispatch / Chart / Add detail width from `lg` up). **Add case** is full width at New treatment size (`px-6 py-3 text-base`) and, when voice is available, splits like Add detail: label starts a blank draft, the mic records against the open draft (or creates one first). Apply still fills that case’s single plan. There is no second mic on the Details tab. There is no Comments button. Opening Messages does not scroll the page. Start and Delete on a draft use the lifecycle 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. Each file being uploaded is its own card with a progress bar (one request per file). Remove one file from that menu after confirm (`DELETE /cases/:id/attachments/:attachmentId`): a clinic file still on a treatment is unlinked only; a lab upload with `detailId` null and no other case link is deleted from the database and disk. Tasks stays view-only. -- **Section badges:** Files counts `ATTACHMENT_ADDED` and Messages counts `LAB_COMMENT` / `CLINIC_COMMENT`, after `LabCaseSectionReadState`, excluding the actor. `GET /cases/:id/section-counts`, `POST /cases/:id/sections/:section/read` when that tab is selected. Opening Details does not clear them. Uploads emit `case-section.changed` to other lab members who can read Cases or Tasks (no inbox card). The existing socket turns that into `tab-badges-changed`. `ATTACHMENT_ADDED` is not a sidebar Cases/Tasks/Treatment count. -- **Attachment uploads:** no size limit in multer, axios, or nginx `/api` (`client_max_body_size 0`, `client_body_timeout 3600s`, `proxy_request_buffering off`). Files stream to disk via `orgDiskStorage` under `uploads/lab-cases/{orgId}` (treatment uploads use `uploads/treatments`). Do not buffer the file in memory and do not set `Content-Type: multipart/form-data` yourself — that drops the boundary. A previous 50MB nginx cap, a 120s axios timeout, and `memoryStorage` are why scans around 80MB failed. +- **Important + external code** (`TAB_CASES_EDIT`): **Mark as important** is centered in the header on `lg`. Below `lg` the header is one compact stack: name and the desktop QR thumb (`w-24 sm:w-32`) on the first row, mobile / from / date on one wrapping line, the progress bar (no separate “tasks completed” sentence), important and billed on one row, and Edit / Outsource / Get PDF sharing one row (`CaseLifecycleButton` `responsiveFill`). External code is under the progress bar in the start column, same width as the bar (no title; placeholder only); billed price is under important on `lg`. Save code on blur → `PATCH /cases/:id/external-code`. Edit, Outsource, Get PDF, and Add files use `CaseLifecycleButton` (primary, no icon; Treatment Lab dispatch / Chart / Add detail width from `lg` up). **Add case** is full width at New treatment size (`px-6 py-3 text-base`) and, when voice is available, splits like Add detail: label starts a blank draft, the mic records against the open draft (or creates one first). Apply still fills that case’s single plan. There is no second mic on the Details tab. There is no Comments button. Opening Messages does not scroll the page. Start and Delete on a draft use the lifecycle 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. Each file being uploaded is its own card with a progress bar (one request per file). Remove one file from that menu after confirm (`DELETE /cases/:id/attachments/:attachmentId`): a clinic file still on a treatment is unlinked only; a lab upload with `detailId` null and no other case link is deleted from the database and disk. Tasks stays view-only. +- **Section badges:** Files counts `ATTACHMENT_ADDED` and Messages counts `LAB_COMMENT` / `CLINIC_COMMENT`, after `LabCaseSectionReadState`, excluding the actor. `GET /cases/:id/section-counts`. `POST /cases/:id/sections/:section/read` only when that tab is open and its count is greater than 0. Opening Details does not clear them. Uploads emit `case-section.changed` to other lab members who can read Cases or Tasks (no inbox card). The existing socket turns that into `tab-badges-changed`. `ATTACHMENT_ADDED` is not a sidebar Cases/Tasks/Treatment count. `LabCaseSectionReadState` has a composite id and stays off the AdminJS allowlist. +- **Attachment uploads:** no size limit in multer, axios, or nginx `/api` (`client_max_body_size 0`, `client_body_timeout 3600s`, `send_timeout 3600s`, `proxy_request_buffering off`, proxy read/send 3600s). The server-level `send_timeout 10` would cut a paused download, so `/api` overrides it. JSON and urlencoded bodies stay on the Express limits; only multipart is unlimited. Files stream to disk via `orgDiskStorage` under `uploads/lab-cases/{orgId}` (treatment uploads use `uploads/treatments`). The attachment row and the case link are one transaction; the disk file is removed only after that transaction commits on delete, and only for a lab-owned upload. A failed activity row does not fail the upload. Do not buffer the file in memory and do not set `Content-Type: multipart/form-data` yourself — that drops the boundary. Releasing this needs `prisma migrate deploy` (the backend container runs it on start; Postgres 15) and a nginx recreate from `nginx.ssl.conf.template`. Staging’s Windows host nginx is a separate paste-and-reload of `windows-edge-http.conf`; Docker alone leaves the 50MB edge. Uploaded bytes live on the backend container disk (`/app/uploads`, no volume) and can fill that disk. - **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`. diff --git a/.cursor/skills/notifications-inbox/SKILL.md b/.cursor/skills/notifications-inbox/SKILL.md index a88b650..647fb13 100644 --- a/.cursor/skills/notifications-inbox/SKILL.md +++ b/.cursor/skills/notifications-inbox/SKILL.md @@ -19,6 +19,8 @@ Do **not** clear tab badges when marking an inbox card read. ## Live cascade (one socket) +`case-section.changed` is the same socket and the same `notifyTabBadgesChanged()` call, for a case file upload. It does **not** write a `UserNotification` row and does not change the bell. + On `notification.created`, [`RealtimeProvider`](frontend/src/lib/realtime/RealtimeProvider.tsx): 1. Updates inbox state (bell list + unread). diff --git a/.cursor/skills/tab-badges/SKILL.md b/.cursor/skills/tab-badges/SKILL.md index 66c0c8e..c657fba 100644 --- a/.cursor/skills/tab-badges/SKILL.md +++ b/.cursor/skills/tab-badges/SKILL.md @@ -16,6 +16,7 @@ Frontend hook: [`frontend/src/lib/hooks/useTabBadgeCounts.ts`](frontend/src/lib/ - **`LabCaseActivity`** — append-only events: `CASE_SENT`, `CLINIC_COMMENT`, `LAB_COMMENT`, `CASE_IMPORTANT`, `CASE_AMENDED` (stub for Step 7), `TASK_COMPLETED` (timeline only), `TASK_ASSIGNED`, `CASE_COMPLETED`, `ATTACHMENT_ADDED` (case Files tab only — **not** a sidebar count) - **`LabCaseUserTabReadState`** — per user/org/tab cursor (`TASKS`) for sidebar badge clearing on tab visit. - **`LabCaseUserReadState`** — per user/org/labCase cursor; drives Cases tab count and `hasUnread` on case list cards +- **`LabCaseSectionReadState`** — per user/org/case/section cursor (`FILES`, `MESSAGES`) for the counts on a case’s own tabs. Composite `@@id`; do not register it in AdminJS. Opening Details does not move these cursors. `ATTACHMENT_ADDED` feeds Files only. ## Tab badge buckets (Option B) @@ -49,7 +50,7 @@ Counts exclude events where `actorUserId === current user`. Clinic `LAB_COMMENT` After mutations, frontend calls `notifyTabBadgesChanged()` (window event). -**Live path:** inbox Socket.IO `notification.created` also dispatches that event so sidebar counts refresh without navigation. **Only currently mounted** feature pages soft-reload list data on the same event (silent; Treatment form/draft untouched). Unmounted tabs do not fetch list data until the user opens them. See `.cursor/skills/notifications-inbox/SKILL.md`. +**Live path:** inbox Socket.IO `notification.created` also dispatches that event so sidebar counts refresh without navigation. Case file uploads emit `case-section.changed` (no `UserNotification` row) and the client turns that into the same event. The open Files or Messages tab marks itself read only when its count is greater than 0. **Only currently mounted** feature pages soft-reload list data on the same event (silent; Treatment form/draft untouched). Unmounted tabs do not fetch list data until the user opens them. See `.cursor/skills/notifications-inbox/SKILL.md`. ## Frontend pattern (same as org connections) diff --git a/.cursor/skills/treatment-workspace/SKILL.md b/.cursor/skills/treatment-workspace/SKILL.md index 5da7560..a65dd54 100644 --- a/.cursor/skills/treatment-workspace/SKILL.md +++ b/.cursor/skills/treatment-workspace/SKILL.md @@ -151,6 +151,8 @@ On today: in-progress slot first, else nearest start time to `now`. Other days: **Today checkbox** (`ScheduleDayPicker`, including `compact` on the Treatment strip and Appointments page headers): unchecked when `selectedDay` is not today (e.g. after loading a historical treatment). Checking Today calls `onSelectDay(today)` which unlocks selection (`selectionLocked = false`) and resets browse/historical context; appointments reload and auto-select nearest to now. +**Day arrows:** `onSelectDay` flushes, switches to live mode, and clears the selected visit before the new day loads. When that day has no appointment and no standalone treatment, the getDraft effect resets the form to one `newDetail()` (no patient, no leftover chart, notes, or lab drafts) unless it is already that blank line. A day that has a visit still auto-selects and loads it. Historical mode is left alone. + ## Lab org search (dispatch) @@ -224,7 +226,7 @@ canEditTreatmentForDay = canEdit && hasLiveContext && !isViewingPastDay && works ### Add / remove details - **Add detail** stays enabled whenever `canEditTreatmentForDay` — even if sibling details are already sent. -- **Remove detail:** trash icon on each **detail chip** in chrome (`TreatmentDetailsEditor` `showChrome`), including the last remaining line. Disabled when `!canEdit`, day/workspace `disabled`, detail sent (`isDetailLocked`), or `uploadBusy`. Confirm via `confirmRemoveDetail`. Drop linked unsent lab drafts with the detail. Empty details persist as `[]` (`SaveTreatmentDraftDto` has no `@ArrayMinSize`; `areDetailsPersistable` is `details.every(isDetailTypeSelected)` so `[]` saves). Unscheduled strip-card trash uses `areUnscheduledDetailsStripDeletable` (blank lines), then `PUT` `{ details: [] }` and `DELETE /treatments/:id` (backend still refuses when any detail row remains — `TREATMENT_HAS_DETAILS`). **Do not** put a delete control in the type/notes fields. +- **Remove detail:** trash icon on each **detail chip** in chrome (`TreatmentDetailsEditor` `showChrome`), including the last remaining line. Disabled when `!canEdit`, day/workspace `disabled`, the line is sent (`isDetailSent`), or `uploadBusy`. The chip’s Sent label uses that same check. `isDetailLocked` is only the later edit lock (a completed lab step). Confirm via `confirmRemoveDetail`. Drop linked unsent lab drafts with the detail. Empty details persist as `[]` (`SaveTreatmentDraftDto` has no `@ArrayMinSize`; `areDetailsPersistable` is `details.every(isDetailTypeSelected)` so `[]` saves). Unscheduled strip-card trash uses `areUnscheduledDetailsStripDeletable` (blank lines), then `PUT` `{ details: [] }` and `DELETE /treatments/:id` (backend still refuses when any detail row remains — `TREATMENT_HAS_DETAILS`). **Do not** put a delete control in the type/notes fields. ### Sent lab shipment fields (vs detail) diff --git a/AGENTS.md b/AGENTS.md index fa9c97a..0b3e7d9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,10 +44,10 @@ frontend/src/ **Treatment tab:** Preview and editable form are **separate** until the user clicks **Load into workspace** on a history item. See `.cursor/skills/treatment-workspace/SKILL.md` before changing that flow. **Treatment edit / details (quick ref):** -- Day/mode gate: editable only for live draft on today/future (`canEditTreatmentForDay`). Past day / historical load → read-only form. Patient search sits in the **page header** (workspace-wide). If the patient has a visit on the day strip, that visit opens; else the latest history plan loads. If neither exists, the editor shows an inline empty state (no dialog) pointing to **New treatment** in the rail — do not auto-create. **New treatment** is at the top of the left rail (selected-patient card below it) and opens a picker: Walk-in first, then a matching card for the current named patient (name + mobile/email), then search. It does not auto-copy the appointment card’s patient. New treatment seeds one blank detail; a persisted empty plan loads as `[]` until Add. +- Day/mode gate: editable only for live draft on today/future (`canEditTreatmentForDay`). Past day / historical load → read-only form. Patient search sits in the **page header** (workspace-wide). If the patient has a visit on the day strip, that visit opens; else the latest history plan loads. Day arrows that land on a day with no visit reset the workspace to one blank detail and no patient, the same as opening Treatment with nothing selected. A day that has a visit still opens it. If neither exists, the editor shows an inline empty state (no dialog) pointing to **New treatment** in the rail — do not auto-create. **New treatment** is at the top of the left rail (selected-patient card below it) and opens a picker: Walk-in first, then a matching card for the current named patient (name + mobile/email), then search. It does not auto-copy the appointment card’s patient. New treatment seeds one blank detail; a persisted empty plan loads as `[]` until Add. - **Unscheduled strip cards** use the same treatment-type banner as appointments from the **first detail’s type only** (`unscheduledStripColorCode`; live draft for the open card). Empty first line → chip theming even if later lines are typed. Strip trash only when every line is blank (no type/teeth/notes/attachments, including `[]`); typed cards need chip-delete first. Backend `DELETE /treatments/:id` is empty-only (`TREATMENT_HAS_DETAILS`). - A sent line stays editable until any lab task is completed, including a step finished by a further lab. Then the line locks (`TREATMENT_DETAIL_SENT`). **Add detail** still OK same day; **Remove detail** = trash on chip (unsent, including last line; day/edit gates apply). A sent line cannot be removed. Empty details persist as `[]`. -- **Entry:** Type dropdown + compact attachments strip (`TreatmentDetailAttachmentsStrip`) on one row (plus **Lab dispatch** / **Chart** toggle when the type is lab-dependent; dispatch is primary, Chart is outline; **Add detail** uses the same width), then bordered FDI chart (Cases chrome/scale) **or** the lab dispatch panel in that same slot, then full-width auto-growing **Notes**. Prosthesis types are assigned on the chart (teeth, or Upper/Lower arch labels for jaw products — dashed outline + plus). Arch Upper/Lower/Both remaps existing `UA`/`LA` jobs (Both→Upper clears lower). Picker: `4fr` wrapping category grid / `1fr` add-ons with a vertical divider; tiles use `ProsthesisCatalogIcon` (`md` + two-line labels on category/addon; `sm` + centered icon/label on child cards); expanded children use a parent-colored **L** rail sized to the first child card; parent-bar back arrow is black; empty crown slot is plus + dashed “Crown can be added”; filled crown slot stays visible so it can be changed. Screen type names use `prosthesisTypeLabelStyleFromCatalog`. Implant/post & core show a **crown** suggestion slot; a veneer/inlay/onlay/overlay hides it. The empty **Pontic** suggestion appears only beside an immediate crown/indirect neighbor; a filled Pontic stays visible and the category remains available for pontic-first entry. Post & core is disabled after crown or implant; Implant is disabled after post & core; screw-retained does not suggest another crown. Removable on a tooth shows the full-arch notice (partial is tooth-selected; complete/overdenture use arch controls). Prosthesis teeth always have jobs (hydrate/save prune). Lab-rail / Go to dispatch **opens the dispatch view** (`pendingScrollToLabRef`). Detail chips show type + teeth; lab-dependent chips use colored sent/unsent text (sent date on dispatch). Lab dispatch keeps comments. +- **Entry:** Type dropdown + compact attachments strip (`TreatmentDetailAttachmentsStrip`) on one row (plus **Lab dispatch** / **Chart** toggle when the type is lab-dependent; dispatch is primary, Chart is outline; **Add detail** uses the same width), then bordered FDI chart (Cases chrome/scale) **or** the lab dispatch panel in that same slot, then full-width auto-growing **Notes**. Prosthesis types are assigned on the chart (teeth, or Upper/Lower arch labels for jaw products — dashed outline + plus). Arch Upper/Lower/Both remaps existing `UA`/`LA` jobs (Both→Upper clears lower). Picker: `4fr` wrapping category grid / `1fr` add-ons with a vertical divider; tiles use `ProsthesisCatalogIcon` (`md` + two-line labels on category/addon; `sm` + centered icon/label on child cards); expanded children use a parent-colored **L** rail sized to the first child card; parent-bar back arrow is black; empty crown slot is plus + dashed “Crown can be added”; filled crown slot stays visible so it can be changed. Screen type names use `prosthesisTypeLabelStyleFromCatalog`. Implant/post & core show a **crown** suggestion slot; a veneer/inlay/onlay/overlay hides it. The empty **Pontic** suggestion appears only beside an immediate crown/indirect neighbor; a filled Pontic stays visible and the category remains available for pontic-first entry. Post & core is disabled after crown or implant; Implant is disabled after post & core; screw-retained does not suggest another crown. Removable on a tooth shows the full-arch notice (partial is tooth-selected; complete/overdenture use arch controls). Prosthesis teeth always have jobs (hydrate/save prune). Lab-rail / Go to dispatch **opens the dispatch view** (`pendingScrollToLabRef`). Detail chips show type + teeth; lab-dependent chips use colored sent/unsent text. Sent follows the linked lab case `sentAt` (or the detail’s own `sentAt`); editing stays open until a lab step is completed. The sent date stays on dispatch. Lab dispatch keeps comments. - **Tooth selection:** Hit target is the unrotated cell (`pointerdown` only — do not also bind `click`). Glyph is `pointer-events-none`; nest hover/selected scale inside the rotate wrapper. Neighbor circles connect/disconnect adjacent selected teeth; midline 11–21 / 41–31 is allowed; never keep a 1-tooth connected group. Prosthesis plain click opens the picker; Done stores the jobs copy brush; **Clear this tooth** stores a clear brush. Ctrl/Cmd+click or drag replays either action on one tooth; Shift+click replays it across an inclusive same-arch range as singles. Brushes reset when the active detail/line changes. Pontic is a no-child tile for pontic-first entry. A tooth immediately beside Pontic initially enables Crown, Indirect, and Pontic, allowing Pontic chains; assigning a Crown immediately enables Implant without reopening the picker (Indirect does not). Choosing a new restoration leaf on one connected abutment updates every restoration abutment in that span while preserving each tooth’s implant/post-core jobs. Orphan/mixed Pontics remain drafts with amber warning but block Send/Start (`PONTIC_BRIDGE_INVALID`). Helpers live in `prosthesisTree.ts`. Same-type teeth in one detail are one display job; stacked types remain distinct. A connected crown/indirect + Pontic span uses the abutment leaf’s steps and renders `13 · Pontic - 14 · PFZ Crown`; Pontic adds none. `UA`/`LA` are arch jobs; partial denture is one tooth-selected job across all selected FDI teeth. - **Lab dispatch layout:** due date beside title (`justify-between`, logical start/end for RTL); job rows from `LabCaseToothJobsList` → `ProsthesisJobLineLabel` (same-type teeth in one detail share a row; Connected badge only for a real bridge). Sent cases: dest/jobs share a row with the Cases **QR** thumb; tracker + comments are full width below. - **Schedule date:** Treatment strip and Appointments page headers use `ScheduleDayPicker` `compact` (date centered in a 3-col header; no “Schedule date” label; Today on the navigator). @@ -72,7 +72,7 @@ frontend/src/ **Lab Tasks tab:** Newest case first (`listedAt`); grouping only for date sort; filters include completed step, origin, due date, assignment, and prosthesis. New tasks are plan-scoped: one scan → prosthesis sections → optional Model design/creation (when any type has `requiresModelSteps`) → packing/shipping. `lineCount` stays 1. `__line__` tasks are independently completable and non-outsourceable; historical `__case__` scan keeps whole-case fan-out. Same-type exclusive steps coalesce across matching teeth; duplicate non-model steps for stacked types become `typeA+typeB` sections. Pontics fold into connected crown/indirect sections. Task identity includes source, first tooth, section type, and workflow code because one section may produce different tooth sets across steps. Job titles use `ProsthesisJobLineLabel`; task assignment is in Cases; only assignee/unassigned pool can update status in Tasks. `CASE_COMPLETED` drives inbox/tab badges only after all case tasks finish. See `.cursor/skills/lab-tasks/SKILL.md`. -**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **From clinic** / **Generated** / **From lab** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces order number. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`. +**Lab Cases tab:** Filter by **prosthesis type** (not treatment type); auto-select newest case on open; list **10 per page**; left rail list fills column height (`flex-1 overflow-y-auto`). Unstarted lab-origin **drafts** sit in a collapsed expandable rail section (opens on click or **Add case**); received + started cases list below, newest first by send or start time (`listedAt`, same key as Tasks). List cards use `LabCaseProsthesisGroupsList` (colored type + teeth, shared with Treatment rail) plus **From clinic** / **Generated** / **From lab** origin badges. Job titles use `ProsthesisJobLineLabel` the same as Treatment/Tasks (`13 · Pontic - 14 · PFZ Crown`; no category; indirect keeps Inlay · Layered ceramic). Deep link: `?caseId=`, `?clinicOrganizationId=`. **Share link:** QR + URL on sent cases **and** started lab-origin cases (attachment left, QR right); opens `/lab-case/[token]` focus page. **Case Sheet PDF:** same portrait/landscape layout, one A4 page (`jspdf`/`html2canvas`, scaled to fit); realistic FDI chart; hex-only print layout; share QR stays in the flex header; optional `externalCode` replaces order number. The page stays LTR; on Persian sheets the org name is shrink-wrapped (RTL only when the name itself is Arabic script) and labels use `0px` letter-spacing. Lab-origin Start has no clinic send and notifies the linked org once (`PARTNER_CASE_CREATED`, share link); generated-case comments have no visibility toggle. A lab-to-lab case uses the eye button so the sending lab can see that comment. Comments use Cases **or** Tasks permission. Unstarted generated drafts can be deleted (`DELETE /cases/:id`). **Edit** (`POST /cases/:id/stop`) returns a started generated case to that drafts rail: completed steps and the previous prosthesis plan stay as history, in-progress steps are dropped, and the case can be edited and started again. Open outsources with no finished step are cancelled; a finished outsourced step blocks Edit. **Outsource** gives selected in-progress prosthesis steps to one linked lab as a child case. Child `sourceKey` stays the child case id unless two selected steps share tooth, type, and workflow (`childId:parentSourceKey`). The child shows only that sending lab (no original clinic or dentist). Those steps leave Tasks until that lab completes them, and only the sending lab sees that direct handoff. The sender chart stays the full plan; the receiver chart is the selected jobs plus pontics on that bridge. **Live:** inbox Socket.IO → `notifyTabBadgesChanged()` soft-refreshes list + selected detail (no remount). A file upload emits `case-section.changed` on that socket (no inbox card) so Files and Messages unread counts refresh the same way. **Add case** is a full-width split button with the lab mic. One file can be removed from its card menu. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`. **Lab case share link (quick ref):** - Token on first ship **or** lab-origin Start → `/{locale}/lab-case/{token}` after login. Editing a generated case keeps that token. The page reads the current round and the live patient/clinic snapshots. Cases, Treatment lab dispatch, and the Case Sheet QR all use this URL. diff --git a/backend/src/modules/cases/cases.service.ts b/backend/src/modules/cases/cases.service.ts index d698d1b..cfb4db5 100644 --- a/backend/src/modules/cases/cases.service.ts +++ b/backend/src/modules/cases/cases.service.ts @@ -1,11 +1,17 @@ -import { - HttpStatus, - Injectable, -} from '@nestjs/common'; +import { HttpStatus, Injectable, Logger } from '@nestjs/common'; import { AppException, ErrorCode } from '../../common/errors'; import { createReadStream, existsSync, unlinkSync } from 'fs'; import { join, resolve, sep } from 'path'; -import { CatalogEntityKind, LabCaseActivityType, LabCaseOrigin, LabCaseSection, LabTaskStatus, LinkStatus, Prisma, UserNotificationType } from '@prisma/client'; +import { + CatalogEntityKind, + LabCaseActivityType, + LabCaseOrigin, + LabCaseSection, + LabTaskStatus, + LinkStatus, + Prisma, + UserNotificationType, +} from '@prisma/client'; import { PrismaService } from '../../../prisma/prisma.service'; import { normalizeMobile } from '../../common/phone'; import { @@ -146,6 +152,7 @@ type LabCaseTaskWithRelations = Prisma.LabCaseTaskGetPayload<{ @Injectable() export class CasesService { + private readonly logger = new Logger(CasesService.name); private readonly uploadRoot = join(process.cwd(), 'uploads', 'lab-cases'); constructor( @@ -1031,16 +1038,7 @@ export class CasesService { actorUserId: string, ) { await this.assertCanEditCases(actorUserId, labOrganizationId); - const existing = await this.prisma.labCase.findFirst({ - where: { - id: labCaseId, - ...this.visibleToLabWhere(labOrganizationId), - }, - select: { id: true }, - }); - if (!existing) { - throw new AppException(ErrorCode.CASE_NOT_FOUND, HttpStatus.NOT_FOUND); - } + await this.requireVisibleCase(labCaseId, labOrganizationId); if (!files?.length) { throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST); } @@ -1052,52 +1050,68 @@ export class CasesService { sizeBytes: number; }[] = []; - for (const file of files) { - const storagePath = file.path; - if (!storagePath) { - throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST); - } + try { + for (const file of files) { + const storagePath = file.path; + if (!storagePath) { + throw new AppException(ErrorCode.TREATMENT_FILE_REQUIRED, HttpStatus.BAD_REQUEST); + } - let attachmentId = ''; - try { - const attachment = await this.prisma.treatmentDetailAttachment.create({ - data: { - detailClientKey: null, - fileName: file.originalname, - mimeType: file.mimetype || 'application/octet-stream', - sizeBytes: file.size, - storagePath, - }, - }); - await this.prisma.labCaseAttachment.create({ - data: { labCaseId, attachmentId: attachment.id }, - }); - attachmentId = attachment.id; - created.push({ - id: attachment.id, - fileName: attachment.fileName, - mimeType: attachment.mimeType, - sizeBytes: attachment.sizeBytes, - }); - } catch (error) { - this.removeStoredFiles([storagePath]); - throw error; + let attachmentId = ''; + try { + const attachment = await this.prisma.$transaction(async (tx) => { + const row = await tx.treatmentDetailAttachment.create({ + data: { + detailClientKey: null, + fileName: file.originalname, + mimeType: file.mimetype || 'application/octet-stream', + sizeBytes: file.size, + storagePath, + }, + }); + await tx.labCaseAttachment.create({ + data: { labCaseId, attachmentId: row.id }, + }); + return row; + }); + attachmentId = attachment.id; + created.push({ + id: attachment.id, + fileName: attachment.fileName, + mimeType: attachment.mimeType, + sizeBytes: attachment.sizeBytes, + }); + } catch (error) { + this.removeStoredFiles([storagePath]); + throw error; + } + + // The file is already stored. A badge-row failure must not make the client retry and upload it again. + try { + await this.labCaseActivity.record({ + labCaseId, + type: LabCaseActivityType.ATTACHMENT_ADDED, + actorUserId, + payload: { attachmentId }, + }); + } catch (error) { + this.logger.error( + `Failed to record ATTACHMENT_ADDED for case ${labCaseId}`, + error instanceof Error ? error.stack : undefined, + ); + } + } + } finally { + if (created.length > 0) { + void this.userNotifications.emitCaseSectionChanged({ + organizationId: labOrganizationId, + actorUserId, + labCaseId, + requiredPermissions: ['TAB_CASES_READ', 'TAB_TASKS_READ'], + }); } - await this.labCaseActivity.record({ - labCaseId, - type: LabCaseActivityType.ATTACHMENT_ADDED, - actorUserId, - payload: { attachmentId }, - }); } - void this.userNotifications.emitCaseSectionChanged({ - organizationId: labOrganizationId, - actorUserId, - labCaseId, - requiredPermissions: ['TAB_CASES_READ', 'TAB_TASKS_READ'], - }); - return { success: true, data: created }; } @@ -1108,16 +1122,7 @@ export class CasesService { actorUserId: string, ) { await this.assertCanEditCases(actorUserId, labOrganizationId); - const existing = await this.prisma.labCase.findFirst({ - where: { - id: labCaseId, - ...this.visibleToLabWhere(labOrganizationId), - }, - select: { id: true }, - }); - if (!existing) { - throw new AppException(ErrorCode.CASE_NOT_FOUND, HttpStatus.NOT_FOUND); - } + await this.requireVisibleCase(labCaseId, labOrganizationId); const link = await this.prisma.labCaseAttachment.findUnique({ where: { labCaseId_attachmentId: { labCaseId, attachmentId } }, @@ -1130,24 +1135,23 @@ export class CasesService { } const file = link.attachment; - await this.prisma.labCaseAttachment.delete({ - where: { labCaseId_attachmentId: { labCaseId, attachmentId } }, + const deleteDisk = await this.prisma.$transaction(async (tx) => { + await tx.labCaseAttachment.delete({ + where: { labCaseId_attachmentId: { labCaseId, attachmentId } }, + }); + + // A clinic file that still belongs to a treatment is unlinked from this case only. + if (file.detailId != null) return false; + + const stillLinked = await tx.labCaseAttachment.count({ + where: { attachmentId }, + }); + if (stillLinked > 0) return false; + + await tx.treatmentDetailAttachment.delete({ where: { id: attachmentId } }); + return this.isLabOwnedUpload(file.storagePath, labOrganizationId); }); - - // A clinic file that still belongs to a treatment is unlinked from this case only. - if (file.detailId != null) { - return { success: true as const }; - } - - const stillLinked = await this.prisma.labCaseAttachment.count({ - where: { attachmentId }, - }); - if (stillLinked > 0) { - return { success: true as const }; - } - - await this.prisma.treatmentDetailAttachment.delete({ where: { id: attachmentId } }); - if (this.isLabOwnedUpload(file.storagePath, labOrganizationId)) { + if (deleteDisk) { this.removeStoredFiles([file.storagePath]); } return { success: true as const }; diff --git a/backend/src/modules/notifications/user-notification.service.ts b/backend/src/modules/notifications/user-notification.service.ts index 771889b..4ab0904 100644 --- a/backend/src/modules/notifications/user-notification.service.ts +++ b/backend/src/modules/notifications/user-notification.service.ts @@ -20,14 +20,9 @@ export type UserNotificationDto = { actorUserId: string | null; }; -type FanoutInput = { +type RecipientQuery = { organizationId: string; - type: UserNotificationType; - href: string; actorUserId?: string | null; - payload?: Record | null; - /** Explicit recipient user ids (e.g. task assignee). Skips permission fan-out. */ - recipientUserIds?: string[]; /** Required tab permission when resolving org members. */ requiredPermission?: string; /** Any-of tab permissions (OR) when resolving org members. */ @@ -36,6 +31,14 @@ type FanoutInput = { labCaseIdForProviderScope?: string; }; +type FanoutInput = RecipientQuery & { + type: UserNotificationType; + href: string; + payload?: Record | null; + /** Explicit recipient user ids (e.g. task assignee). Skips permission fan-out. */ + recipientUserIds?: string[]; +}; + @Injectable() export class UserNotificationService { constructor( @@ -205,8 +208,6 @@ export class UserNotificationService { const recipientIds = await this.resolveRecipients({ organizationId: input.organizationId, actorUserId: input.actorUserId, - type: UserNotificationType.LAB_COMMENT, - href: `/cases?caseId=${encodeURIComponent(input.labCaseId)}`, requiredPermissions: input.requiredPermissions, }); for (const userId of recipientIds) { @@ -346,7 +347,7 @@ export class UserNotificationService { }; } - private async resolveRecipients(input: FanoutInput): Promise { + private async resolveRecipients(input: RecipientQuery): Promise { const requiredPermissions = [ ...(input.requiredPermissions ?? []), ...(input.requiredPermission ? [input.requiredPermission] : []), diff --git a/frontend/src/components/ui/lab/CaseCreatePanel.tsx b/frontend/src/components/ui/lab/CaseCreatePanel.tsx index 3f38f85..d498ab0 100644 --- a/frontend/src/components/ui/lab/CaseCreatePanel.tsx +++ b/frontend/src/components/ui/lab/CaseCreatePanel.tsx @@ -196,6 +196,8 @@ export function CaseCreatePanel({ const cancelScheduledPersistRef = useRef<() => void>(() => {}); const attachmentIdsRef = useRef(labCase.attachments.map((file) => file.id)); attachmentIdsRef.current = plan.attachments.map((file) => file.id); + const filesListEpoch = useRef(0); + const filesListRequest = useRef(0); useEffect(() => { if (hydratedIdRef.current === labCase.id) return; @@ -327,8 +329,16 @@ export function CaseCreatePanel({ useEffect(() => { if (section !== 'files') return; const onChanged = () => { + const epoch = filesListEpoch.current; + const request = ++filesListRequest.current; void casesApi.listAttachments(labCase.id).then((response) => { - setPlan((current) => ({ ...current, attachments: response.data })); + if (epoch !== filesListEpoch.current || request !== filesListRequest.current) return; + setPlan((current) => { + const currentIds = new Set(current.attachments.map((file) => file.id)); + const extra = response.data.filter((file) => !currentIds.has(file.id)); + if (extra.length === 0) return current; + return { ...current, attachments: [...current.attachments, ...extra] }; + }); }).catch(() => undefined); }; window.addEventListener(tabBadgesChangedEventName(), onChanged); @@ -344,6 +354,7 @@ export function CaseCreatePanel({ tone: 'danger', }); if (!accepted) return; + filesListEpoch.current += 1; cancelScheduledPersistRef.current(); if (persistInFlightRef.current) { await persistInFlightRef.current.catch(() => null); @@ -354,6 +365,7 @@ export function CaseCreatePanel({ ...line, attachments: line.attachments.filter((file) => file.id !== attachmentId), })); + filesListEpoch.current += 1; } catch (error: unknown) { onError(getUserFacingError(error, tErrors, t('errorSaveCase'))); } @@ -449,6 +461,7 @@ export function CaseCreatePanel({ async function handleUploadFile(file: File, onProgress: (percent: number) => void) { if (!canEdit) return; + filesListEpoch.current += 1; uploadLockRef.current = true; cancelScheduledPersistRef.current(); setUploadBusy(true); @@ -464,6 +477,7 @@ export function CaseCreatePanel({ ...line, attachments: [...line.attachments, ...response.data], })); + filesListEpoch.current += 1; } catch (error: unknown) { onError(getUserFacingError(error, tErrors, t('errorSaveCase'))); throw error; diff --git a/frontend/src/components/ui/lab/CaseDetailPanel.tsx b/frontend/src/components/ui/lab/CaseDetailPanel.tsx index 9153368..80e22f5 100644 --- a/frontend/src/components/ui/lab/CaseDetailPanel.tsx +++ b/frontend/src/components/ui/lab/CaseDetailPanel.tsx @@ -329,7 +329,7 @@ export function CaseDetailPanel({ const refreshed = await casesApi.getOne(labCase.id); onCaseUpdated?.(refreshed.data); } catch (error: unknown) { - toast.showError(t('errorSaveCase')); + toast.showError(getUserFacingError(error, tErrors, t('errorSaveCase'))); throw error; } } diff --git a/frontend/src/components/ui/treatment/TreatmentDetailsEditor.tsx b/frontend/src/components/ui/treatment/TreatmentDetailsEditor.tsx index e91653c..c113b49 100644 --- a/frontend/src/components/ui/treatment/TreatmentDetailsEditor.tsx +++ b/frontend/src/components/ui/treatment/TreatmentDetailsEditor.tsx @@ -234,11 +234,10 @@ export function TreatmentDetailsEditor({
{details.map((d, idx) => { - const detailLocked = isDetailLocked(d); const detailSent = isDetailSent(d); const isActive = d.clientId === activeDetailId; const showRemoveAction = Boolean(onRemoveDetail); - const removeDisabled = !canEdit || disabled || Boolean(d.sentAt) || detailLocked || uploadBusy; + const removeDisabled = !canEdit || disabled || detailSent || uploadBusy; const chipLabel = formatDetailChipLabel( d, treatmentCatalog, diff --git a/frontend/src/components/ui/treatment/TreatmentWorkspace.tsx b/frontend/src/components/ui/treatment/TreatmentWorkspace.tsx index 898b2df..262584b 100644 --- a/frontend/src/components/ui/treatment/TreatmentWorkspace.tsx +++ b/frontend/src/components/ui/treatment/TreatmentWorkspace.tsx @@ -1363,6 +1363,7 @@ export function TreatmentWorkspace({ // A day with no visit must match a fresh open of the tab: one blank line, // no patient, no leftover plan from the day the arrows just left. if (!appointmentId && !treatmentId) { + skipNextGetDraftRef.current = false; const current = detailsRef.current; const drafts = labCaseDraftsRef.current; const alreadyBlank = diff --git a/frontend/src/lib/hooks/useCaseSectionCounts.ts b/frontend/src/lib/hooks/useCaseSectionCounts.ts index d4c7e3c..c6fd2d6 100644 --- a/frontend/src/lib/hooks/useCaseSectionCounts.ts +++ b/frontend/src/lib/hooks/useCaseSectionCounts.ts @@ -23,7 +23,7 @@ export function useCaseSectionCounts(caseId: string, section: CasePanelSection) const response = await casesApi.sectionCounts(caseId); if (cancelled) return; const next = { ...response.data }; - if (section === 'files' || section === 'messages') { + if ((section === 'files' || section === 'messages') && next[section] > 0) { await casesApi.markSectionRead(caseId, section === 'files' ? 'FILES' : 'MESSAGES'); if (cancelled) return; next[section] = 0; diff --git a/infrastructure/DEPLOY.md b/infrastructure/DEPLOY.md index 00fec58..15e09a9 100644 --- a/infrastructure/DEPLOY.md +++ b/infrastructure/DEPLOY.md @@ -401,6 +401,12 @@ docker compose -f docker-compose.prod.yml --env-file .env up -d Backend runs `prisma migrate deploy` automatically on container start. +### Large attachment uploads + +Case and treatment files have no size cap. Nginx `/api` (`nginx.ssl.conf.template`, rendered on deploy) sets `client_max_body_size 0`, `send_timeout 3600s`, and `proxy_request_buffering off`. `location /` and `/admin` stay at 50MB. JSON bodies stay on the Express limit; only multipart uploads are unlimited. + +A tag deploy that recreates nginx picks this up. Pulling only the backend image leaves the previous 50MB `/api` cap. Uploaded files are written to the backend container disk (`/app/uploads`, no volume). A very large upload can fill that disk, and recreating the backend container removes those files. + --- ## Troubleshooting diff --git a/infrastructure/STAGING-DEPLOY.md b/infrastructure/STAGING-DEPLOY.md index d0642d0..689b4ea 100644 --- a/infrastructure/STAGING-DEPLOY.md +++ b/infrastructure/STAGING-DEPLOY.md @@ -257,6 +257,8 @@ curl.exe http://127.0.0.1/health Replace any **default_server** / leftover `server { listen 80; }` in the host nginx that returns 404, or this file will never win. +Attachment uploads are unlimited only on `location /api` in this host file **and** in the Docker nginx behind it. Reloading Docker without pasting `windows-edge-http.conf` and running `nginx -s reload` leaves the Windows edge at 50MB, so a large scan still fails before it reaches the API. + From another machine (after **router forward TCP 80** → this PC): ```bash diff --git a/infrastructure/nginx/http-only.conf b/infrastructure/nginx/http-only.conf index 90348c3..8929cb9 100644 --- a/infrastructure/nginx/http-only.conf +++ b/infrastructure/nginx/http-only.conf @@ -43,6 +43,7 @@ server { # rejected or dropped when the client pauses. client_max_body_size 0; client_body_timeout 3600s; + send_timeout 3600s; proxy_request_buffering off; proxy_read_timeout 3600s; proxy_send_timeout 3600s; diff --git a/infrastructure/nginx/http-only.dev.conf b/infrastructure/nginx/http-only.dev.conf index a759e64..381ffc3 100644 --- a/infrastructure/nginx/http-only.dev.conf +++ b/infrastructure/nginx/http-only.dev.conf @@ -46,6 +46,7 @@ server { # rejected or dropped when the client pauses. client_max_body_size 0; client_body_timeout 3600s; + send_timeout 3600s; proxy_request_buffering off; proxy_read_timeout 3600s; proxy_send_timeout 3600s; diff --git a/infrastructure/nginx/nginx.conf b/infrastructure/nginx/nginx.conf index 098dceb..5d3c6f5 100644 --- a/infrastructure/nginx/nginx.conf +++ b/infrastructure/nginx/nginx.conf @@ -87,6 +87,7 @@ server { # rejected or dropped when the client pauses. client_max_body_size 0; client_body_timeout 3600s; + send_timeout 3600s; proxy_request_buffering off; proxy_read_timeout 3600s; proxy_send_timeout 3600s; diff --git a/infrastructure/nginx/nginx.ssl.conf.template b/infrastructure/nginx/nginx.ssl.conf.template index 24660d1..e265b3a 100644 --- a/infrastructure/nginx/nginx.ssl.conf.template +++ b/infrastructure/nginx/nginx.ssl.conf.template @@ -81,6 +81,7 @@ server { # rejected or dropped when the client pauses. client_max_body_size 0; client_body_timeout 3600s; + send_timeout 3600s; proxy_request_buffering off; proxy_read_timeout 3600s; proxy_send_timeout 3600s; diff --git a/infrastructure/nginx/windows-edge-http.conf b/infrastructure/nginx/windows-edge-http.conf index 95639f7..926bc68 100644 --- a/infrastructure/nginx/windows-edge-http.conf +++ b/infrastructure/nginx/windows-edge-http.conf @@ -46,6 +46,7 @@ http { location /api { client_max_body_size 0; client_body_timeout 3600s; + send_timeout 3600s; proxy_request_buffering off; proxy_pass http://127.0.0.1:18088; proxy_http_version 1.1; @@ -88,6 +89,7 @@ http { location /api { client_max_body_size 0; client_body_timeout 3600s; + send_timeout 3600s; proxy_request_buffering off; proxy_pass http://127.0.0.1:18088; proxy_http_version 1.1; -- 2.53.0.windows.1