Compare commits
9 Commits
bug/ci-cd
...
feature/se
| Author | SHA1 | Date | |
|---|---|---|---|
| 7390491a8d | |||
| 16689b1d03 | |||
| 6f248b13df | |||
| 385a5c0ff8 | |||
| 24d298bf6e | |||
| 6dce1e1bfb | |||
| 377c752fbb | |||
| 831f0f9f5a | |||
| add2b5a7be |
@@ -43,7 +43,7 @@ QR + URL for **sent** cases and started lab-origin cases; focus page `/lab-case/
|
||||
|
||||
## API errors
|
||||
|
||||
Logical failures: `AppException(ErrorCode.X)` → `errors.X` in en/fa/nl. UI: `getUserFacingError`. Unexpected 500s / client crashes: GlitchTip via Sentry SDKs (`SENTRY_DSN` / `NEXT_PUBLIC_SENTRY_DSN`). Skill: `.cursor/skills/api-errors/SKILL.md`. Appointments/working hours: client IANA `timeZone` (never Node local `getHours()`).
|
||||
Logical failures: `AppException(ErrorCode.X)` → `errors.X` in en/fa/nl. UI: `getUserFacingError`. Unexpected 500s / client crashes: GlitchTip via Sentry SDKs (`SENTRY_DSN` / `NEXT_PUBLIC_SENTRY_DSN`) — one failure, one event, and each 5xx wrapper passes `{ cause }`. Rule: `.cursor/rules/error-tracking.mdc`. Skill: `.cursor/skills/api-errors/SKILL.md`. Appointments/working hours: client IANA `timeZone` (never Node local `getHours()`).
|
||||
|
||||
## Notifications (inbox + live tabs)
|
||||
|
||||
|
||||
@@ -1,20 +1,31 @@
|
||||
---
|
||||
description: GlitchTip error tracking via Sentry SDKs — 500s only, no PHI
|
||||
description: GlitchTip error tracking via Sentry SDKs — one failure one event, cause on each 5xx wrapper, no PHI
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Error tracking (GlitchTip)
|
||||
|
||||
Self-hosted GlitchTip at `https://errors.wixur.ir`. Apps use official Sentry SDKs (`@sentry/nestjs`, `@sentry/nextjs`) pointed at that DSN — not sentry.io.
|
||||
Self-hosted GlitchTip at `https://errors.wixur.ir`. Apps use official Sentry SDKs (`@sentry/nestjs`, `@sentry/nextjs`) pointed at that DSN — not sentry.io. SDK stays on **10.x**: GlitchTip ignores `span` items, and SDK 11 streams spans by default.
|
||||
|
||||
## What to report
|
||||
|
||||
- Backend: HTTP **500+** in `HttpExceptionFilter` only. Do **not** send `AppException` 4xx.
|
||||
- Frontend: render crashes (`error.tsx` / `global-error.tsx`) and axios **5xx / network** failures only.
|
||||
- No session replay. Scrub cookies, JWT, request bodies, emails.
|
||||
- **One failure, one event.** Backend: HTTP 5xx in `HttpExceptionFilter`. Frontend: only failures that have no backend event — no response (network, timeout), or a 5xx without a backend error body (`reportUnexpectedApiFailure.ts`). The frontend does not report a backend 5xx, a 4xx, or a canceled request.
|
||||
- A 5xx wrapper passes the original error: `new InternalServerErrorException('…', { cause: error })`, `new AppException(code, status, undefined, cause)`. A `catch` lets an `HttpException` pass first.
|
||||
- Work that runs detached from the response uses `reportBackgroundFailure(task, error)` (`common/observability/report-failure.ts`), or `notifyInBackground(...)` for inbox notifications. Never `.catch(() => undefined)` on work that matters. A `catch` that logs and continues uses `reportHandledFailure(operation, error)`.
|
||||
- Frontend: a caught error that is not an `ApiError` is a bug. `getUserFacingError` reports it once per error object. `Button` reports a rejected `onClick`. `error.tsx` / `global-error.tsx` capture only an error without a `digest` (the server already sent that one).
|
||||
- No session replay. No `tracesSampleRate` yet (spans are a later step): errors still share a `trace_id`.
|
||||
|
||||
## Context on each event
|
||||
|
||||
`SentryContextInterceptor` (backend) and `useAuth` (frontend) set `user.id` and `organization_id`; the frontend also sets `organization_type` and `route`. `beforeSend` adds `http_status` and `error_code`, and names an `AppException` by its code.
|
||||
|
||||
## No sensitive data
|
||||
|
||||
`beforeSend` / `beforeBreadcrumb` (`backend/src/common/observability/sentry-options.ts`, `frontend/src/lib/error-tracking/sentrySharedOptions.ts`) remove cookies, JWT, request bodies, query strings, share-link tokens, emails, mobile numbers, and IP addresses. Never log an OTP code, API key, token, or patient data: console output becomes a breadcrumb. Nest `Logger` is **not** connected to Sentry (one log line prints the voice transcript) — keep it that way.
|
||||
|
||||
## Config
|
||||
|
||||
- Backend DSN: `SENTRY_DSN` in `backend.env` / `backend.staging.env` (runtime).
|
||||
- Frontend DSN: `NEXT_PUBLIC_SENTRY_DSN` baked at Docker build (Gitea var `NEXT_PUBLIC_SENTRY_DSN`).
|
||||
- Backend DSN: `SENTRY_DSN` in `backend.env` / `backend.staging.env` (runtime). Release: `SENTRY_RELEASE` = image tag.
|
||||
- Frontend DSN: `NEXT_PUBLIC_SENTRY_DSN` baked at Docker build (Gitea var). Release: `SENTRY_RELEASE` build arg.
|
||||
- Source maps: Gitea secret `SENTRY_AUTH_TOKEN` + vars `SENTRY_ORG`, `SENTRY_PROJECT_BACKEND`, `SENTRY_PROJECT_FRONTEND`. The token needs the scopes `org:read`, `project:read`, `project:releases`. Empty = no upload, and the build continues.
|
||||
- Empty DSN = tracking off (local default).
|
||||
|
||||
@@ -14,7 +14,7 @@ alwaysApply: false
|
||||
- **Comments:** a generated case hides 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. A received case uses the eye for the clinic. A lab-to-lab case uses it for the sending lab; the sender's handoff lists only comments with that control on.
|
||||
- **Outsource** (`POST /cases/:id/outsource`, label `cases.sendCase`): one linked lab, checked in-progress prosthesis-job steps plus `model_design` / `model_create`, one `LAB_OUTSOURCE` child case. The child stores the sending lab as `referringClinicName` and clears dentist and partner clinic. Those parent steps leave Tasks until the child completes them (written back with no actor). Sender detail shows only that direct lab. The sender chart stays the full plan; the child chart is the selected jobs plus pontics on that bridge, or that line’s teeth for a model step (the whole plan for a historical `__case__` model step). Recall before any of those steps is completed. Received child cases have Outsource, not Start, Delete, or Edit. Scan, packing, and shipping stay on the owning lab. Child `sourceKey` is the child case id. When two selected steps share tooth, prosthesis type, and workflow step, `outsourceChildSourceKey` uses `childId:parentSourceKey` so the current-round unique index accepts both. `dedupeToothJobs` includes `sourceKey`.
|
||||
- **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`.
|
||||
- **Send to Exocad:** writes an official `.dentalProject` XML into DentalDB’s Project Auto-Import folder (`showDirectoryPicker`, Chrome/Edge only). Does not open or mutate DentalDB SQLite. Builder: `components/lab/exocad/exocadDentalProject.ts`. Folder session: `ExocadExportFolderProvider` (changeable Auto-Import folder). Active indirect leaves and implant stacks are mapped; empty plans refuse export; Coping pontics use `ReducedPontic`, full-contour use `AnatomicPontic`; shade is `VCL` or bleach `V3DM`. No antagonists or scan files in this phase. `externalCode` stays manual. See `.cursor/skills/lab-cases/SKILL.md`.
|
||||
- **Send to Exocad:** writes an official `.dentalProject` XML into DentalDB’s Project Auto-Import folder (`showDirectoryPicker`, Chrome/Edge only). Does not open or mutate DentalDB SQLite. Builder: `components/lab/exocad/exocadDentalProject.ts` (PDF Tables 2–4 are the value source of truth). Folder session: `ExocadExportFolderProvider` (changeable Auto-Import folder). Monolithic = `AnatomicCrown`/`ZI`; prefab/Ti-base/multi-unit = `CustomAbutment`/`TI`; empty plans refuse export; Coping pontics use `ReducedPontic`, full-contour use `AnatomicPontic`; shade is `VCL` or bleach `V3DM`. No antagonists or scan files in this phase. `externalCode` stays manual. See `.cursor/skills/lab-cases/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. 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, 56px line box so html2canvas does not clip the 28px glyphs), Nudentic lockup aligned with that text, share QR at 88px inside a 96px frame with `fill` off (a stretched SVG is dropped by html2canvas; not a table cell). Print root top padding is 16px portrait / 24px landscape so the QR is not clipped; `html2canvas` `scrollY` is 0. 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). Section rules keep a 12px gap and 8px padding so the line clears the values; `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 printed order number and the `case-sheet-{orderNumber}.pdf` filename.
|
||||
- **Detail chrome:** The header follows the detail panel width (`@container`, not the viewport): two columns (info start, actions end) from `@2xl`, otherwise one stack with the buttons under the info: name and the same QR thumb (`w-24 sm:w-32`) on the first row, mobile/from/date on one wrapping line, then progress bar, external code, **Mark as important**, and billed, stacked and left aligned. The destination lab with `TAB_BILLING_EDIT` edits that fee (`PUT /billing/cases/:id/amount`) and the open case updates immediately; anyone else sees the stored fee, or the calculated quote when no fee is stored. Edit / Outsource / Send to Exocad / Get PDF are one equal-width grid (`responsiveFill`, truncating caption): 2 columns when narrow, one column per button from `@xl`, 2 columns in the `@2xl` end column with the QR below. Get PDF is a primary `CaseLifecycleButton` with no icon. Add files uses that button at the treatment action width. **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}”.
|
||||
|
||||
@@ -33,6 +33,17 @@ catch (err: unknown) {
|
||||
|
||||
3. Do not use `err.message` or `(err as Error).message` for user display.
|
||||
|
||||
## Unexpected errors (5xx)
|
||||
|
||||
Rule: `.cursor/rules/error-tracking.mdc`.
|
||||
|
||||
1. Let an `HttpException` pass first: `if (error instanceof HttpException) { throw error; }`
|
||||
2. Wrap with the cause: `new InternalServerErrorException('What failed', { cause: error })` or `new AppException(code, status, undefined, error)`. A wrapper without the cause hides the real error from the tracker.
|
||||
3. Give each wrapper its own message. Two causes with one message make one issue in GlitchTip.
|
||||
4. Work that is not awaited: `reportBackgroundFailure('task-name', error)` — never an unhandled rejection or `.catch(() => undefined)`.
|
||||
5. A `catch` that logs and continues: `reportHandledFailure('operation', error)`.
|
||||
6. Log with `this.logger`, not `console`. Never log a secret or patient data.
|
||||
|
||||
## Axios shape
|
||||
|
||||
Parsed in `lib/api/client` — expects `{ success: false, error: { code, details? } }`.
|
||||
|
||||
@@ -64,7 +64,7 @@ Writes an official `.dentalProject` XML into DentalDB’s Project Auto-Import fo
|
||||
- `ExocadExportFolderProvider` remembers the Auto-Import directory handle (IndexedDB). The next export reopens that folder when permission remains and skips Browse. A missing or denied folder shows the folder picker again.
|
||||
- The connect dialog asks for the DentalDB Project Auto-Import folder and notes that this release exports case data only (scan companion files are still placed by the user when needed).
|
||||
- Builder: `frontend/src/components/lab/exocad/exocadDentalProject.ts`. Root is `<Treatment UseRecipientMaterialConfiguration="True">`. `ProjectGUID` is the Dyolink case id. `PracticeName` is the clinic name (no `PracticeId`). Patient family/given names are mandatory (`PatientName` / `PatientFirstName`); a one-word name is refused. `Notes` are the case comment bodies, or the detail comment when the thread is empty. File name is `{date}-{shortCaseId}.dentalProject`.
|
||||
- Tooth mapping (XML `ReconstructionType` / `Material`): Monolithic Zirconia and PFZ = `Coping`/`ZI`; PFM = `Coping`/`NP`; Full Metal = `AnatomicCrown`/`NP`; PMMA = `AnatomicCrown`/`PMMA`; Glass Ceramic = `AnatomicCrown`/`GCER`; Pressed Ceramic = `AnatomicCrown`/`LS2`; PEEK = `AnatomicCrown`/`PEEK`; Temporary Resin = `ProvisionalCrown`/`TEMP`. Active indirect: `veneer_*` → `Veneer`/`LS2`; `*_full_contour` inlay/onlay/overlay → `AnatomicInlay`/`LS2`; `*_layered` inlay/onlay/overlay → `OffsetInlay`/`LS2`. Legacy veneer/overlay leaves keep their old pairs; overlays never use OverlayCrown. Pontic follows the abutment family: `Coping` → `ReducedPontic`, full-contour → `AnatomicPontic`, with the abutment material. `customized_abutment` → `CustomAbutment`/`TI`; `zirconia_abutment` → `CustomAbutment`/`ZI`; `screw_retained` → `WithoutAbutment`. Unmapped stacks (`ti_base_abutment`, prefab/multi-unit, post & core) are skipped and never force `ImplantType None`. A plain Coping with no implant stack sets `ImplantType` `None`. Bridge groups set `MesialConnector` toward the mesial neighbor in the same `selectionGroupId`. Empty exports are refused (`NOTHING_TO_EXPORT`). Antagonists and scan files are not exported in this phase. Case shade → `ToothShade` as `VCL:<code>` or bleach `V3DM:0M*`.
|
||||
- Tooth mapping follows the official `.dentalProject` Tables 2–4 in `docs/exocad_Specification_Document_dentalProject_Format_to_Be_Written.pdf` (XML `ReconstructionType` / `Material` / `ImplantType`). Full-contour Monolithic Zirconia = `AnatomicCrown`/`ZI`; cutback PFZ = `Coping`/`ZI`; PFM = `Coping`/`NP`; Full Metal = `AnatomicCrown`/`NP`; PMMA = `AnatomicCrown`/`PMMA`; Glass Ceramic = `AnatomicCrown`/`GCER`; Pressed Ceramic = `AnatomicCrown`/`LS2`; PEEK = `AnatomicCrown`/`PEEK`; Temporary Resin = `ProvisionalCrown`/`TEMP`. Active indirect: `veneer_*` → `Veneer`/`LS2`; `*_full_contour` inlay/onlay/overlay → `AnatomicInlay`/`LS2`; `*_layered` inlay/onlay/overlay → `OffsetInlay`/`LS2`. Legacy veneer/overlay leaves keep their old pairs; overlays never use OverlayCrown. Pontic follows the abutment family: `Coping` → `ReducedPontic`, full-contour → `AnatomicPontic`, with the abutment material. Implant stacks (Table 4 only has `None` / `CustomAbutment` / `WithoutAbutment`; DentalDB “On stock abutment” is not writable): `customized_abutment` → `CustomAbutment`/`TI`; `zirconia_abutment` → `CustomAbutment`/`ZI`; prefab / Ti-base / multi-unit → `CustomAbutment`/`TI`; `screw_retained` → `WithoutAbutment`. Post & core stacks are skipped and never force `ImplantType None`. A plain implant-capable restoration with no stack sets `ImplantType` `None`. Bridge groups set `MesialConnector` toward the mesial neighbor in the same `selectionGroupId`. Empty exports are refused (`NOTHING_TO_EXPORT`). Antagonists and scan files are not exported in this phase. Case shade → `ToothShade` as `VCL:<code>` or bleach `V3DM:0M*`.
|
||||
- Auto-Import folder can be changed from the case header; success toast names the folder when known.
|
||||
- `externalCode` stays manual-only — export does not auto-fill it.
|
||||
- There is no Local database tab.
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
# CLONE_HOST git clone, e.g. 127.0.0.1:3000
|
||||
# COM_PUBLIC_BASE_URL https://nudentic.com (required; no trailing slash)
|
||||
# NEXT_PUBLIC_SENTRY_DSN GlitchTip frontend project DSN
|
||||
# SENTRY_ORG, SENTRY_PROJECT_BACKEND, SENTRY_PROJECT_FRONTEND
|
||||
# GlitchTip slugs for the source map upload (empty = no upload).
|
||||
# Secret SENTRY_AUTH_TOKEN: GlitchTip auth token for that upload.
|
||||
# NODE_IMAGE_SOURCE extra base-image ref(s) for seed/resolve
|
||||
# NPM_REGISTRY default http://host.docker.internal:4873
|
||||
# PROD_REGISTRY_HOST Linux pull host, e.g. wixur.ir:3000
|
||||
@@ -128,6 +131,10 @@ jobs:
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
|
||||
- name: Build and push backend (:tag-com only)
|
||||
env:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
|
||||
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_BACKEND }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = $env:COM_IMAGE_TAG
|
||||
@@ -151,6 +158,9 @@ jobs:
|
||||
--add-host "host.docker.internal:host-gateway" `
|
||||
--build-arg "NODE_IMAGE=$nodeImage" `
|
||||
--build-arg "NPM_REGISTRY=$npmReg" `
|
||||
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
|
||||
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
|
||||
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
|
||||
-t "$prefix/dyolink-backend:$tag" ./backend
|
||||
if ($LASTEXITCODE -eq 0) { $ok = $true; break }
|
||||
if ($i -lt 3) { Start-Sleep -Seconds (20 * $i) }
|
||||
@@ -163,6 +173,9 @@ jobs:
|
||||
env:
|
||||
COM_PUBLIC_BASE_URL: ${{ vars.COM_PUBLIC_BASE_URL }}
|
||||
NEXT_PUBLIC_SENTRY_DSN: ${{ vars.NEXT_PUBLIC_SENTRY_DSN }}
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
|
||||
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_FRONTEND }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = $env:COM_IMAGE_TAG
|
||||
@@ -194,6 +207,10 @@ jobs:
|
||||
--build-arg "NEXT_PUBLIC_APP_NAME=Dyolink" `
|
||||
--build-arg "NEXT_PUBLIC_SENTRY_DSN=$env:NEXT_PUBLIC_SENTRY_DSN" `
|
||||
--build-arg "NEXT_PUBLIC_SENTRY_ENVIRONMENT=production" `
|
||||
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
|
||||
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
|
||||
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
|
||||
--build-arg "SENTRY_RELEASE=$tag" `
|
||||
--build-arg "NODE_IMAGE=$nodeImage" `
|
||||
--build-arg "NPM_REGISTRY=$npmReg" `
|
||||
-t "$prefix/dyolink-frontend:$tag" `
|
||||
|
||||
@@ -13,12 +13,15 @@
|
||||
# CLONE_HOST git clone, e.g. 127.0.0.1:3000
|
||||
# PROD_PUBLIC_BASE_URL https://nudentic.ir (no trailing slash)
|
||||
# NEXT_PUBLIC_SENTRY_DSN GlitchTip frontend project DSN
|
||||
# SENTRY_ORG, SENTRY_PROJECT_BACKEND, SENTRY_PROJECT_FRONTEND
|
||||
# GlitchTip slugs for the source map upload (empty = no upload)
|
||||
# NODE_IMAGE_SOURCE extra base-image ref(s) for seed/resolve
|
||||
# NPM_REGISTRY default http://host.docker.internal:4873 (Verdaccio on Windows)
|
||||
# PROD_REGISTRY_HOST Linux pull host, e.g. wixur.ir:3000 (HTTP; insecure-registries on the VPS)
|
||||
# PROD_INFRA_DIR /opt/dyolink/infrastructure
|
||||
#
|
||||
# Secrets (in addition to REGISTRY_USERNAME / REGISTRY_PASSWORD):
|
||||
# SENTRY_AUTH_TOKEN GlitchTip auth token for the source map upload (optional)
|
||||
# PROD_SSH_HOST Linux public IP or hostname
|
||||
# PROD_SSH_USER e.g. dyolink
|
||||
# PROD_SSH_KEY OpenSSH private key (full PEM)
|
||||
@@ -151,6 +154,10 @@ jobs:
|
||||
|
||||
- name: Build and push backend (tag only, not :latest)
|
||||
if: steps.gate.outputs.skip != 'true'
|
||||
env:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
|
||||
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_BACKEND }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$dispatchTag = '${{ github.event.inputs.tag }}'.Trim()
|
||||
@@ -175,6 +182,9 @@ jobs:
|
||||
--add-host "host.docker.internal:host-gateway" `
|
||||
--build-arg "NODE_IMAGE=$nodeImage" `
|
||||
--build-arg "NPM_REGISTRY=$npmReg" `
|
||||
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
|
||||
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
|
||||
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
|
||||
-t "$prefix/dyolink-backend:$tag" ./backend
|
||||
if ($LASTEXITCODE -eq 0) { $ok = $true; break }
|
||||
if ($i -lt 3) { Start-Sleep -Seconds (20 * $i) }
|
||||
@@ -188,6 +198,9 @@ jobs:
|
||||
env:
|
||||
PROD_PUBLIC_BASE_URL: ${{ vars.PROD_PUBLIC_BASE_URL }}
|
||||
NEXT_PUBLIC_SENTRY_DSN: ${{ vars.NEXT_PUBLIC_SENTRY_DSN }}
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
|
||||
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_FRONTEND }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$dispatchTag = '${{ github.event.inputs.tag }}'.Trim()
|
||||
@@ -218,6 +231,10 @@ jobs:
|
||||
--build-arg "NEXT_PUBLIC_APP_NAME=Dyolink" `
|
||||
--build-arg "NEXT_PUBLIC_SENTRY_DSN=$env:NEXT_PUBLIC_SENTRY_DSN" `
|
||||
--build-arg "NEXT_PUBLIC_SENTRY_ENVIRONMENT=production" `
|
||||
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
|
||||
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
|
||||
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
|
||||
--build-arg "SENTRY_RELEASE=$tag" `
|
||||
--build-arg "NODE_IMAGE=$nodeImage" `
|
||||
--build-arg "NPM_REGISTRY=$npmReg" `
|
||||
-t "$prefix/dyolink-frontend:$tag" `
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
# REGISTRY_OWNER Gitea user or org that owns the packages
|
||||
# PUBLIC_BASE_URL URL users open in the browser, e.g. http://wixur.ir (no trailing slash, no :8088)
|
||||
# NEXT_PUBLIC_SENTRY_DSN GlitchTip frontend project DSN (https://…@errors.wixur.ir/…)
|
||||
# SENTRY_ORG, SENTRY_PROJECT_BACKEND, SENTRY_PROJECT_FRONTEND
|
||||
# GlitchTip slugs for the source map upload (empty = no upload).
|
||||
# Secret SENTRY_AUTH_TOKEN: GlitchTip auth token for that upload.
|
||||
# DEPLOY_SECRETS_DIR absolute path on runner, e.g. C:/dyolink/secrets
|
||||
#
|
||||
# Optional:
|
||||
@@ -121,6 +124,10 @@ jobs:
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
|
||||
- name: Build and push backend
|
||||
env:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
|
||||
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_BACKEND }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = "${{ github.sha }}".Substring(0, 7)
|
||||
@@ -148,6 +155,9 @@ jobs:
|
||||
--add-host "host.docker.internal:host-gateway" `
|
||||
--build-arg "NODE_IMAGE=$nodeImage" `
|
||||
--build-arg "NPM_REGISTRY=$npmReg" `
|
||||
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
|
||||
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
|
||||
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
|
||||
-t "$prefix/dyolink-backend:$tag" `
|
||||
-t "$prefix/dyolink-backend:latest" `
|
||||
./backend
|
||||
@@ -164,6 +174,9 @@ jobs:
|
||||
env:
|
||||
PUBLIC_BASE_URL: ${{ vars.PUBLIC_BASE_URL }}
|
||||
NEXT_PUBLIC_SENTRY_DSN: ${{ vars.NEXT_PUBLIC_SENTRY_DSN }}
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
|
||||
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT_FRONTEND }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tag = "${{ github.sha }}".Substring(0, 7)
|
||||
@@ -191,6 +204,10 @@ jobs:
|
||||
--build-arg "NEXT_PUBLIC_APP_NAME=Dyolink" `
|
||||
--build-arg "NEXT_PUBLIC_SENTRY_DSN=$env:NEXT_PUBLIC_SENTRY_DSN" `
|
||||
--build-arg "NEXT_PUBLIC_SENTRY_ENVIRONMENT=staging" `
|
||||
--build-arg "SENTRY_AUTH_TOKEN=$env:SENTRY_AUTH_TOKEN" `
|
||||
--build-arg "SENTRY_ORG=$env:SENTRY_ORG" `
|
||||
--build-arg "SENTRY_PROJECT=$env:SENTRY_PROJECT" `
|
||||
--build-arg "SENTRY_RELEASE=$tag" `
|
||||
--build-arg "NODE_IMAGE=$nodeImage" `
|
||||
--build-arg "NPM_REGISTRY=$npmReg" `
|
||||
-t "$prefix/dyolink-frontend:$tag" `
|
||||
|
||||
@@ -74,7 +74,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. A type with both dry milling and sintering generates `milling_dry_sinter`; both wet milling and sintering generate `milling_wet_sinter`; both stain and glaze generate `stain_glaze`. A type with only one half keeps that half, and existing task rows are not rewritten. Model design and model create can be outsourced with that line’s teeth, or the whole plan for a historical `__case__` model step; scan, packing, and shipping cannot. 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 the printed order number and the `case-sheet-{orderNumber}.pdf` filename. 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, plus model design and model create, 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. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. **Send to Exocad** (Chrome and Edge only, any screen size; no helper or download) writes an official `.dentalProject` XML into DentalDB's Project Auto-Import folder (`showDirectoryPicker`). It does not open or mutate DentalDB SQLite. Prosthesis pairs stay the same (`Coping`/`ZI` for monolithic/PFZ, custom abutment on Coping, etc.); IPS Overlay uses `AnatomicInlay`/`LS2`; active indirect leaves and implant stacks are mapped; Coping bridges use `ReducedPontic`, full-contour use `AnatomicPontic`. Case shade maps to `VCL:<code>` or bleach `V3DM:0M*`. Empty plans refuse export. The Auto-Import folder can be changed. `externalCode` stays manual. No antagonists or scan files in this phase. There is no Local database tab. 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 the printed order number and the `case-sheet-{orderNumber}.pdf` filename. 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, plus model design and model create, 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. An upload keeps running after leaving Files or Cases; the open case adds the file from the upload response without another fetch. Attachments have no size cap; production must recreate nginx from the SSL template or `/api` stays at 50MB. **Send to Exocad** (Chrome and Edge only, any screen size; no helper or download) writes an official `.dentalProject` XML into DentalDB's Project Auto-Import folder (`showDirectoryPicker`). It does not open or mutate DentalDB SQLite. Mapping follows the official PDF tables: monolithic = `AnatomicCrown`/`ZI`, PFZ/PFM = `Coping`, prefab/Ti-base/multi-unit/custom abutments = `CustomAbutment` (+ material), screw-retained = `WithoutAbutment`; IPS Overlay uses `AnatomicInlay`/`LS2`; active indirect leaves are mapped; Coping bridges use `ReducedPontic`, full-contour use `AnatomicPontic`. Case shade maps to `VCL:<code>` or bleach `V3DM:0M*`. Empty plans refuse export. The Auto-Import folder can be changed. `externalCode` stays manual. No antagonists or scan files in this phase. There is no Local database tab. See `.cursor/skills/lab-cases/SKILL.md` and `.cursor/skills/lab-case-share-link/SKILL.md`.
|
||||
|
||||
**Tooth shade (quick ref):** One optional VITA shade per lab case (`LabCase.toothShadeCode`, nullable; historical shades stay in notes). Full guide in Treatment (lab-dependent) and Cases create/detail; text only on Tasks, share page, and Case Sheet. Locks once any step in the outsource tree is completed; an unchanged resend is a no-op. See `.cursor/rules/tooth-shade.mdc`.
|
||||
|
||||
@@ -96,7 +96,7 @@ backend/src/
|
||||
prisma/ → schema, migrations, seed
|
||||
```
|
||||
|
||||
Errors: `AppException` + `ErrorCode` → frontend `getUserFacingError()`. Unexpected 500s: GlitchTip (`SENTRY_DSN`). Never throw raw strings for user-facing failures.
|
||||
Errors: `AppException` + `ErrorCode` → frontend `getUserFacingError()`. Unexpected 500s: GlitchTip (`SENTRY_DSN`) — one failure, one event; each 5xx wrapper passes `{ cause }` (rule: `.cursor/rules/error-tracking.mdc`). Never throw raw strings for user-facing failures.
|
||||
|
||||
**AdminJS:** Manual resource allowlist in `backend/src/admin/resources.ts`. **Whenever `schema.prisma` changes**, update AdminJS resources in the same task (new/renamed/removed models, hide secrets). Models with only composite `@@id` must not be registered (list 500) — including `LabCaseAttachment`. Single-id models such as `StaffWorkingHoursSchedule` / `StaffWorkingHoursBlock` **are** registered. `LabCase.listedAt` is trigger-maintained (list/filter/show only; never write). Rule: `.cursor/rules/adminjs.mdc`.
|
||||
|
||||
|
||||
@@ -40,6 +40,20 @@ RUN npm run prisma:generate
|
||||
RUN npm run build
|
||||
RUN npm prune --omit=dev
|
||||
|
||||
# Source maps for GlitchTip (Debug IDs). Skipped without SENTRY_AUTH_TOKEN;
|
||||
# a failed upload does not stop the build.
|
||||
ARG SENTRY_AUTH_TOKEN
|
||||
ARG SENTRY_URL=https://errors.wixur.ir
|
||||
ARG SENTRY_ORG
|
||||
ARG SENTRY_PROJECT
|
||||
RUN if [ -z "$SENTRY_AUTH_TOKEN" ]; then \
|
||||
echo "SENTRY_AUTH_TOKEN not set: skip source map upload"; \
|
||||
else \
|
||||
{ npm exec --yes --package=@sentry/cli@2.58.6 -- sentry-cli sourcemaps inject dist \
|
||||
&& npm exec --yes --package=@sentry/cli@2.58.6 -- sentry-cli sourcemaps upload dist; } \
|
||||
|| echo "WARN: source map upload failed; stack traces stay compiled"; \
|
||||
fi
|
||||
|
||||
|
||||
# ============================================
|
||||
# STAGE 2: PRODUCTION STAGE
|
||||
|
||||
@@ -28,6 +28,8 @@ import { VoiceModule } from './modules/voice/voice.module';
|
||||
import { BillingModule } from './modules/billing/billing.module';
|
||||
import { SubscriptionModule } from './modules/subscription/subscription.module';
|
||||
import { SubscriptionWriteInterceptor } from './modules/subscription/subscription-write.interceptor';
|
||||
import { SentryContextInterceptor } from './common/observability/sentry-context.interceptor';
|
||||
import { SentryLifecycle } from './common/observability/sentry-lifecycle';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -77,7 +79,10 @@ import { SubscriptionWriteInterceptor } from './modules/subscription/subscriptio
|
||||
controllers: [AppController],
|
||||
providers: [
|
||||
AppService,
|
||||
// First, so that its tags are on the scope for each later interceptor and handler.
|
||||
{ provide: APP_INTERCEPTOR, useClass: SentryContextInterceptor },
|
||||
{ provide: APP_INTERCEPTOR, useClass: SubscriptionWriteInterceptor },
|
||||
SentryLifecycle,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -11,7 +11,12 @@ export class AppException extends HttpException {
|
||||
code: ErrorCodeValue,
|
||||
status: HttpStatus,
|
||||
details?: ValidationErrorDetail[] | unknown,
|
||||
cause?: unknown,
|
||||
) {
|
||||
super({ code, details } satisfies AppErrorResponse, status);
|
||||
super(
|
||||
{ code, details } satisfies AppErrorResponse,
|
||||
status,
|
||||
cause === undefined ? undefined : { cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
47
backend/src/common/observability/report-failure.ts
Normal file
47
backend/src/common/observability/report-failure.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import * as Sentry from '@sentry/nestjs';
|
||||
|
||||
const fallbackLogger = new Logger('FailureReport');
|
||||
|
||||
function logFailure(
|
||||
kind: string,
|
||||
name: string,
|
||||
error: unknown,
|
||||
logger?: Logger,
|
||||
context?: Record<string, string>,
|
||||
): void {
|
||||
const details =
|
||||
context && Object.keys(context).length > 0
|
||||
? ` ${JSON.stringify(context)}`
|
||||
: '';
|
||||
(logger ?? fallbackLogger).error(
|
||||
`${kind} "${name}" failed${details}`,
|
||||
error instanceof Error ? error.stack : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
/** A failure of work that runs detached from the response (fire-and-forget calls, timers). */
|
||||
export function reportBackgroundFailure(
|
||||
task: string,
|
||||
error: unknown,
|
||||
logger?: Logger,
|
||||
context?: Record<string, string>,
|
||||
): void {
|
||||
logFailure('Background task', task, error, logger, context);
|
||||
Sentry.captureException(error, {
|
||||
tags: { background_task: task, ...context },
|
||||
});
|
||||
}
|
||||
|
||||
/** A failure that the code handled (the user still gets a response) but that must be visible. */
|
||||
export function reportHandledFailure(
|
||||
operation: string,
|
||||
error: unknown,
|
||||
logger?: Logger,
|
||||
context?: Record<string, string>,
|
||||
): void {
|
||||
logFailure('Handled failure', operation, error, logger, context);
|
||||
Sentry.captureException(error, {
|
||||
tags: { handled: 'true', operation, ...context },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import * as Sentry from '@sentry/nestjs';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
type RequestWithUser = { user?: { id?: string; organizationId?: string } };
|
||||
|
||||
/**
|
||||
* Puts the user and the organization of the request on each event.
|
||||
* Runs after the guards, so `request.user` is set.
|
||||
*/
|
||||
@Injectable()
|
||||
export class SentryContextInterceptor implements NestInterceptor {
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
const user = context
|
||||
.switchToHttp()
|
||||
.getRequest<RequestWithUser | undefined>()?.user;
|
||||
|
||||
if (user?.id) {
|
||||
Sentry.setUser({ id: user.id });
|
||||
if (user.organizationId) {
|
||||
Sentry.setTag('organization_id', user.organizationId);
|
||||
}
|
||||
}
|
||||
|
||||
return next.handle();
|
||||
}
|
||||
}
|
||||
10
backend/src/common/observability/sentry-lifecycle.ts
Normal file
10
backend/src/common/observability/sentry-lifecycle.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { Injectable, type OnApplicationShutdown } from '@nestjs/common';
|
||||
import * as Sentry from '@sentry/nestjs';
|
||||
|
||||
/** Drains the event queue on SIGTERM. Needs `app.enableShutdownHooks()`. */
|
||||
@Injectable()
|
||||
export class SentryLifecycle implements OnApplicationShutdown {
|
||||
async onApplicationShutdown(): Promise<void> {
|
||||
await Sentry.close(2000);
|
||||
}
|
||||
}
|
||||
199
backend/src/common/observability/sentry-options.spec.ts
Normal file
199
backend/src/common/observability/sentry-options.spec.ts
Normal file
@@ -0,0 +1,199 @@
|
||||
import { HttpStatus, InternalServerErrorException } from '@nestjs/common';
|
||||
import type { Breadcrumb, ErrorEvent } from '@sentry/core';
|
||||
import { AppException } from '../errors/app.exception';
|
||||
import { ErrorCode } from '../errors/error-codes';
|
||||
import {
|
||||
beforeSend,
|
||||
buildSentryOptions,
|
||||
filterBreadcrumb,
|
||||
redactSensitiveText,
|
||||
scrubUrl,
|
||||
} from './sentry-options';
|
||||
|
||||
describe('sentry options', () => {
|
||||
describe('scrubUrl', () => {
|
||||
it('given a URL with a query string and a hash, when scrubUrl runs, then only the path stays', () => {
|
||||
expect(scrubUrl('http://host/api/patients?q=0912&x=1#top')).toBe(
|
||||
'http://host/api/patients',
|
||||
);
|
||||
});
|
||||
|
||||
it('given the path of a share link, when scrubUrl runs, then the token segment is masked', () => {
|
||||
expect(
|
||||
scrubUrl('http://host/api/lab-cases/access/abc123/tasks?x=1'),
|
||||
).toBe('http://host/api/lab-cases/access/[token]/tasks');
|
||||
});
|
||||
});
|
||||
|
||||
describe('redactSensitiveText', () => {
|
||||
it('given text with an email address and mobile numbers, when redactSensitiveText runs, then all are masked', () => {
|
||||
expect(
|
||||
redactSensitiveText('No user for a@b.co, 09120000000 or +989120000000'),
|
||||
).toBe('No user for [email], [mobile] or [mobile]');
|
||||
});
|
||||
|
||||
it('given text with ordinary numbers, when redactSensitiveText runs, then the numbers stay', () => {
|
||||
expect(redactSensitiveText('status 500, id 123456789012')).toBe(
|
||||
'status 500, id 123456789012',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('beforeSend', () => {
|
||||
const makeEvent = () =>
|
||||
({
|
||||
exception: {
|
||||
values: [{ type: 'AppException', value: 'App Exception' }],
|
||||
},
|
||||
request: {
|
||||
url: 'http://host/api/lab-cases/access/abc?token=1',
|
||||
query_string: 'token=1',
|
||||
cookies: { accessToken: 'JWT' },
|
||||
data: '{"password":"x"}',
|
||||
headers: { cookie: 'a=b', authorization: 'Bearer x', host: 'host' },
|
||||
},
|
||||
user: {
|
||||
id: 'u1',
|
||||
email: 'a@b.co',
|
||||
ip_address: '203.0.113.9',
|
||||
username: 'amin',
|
||||
},
|
||||
tags: {},
|
||||
}) as unknown as ErrorEvent;
|
||||
|
||||
it('given an event with cookies, body, query string, and user contact data, when beforeSend runs, then that data is gone', () => {
|
||||
const result = beforeSend(makeEvent(), {
|
||||
originalException: new Error('x'),
|
||||
});
|
||||
|
||||
expect(result?.request).toEqual({
|
||||
url: 'http://host/api/lab-cases/access/[token]',
|
||||
headers: { host: 'host' },
|
||||
});
|
||||
expect(result?.user).toEqual({ id: 'u1' });
|
||||
});
|
||||
|
||||
it('given an AppException with status 502, when beforeSend runs, then the exception is named by its error code and the status is tagged', () => {
|
||||
const exception = new AppException(
|
||||
ErrorCode.VOICE_EXTRACT_FAILED,
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
const result = beforeSend(makeEvent(), { originalException: exception });
|
||||
|
||||
expect(result?.exception?.values?.[0].value).toBe('VOICE_EXTRACT_FAILED');
|
||||
expect(result?.tags).toEqual({
|
||||
http_status: '502',
|
||||
error_code: 'VOICE_EXTRACT_FAILED',
|
||||
});
|
||||
});
|
||||
|
||||
it('given a Nest 5xx with its own message, when beforeSend runs, then the message stays and the status is tagged', () => {
|
||||
const exception = new InternalServerErrorException(
|
||||
'Failed to get profile',
|
||||
);
|
||||
const event = {
|
||||
exception: { values: [{ type: 'Error', value: 'db down' }] },
|
||||
tags: {},
|
||||
} as unknown as ErrorEvent;
|
||||
|
||||
const result = beforeSend(event, { originalException: exception });
|
||||
|
||||
expect(result?.exception?.values?.[0].value).toBe('db down');
|
||||
expect(result?.tags).toEqual({ http_status: '500' });
|
||||
});
|
||||
|
||||
it('given an exception message with an email address and a mobile number, when beforeSend runs, then both are masked', () => {
|
||||
const event = {
|
||||
exception: {
|
||||
values: [{ type: 'Error', value: 'No user a@b.co 09120000000' }],
|
||||
},
|
||||
} as unknown as ErrorEvent;
|
||||
|
||||
expect(
|
||||
beforeSend(event, { originalException: new Error('x') })?.exception
|
||||
?.values?.[0].value,
|
||||
).toBe('No user [email] [mobile]');
|
||||
});
|
||||
|
||||
it('given a route name with a share-link token, when beforeSend runs, then the token is masked', () => {
|
||||
const event = {
|
||||
transaction: 'GET /api/lab-cases/access/abc123/tasks',
|
||||
} as unknown as ErrorEvent;
|
||||
|
||||
expect(
|
||||
beforeSend(event, { originalException: new Error('x') })?.transaction,
|
||||
).toBe('GET /api/lab-cases/access/[token]/tasks');
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterBreadcrumb', () => {
|
||||
it('given console output of level log or info in production, when the breadcrumb is filtered, then it is dropped', () => {
|
||||
expect(
|
||||
filterBreadcrumb(
|
||||
{ category: 'console', level: 'log', message: 'x' },
|
||||
true,
|
||||
),
|
||||
).toBeNull();
|
||||
expect(
|
||||
filterBreadcrumb(
|
||||
{ category: 'console', level: 'info', message: 'x' },
|
||||
true,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('given console output of level log outside production, when the breadcrumb is filtered, then it stays', () => {
|
||||
expect(
|
||||
filterBreadcrumb(
|
||||
{ category: 'console', level: 'log', message: 'x' },
|
||||
false,
|
||||
),
|
||||
).not.toBeNull();
|
||||
});
|
||||
|
||||
it('given console output of level error in production, when the breadcrumb is filtered, then it stays', () => {
|
||||
expect(
|
||||
filterBreadcrumb(
|
||||
{ category: 'console', level: 'error', message: 'x' },
|
||||
true,
|
||||
),
|
||||
).not.toBeNull();
|
||||
});
|
||||
|
||||
it('given a request breadcrumb with a query string in its URL, when the breadcrumb is filtered, then the query string is gone', () => {
|
||||
const breadcrumb = {
|
||||
category: 'xhr',
|
||||
level: 'info',
|
||||
data: { url: '/api/patients?q=john' },
|
||||
} as Breadcrumb;
|
||||
|
||||
filterBreadcrumb(breadcrumb, false);
|
||||
|
||||
expect(breadcrumb.data).toEqual({ url: '/api/patients' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildSentryOptions', () => {
|
||||
it('given no DSN, when the options are built, then the SDK is off and no tracing option is set', () => {
|
||||
const options = buildSentryOptions({ NODE_ENV: 'production' });
|
||||
|
||||
expect(options.dsn).toBeUndefined();
|
||||
expect(options.sendDefaultPii).toBe(false);
|
||||
expect(options).not.toHaveProperty('tracesSampleRate');
|
||||
expect(options).not.toHaveProperty('tracesSampler');
|
||||
});
|
||||
|
||||
it('given a DSN, an environment, and a release, when the options are built, then all three are read', () => {
|
||||
const options = buildSentryOptions({
|
||||
NODE_ENV: 'production',
|
||||
SENTRY_DSN: ' https://key@errors.example/1 ',
|
||||
SENTRY_ENVIRONMENT: 'staging',
|
||||
SENTRY_RELEASE: 'v1.2.3',
|
||||
});
|
||||
|
||||
expect(options.dsn).toBe('https://key@errors.example/1');
|
||||
expect(options.environment).toBe('staging');
|
||||
expect(options.release).toBe('v1.2.3');
|
||||
});
|
||||
});
|
||||
});
|
||||
169
backend/src/common/observability/sentry-options.ts
Normal file
169
backend/src/common/observability/sentry-options.ts
Normal file
@@ -0,0 +1,169 @@
|
||||
import type { Breadcrumb, ErrorEvent, Event, EventHint } from '@sentry/core';
|
||||
import type { NodeOptions } from '@sentry/nestjs';
|
||||
|
||||
type Env = Record<string, string | undefined>;
|
||||
|
||||
/** Path prefixes whose next segment is a secret token (lab case share links). */
|
||||
const TOKEN_PATH_PREFIXES = ['/api/lab-cases/access/'];
|
||||
|
||||
const TOKEN_PATH_PATTERNS = TOKEN_PATH_PREFIXES.map(
|
||||
(prefix) =>
|
||||
new RegExp(
|
||||
`(${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})[^/?#]+`,
|
||||
'g',
|
||||
),
|
||||
);
|
||||
|
||||
const EMAIL_PATTERN = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g;
|
||||
const MOBILE_PATTERN = /(?<![\d+])(?:\+98|0098)?0?9\d{9}(?!\d)/g;
|
||||
|
||||
const SENSITIVE_HEADERS = [
|
||||
'cookie',
|
||||
'Cookie',
|
||||
'authorization',
|
||||
'Authorization',
|
||||
];
|
||||
|
||||
export function scrubUrl(url: string): string {
|
||||
const [path] = url.split(/[?#]/);
|
||||
return TOKEN_PATH_PATTERNS.reduce(
|
||||
(value, pattern) => value.replace(pattern, '$1[token]'),
|
||||
path,
|
||||
);
|
||||
}
|
||||
|
||||
// Exception messages can quote user input.
|
||||
export function redactSensitiveText(text: string): string {
|
||||
return text
|
||||
.replace(EMAIL_PATTERN, '[email]')
|
||||
.replace(MOBILE_PATTERN, '[mobile]');
|
||||
}
|
||||
|
||||
function scrubRequest(event: Event): void {
|
||||
const request = event.request as
|
||||
| (Record<string, unknown> & {
|
||||
url?: unknown;
|
||||
headers?: Record<string, string>;
|
||||
})
|
||||
| undefined;
|
||||
if (!request) return;
|
||||
|
||||
if (typeof request.url === 'string') {
|
||||
request.url = scrubUrl(request.url);
|
||||
}
|
||||
// SDK 10 puts cookies, the body, and the query string on server events although sendDefaultPii is false.
|
||||
delete request.query_string;
|
||||
delete request.data;
|
||||
delete request.cookies;
|
||||
for (const header of SENSITIVE_HEADERS) {
|
||||
delete request.headers?.[header];
|
||||
}
|
||||
}
|
||||
|
||||
function scrubUser(event: Event): void {
|
||||
if (!event.user) return;
|
||||
|
||||
delete event.user.email;
|
||||
delete event.user.username;
|
||||
delete event.user.ip_address;
|
||||
}
|
||||
|
||||
function redactExceptions(event: Event): void {
|
||||
for (const exception of event.exception?.values ?? []) {
|
||||
if (exception.value) {
|
||||
exception.value = redactSensitiveText(exception.value);
|
||||
}
|
||||
}
|
||||
if (event.message) {
|
||||
event.message = redactSensitiveText(event.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Duck-typed: instrument.ts must not load Nest before Sentry.init.
|
||||
function httpStatusOf(value: unknown): number | undefined {
|
||||
if (typeof value !== 'object' || value === null) return undefined;
|
||||
const getStatus = (value as { getStatus?: unknown }).getStatus;
|
||||
return typeof getStatus === 'function'
|
||||
? Number(getStatus.call(value))
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function appErrorCodeOf(value: unknown): string | undefined {
|
||||
if (typeof value !== 'object' || value === null) return undefined;
|
||||
const getResponse = (value as { getResponse?: unknown }).getResponse;
|
||||
if (typeof getResponse !== 'function') return undefined;
|
||||
|
||||
const response = getResponse.call(value) as { code?: unknown } | undefined;
|
||||
return typeof response?.code === 'string' ? response.code : undefined;
|
||||
}
|
||||
|
||||
export function beforeSend(
|
||||
event: ErrorEvent,
|
||||
hint: EventHint,
|
||||
): ErrorEvent | null {
|
||||
scrubRequest(event);
|
||||
scrubUser(event);
|
||||
redactExceptions(event);
|
||||
|
||||
// Can be the raw path, which carries the share-link token.
|
||||
if (typeof event.transaction === 'string') {
|
||||
event.transaction = scrubUrl(event.transaction);
|
||||
}
|
||||
|
||||
const exception = hint?.originalException;
|
||||
const status = httpStatusOf(exception);
|
||||
if (status !== undefined) {
|
||||
event.tags = { ...event.tags, http_status: String(status) };
|
||||
|
||||
const code = appErrorCodeOf(exception);
|
||||
if (code) {
|
||||
event.tags.error_code = code;
|
||||
// An AppException message is only its class name.
|
||||
const values = event.exception?.values;
|
||||
const thrown = values?.[values.length - 1];
|
||||
if (thrown) {
|
||||
thrown.value = code;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return event;
|
||||
}
|
||||
|
||||
// In production, console output of level log and info is dropped.
|
||||
export function filterBreadcrumb(
|
||||
breadcrumb: Breadcrumb,
|
||||
isProduction: boolean,
|
||||
): Breadcrumb | null {
|
||||
const data = breadcrumb.data as { url?: unknown } | undefined;
|
||||
if (data && typeof data.url === 'string') {
|
||||
data.url = scrubUrl(data.url);
|
||||
}
|
||||
|
||||
if (
|
||||
isProduction &&
|
||||
breadcrumb.category === 'console' &&
|
||||
(breadcrumb.level === 'log' || breadcrumb.level === 'info')
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return breadcrumb;
|
||||
}
|
||||
|
||||
// No tracesSampleRate: without it no tracing code loads, and errors still share a trace id.
|
||||
export function buildSentryOptions(env: Env = process.env): NodeOptions {
|
||||
const dsn = env.SENTRY_DSN?.trim();
|
||||
const isProduction = env.NODE_ENV === 'production';
|
||||
|
||||
return {
|
||||
dsn: dsn || undefined,
|
||||
environment:
|
||||
env.SENTRY_ENVIRONMENT?.trim() || env.NODE_ENV || 'development',
|
||||
release: env.SENTRY_RELEASE?.trim() || undefined,
|
||||
sendDefaultPii: false,
|
||||
beforeSend,
|
||||
beforeBreadcrumb: (breadcrumb: Breadcrumb) =>
|
||||
filterBreadcrumb(breadcrumb, isProduction),
|
||||
};
|
||||
}
|
||||
@@ -1,36 +1,11 @@
|
||||
import { config } from 'dotenv';
|
||||
import * as Sentry from '@sentry/nestjs';
|
||||
import { buildSentryOptions } from './common/observability/sentry-options';
|
||||
|
||||
config();
|
||||
|
||||
const dsn = process.env.SENTRY_DSN?.trim();
|
||||
const options = buildSentryOptions();
|
||||
|
||||
if (dsn) {
|
||||
Sentry.init({
|
||||
dsn,
|
||||
environment:
|
||||
process.env.SENTRY_ENVIRONMENT?.trim() ||
|
||||
process.env.NODE_ENV ||
|
||||
'development',
|
||||
release: process.env.SENTRY_RELEASE?.trim() || undefined,
|
||||
sendDefaultPii: false,
|
||||
tracesSampleRate: 0,
|
||||
beforeSend(event) {
|
||||
if (event.request) {
|
||||
delete event.request.cookies;
|
||||
delete event.request.data;
|
||||
if (event.request.headers) {
|
||||
delete event.request.headers.cookie;
|
||||
delete event.request.headers.authorization;
|
||||
delete event.request.headers.Authorization;
|
||||
}
|
||||
}
|
||||
if (event.user) {
|
||||
delete event.user.email;
|
||||
delete event.user.ip_address;
|
||||
delete event.user.username;
|
||||
}
|
||||
return event;
|
||||
},
|
||||
});
|
||||
if (options.dsn) {
|
||||
Sentry.init(options);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// backend/src/main.ts
|
||||
import './instrument';
|
||||
import * as Sentry from '@sentry/nestjs';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { urlencoded } from 'express';
|
||||
import { AppModule } from './app.module';
|
||||
@@ -30,6 +31,9 @@ async function bootstrap() {
|
||||
// Nest's built-in one would otherwise reject a voice recording at 100 kb.
|
||||
const app = await NestFactory.create(AppModule, { bodyParser: false });
|
||||
|
||||
// SIGTERM: run onModuleDestroy (Prisma, timers), then drain the Sentry queue (SentryLifecycle).
|
||||
app.enableShutdownHooks();
|
||||
|
||||
// Nginx terminates TLS; AdminJS sessions and Secure cookies need the real proto/host.
|
||||
app.getHttpAdapter().getInstance().set('trust proxy', 1);
|
||||
|
||||
@@ -97,4 +101,9 @@ async function bootstrap() {
|
||||
console.log(`📚 AdminJS Panel: http://localhost:${port}/admin`);
|
||||
}
|
||||
|
||||
bootstrap();
|
||||
bootstrap().catch((error: unknown) => {
|
||||
// Exit so the container restarts; the SDK alone would keep the process alive with no port.
|
||||
console.error('Backend failed to start', error);
|
||||
Sentry.captureException(error, { tags: { startup: 'true' } });
|
||||
void Sentry.close(2000).finally(() => process.exit(1));
|
||||
});
|
||||
|
||||
@@ -73,8 +73,6 @@ export class AuthController {
|
||||
@Req() req,
|
||||
@Res({ passthrough: true }) res: Response
|
||||
) {
|
||||
console.log('Login endpoint hit');
|
||||
|
||||
const result = await this.authService.login(loginDto, req.user);
|
||||
const rememberMe = Boolean(loginDto.rememberMe);
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@ import {
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
HttpException,
|
||||
InternalServerErrorException
|
||||
InternalServerErrorException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import type { JwtSignOptions } from '@nestjs/jwt';
|
||||
@@ -147,6 +148,8 @@ const READ_ONLY_PERMISSIONS = [
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private readonly logger = new Logger(AuthService.name);
|
||||
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private jwtService: JwtService,
|
||||
@@ -157,6 +160,16 @@ export class AuthService {
|
||||
private subscription: SubscriptionService,
|
||||
) { }
|
||||
|
||||
/** A malformed, expired, or not-yet-valid token is a client condition. Each other error is a server failure. */
|
||||
private isTokenError(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof Error &&
|
||||
(error.name === 'JsonWebTokenError' ||
|
||||
error.name === 'TokenExpiredError' ||
|
||||
error.name === 'NotBeforeError')
|
||||
);
|
||||
}
|
||||
|
||||
private accessJwtSignOptions(): JwtSignOptions {
|
||||
return {
|
||||
secret: this.configService.get<string>('jwt.secret')!,
|
||||
@@ -219,7 +232,12 @@ export class AuthService {
|
||||
const { passwordHash, ...result } = user;
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw new InternalServerErrorException('Error validating user');
|
||||
if (error instanceof HttpException) {
|
||||
throw error;
|
||||
}
|
||||
throw new InternalServerErrorException('Error validating user', {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,8 +298,13 @@ export class AuthService {
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
//throw new InternalServerErrorException('Login failed');
|
||||
console.error('🔥 LOGIN ERROR FULL:', error);
|
||||
// Expected 4xx (unverified email) must not log as an error; the filter reports the rest.
|
||||
if (!(error instanceof HttpException)) {
|
||||
this.logger.error(
|
||||
'Login failed',
|
||||
error instanceof Error ? error.stack : undefined,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -518,7 +541,12 @@ export class AuthService {
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
throw new InternalServerErrorException('Failed to get profile');
|
||||
if (error instanceof HttpException) {
|
||||
throw error;
|
||||
}
|
||||
throw new InternalServerErrorException('Failed to get profile', {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -538,7 +566,9 @@ export class AuthService {
|
||||
message: 'Logged out successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new InternalServerErrorException('Logout failed');
|
||||
throw new InternalServerErrorException('Logout failed', {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -622,10 +652,11 @@ export class AuthService {
|
||||
if (error instanceof HttpException) {
|
||||
throw error;
|
||||
}
|
||||
if (error instanceof Error && (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError')) {
|
||||
if (this.isTokenError(error)) {
|
||||
throw new AppException(ErrorCode.AUTH_REFRESH_TOKEN_INVALID, HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
throw new AppException(ErrorCode.AUTH_REFRESH_TOKEN_INVALID, HttpStatus.UNAUTHORIZED);
|
||||
// A database failure is a server error. The filter reports it.
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -687,7 +718,9 @@ export class AuthService {
|
||||
if (error instanceof HttpException) {
|
||||
throw error;
|
||||
}
|
||||
throw new InternalServerErrorException('Failed to change password');
|
||||
throw new InternalServerErrorException('Failed to change password', {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -926,7 +959,9 @@ export class AuthService {
|
||||
data: sessions,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new InternalServerErrorException('Failed to get sessions');
|
||||
throw new InternalServerErrorException('Failed to get sessions', {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -950,7 +985,9 @@ export class AuthService {
|
||||
message: 'Session revoked successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new InternalServerErrorException('Failed to revoke session');
|
||||
throw new InternalServerErrorException('Failed to revoke session', {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -974,7 +1011,9 @@ export class AuthService {
|
||||
message: 'All other sessions revoked successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new InternalServerErrorException('Failed to revoke sessions');
|
||||
throw new InternalServerErrorException('Failed to revoke sessions', {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1023,7 +1062,16 @@ export class AuthService {
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
throw new AppException(ErrorCode.AUTH_SESSION_EXPIRED, HttpStatus.UNAUTHORIZED);
|
||||
if (error instanceof HttpException) {
|
||||
throw error;
|
||||
}
|
||||
if (this.isTokenError(error)) {
|
||||
throw new AppException(
|
||||
ErrorCode.AUTH_SESSION_EXPIRED,
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { reportBackgroundFailure } from '../../common/observability/report-failure';
|
||||
import {
|
||||
BillingCatalogKind,
|
||||
BillingCashEventType,
|
||||
@@ -158,11 +159,12 @@ export class BillingService implements OnModuleInit, OnModuleDestroy {
|
||||
}
|
||||
|
||||
onModuleInit() {
|
||||
void this.runScheduledStaffRollupIfDue().catch(() => undefined);
|
||||
this.staffRollupTimer = setInterval(
|
||||
() => void this.runScheduledStaffRollupIfDue().catch(() => undefined),
|
||||
60 * 60 * 1000,
|
||||
);
|
||||
const runRollup = () =>
|
||||
void this.runScheduledStaffRollupIfDue().catch((error: unknown) => {
|
||||
reportBackgroundFailure('staff-billing-rollup', error);
|
||||
});
|
||||
runRollup();
|
||||
this.staffRollupTimer = setInterval(runRollup, 60 * 60 * 1000);
|
||||
this.staffRollupTimer.unref?.();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { HttpStatus, Injectable, Logger } from '@nestjs/common';
|
||||
import { AppException, ErrorCode } from '../../common/errors';
|
||||
import { reportHandledFailure } from '../../common/observability/report-failure';
|
||||
import { createReadStream, existsSync, unlinkSync } from 'fs';
|
||||
import { join, resolve, sep } from 'path';
|
||||
import {
|
||||
@@ -647,8 +648,11 @@ export class CasesService {
|
||||
});
|
||||
try {
|
||||
await this.notifyPartnerCaseCreated(labCaseId, actorUserId);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// Start already committed. A notice failure must not turn that into a 500.
|
||||
reportHandledFailure('partner-case-created-notice', error, this.logger, {
|
||||
lab_case_id: labCaseId,
|
||||
});
|
||||
}
|
||||
return { success: true, data: await this.mapLabCaseDetail(refreshed, localeInput, labOrganizationId) };
|
||||
}
|
||||
@@ -943,7 +947,7 @@ export class CasesService {
|
||||
return child.id;
|
||||
});
|
||||
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: dto.destinationOrganizationId,
|
||||
type: UserNotificationType.CASE_SENT,
|
||||
href: `/cases?caseId=${encodeURIComponent(childCaseId)}`,
|
||||
@@ -1128,15 +1132,14 @@ export class CasesService {
|
||||
payload: { attachmentId },
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Failed to record ATTACHMENT_ADDED for case ${labCaseId}`,
|
||||
error instanceof Error ? error.stack : undefined,
|
||||
);
|
||||
reportHandledFailure('attachment-activity-row', error, this.logger, {
|
||||
lab_case_id: labCaseId,
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (created.length > 0) {
|
||||
void this.userNotifications.emitCaseSectionChanged({
|
||||
this.userNotifications.emitCaseSectionChangedInBackground({
|
||||
organizationId: labOrganizationId,
|
||||
actorUserId,
|
||||
labCaseId,
|
||||
@@ -1404,7 +1407,7 @@ export class CasesService {
|
||||
type: LabCaseActivityType.CASE_IMPORTANT,
|
||||
actorUserId,
|
||||
});
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: labOrganizationId,
|
||||
type: UserNotificationType.CASE_IMPORTANT,
|
||||
href: `/cases?caseId=${encodeURIComponent(labCaseId)}`,
|
||||
@@ -1599,7 +1602,7 @@ export class CasesService {
|
||||
payload: { taskId, assigneeUserId },
|
||||
});
|
||||
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: labOrganizationId,
|
||||
type: UserNotificationType.TASK_ASSIGNED,
|
||||
href: `/tasks?taskId=${encodeURIComponent(taskId)}&labCaseId=${encodeURIComponent(labCaseId)}`,
|
||||
@@ -2308,7 +2311,7 @@ export class CasesService {
|
||||
const token = await this.labCaseAccess.ensureAccessToken(labCase.id);
|
||||
if (!token) return;
|
||||
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: labCase.partnerClinicOrganizationId,
|
||||
type: UserNotificationType.PARTNER_CASE_CREATED,
|
||||
href: `/lab-case/${token}`,
|
||||
|
||||
@@ -65,7 +65,7 @@ export class LabCaseCommentsService {
|
||||
},
|
||||
});
|
||||
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: labOrganizationId,
|
||||
type: UserNotificationType.LAB_COMMENT,
|
||||
href: `/cases?caseId=${encodeURIComponent(caseId)}`,
|
||||
@@ -146,7 +146,7 @@ export class LabCaseCommentsService {
|
||||
});
|
||||
const labOrgId = await this.labOrgIdForCase(caseId);
|
||||
if (labOrgId) {
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: labOrgId,
|
||||
type: UserNotificationType.CLINIC_COMMENT,
|
||||
href: `/cases?caseId=${encodeURIComponent(caseId)}`,
|
||||
@@ -199,7 +199,7 @@ export class LabCaseCommentsService {
|
||||
});
|
||||
const labOrgId = await this.labOrgIdForCase(caseId);
|
||||
if (labOrgId) {
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: labOrgId,
|
||||
type: UserNotificationType.CLINIC_COMMENT,
|
||||
href: `/cases?caseId=${encodeURIComponent(caseId)}`,
|
||||
@@ -254,7 +254,7 @@ export class LabCaseCommentsService {
|
||||
|
||||
const labOrgId = await this.labOrgIdForCase(caseId);
|
||||
if (labOrgId && labOrgId !== partnerOrganizationId) {
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: labOrgId,
|
||||
type:
|
||||
authorSide === LabCaseCommentSide.CLINIC
|
||||
@@ -524,7 +524,7 @@ export class LabCaseCommentsService {
|
||||
if (!partnerId || labCase.partnerClinic?.type.name !== 'CLINIC') return;
|
||||
const href = await this.partnerShareHref(caseId);
|
||||
if (!href) return;
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: partnerId,
|
||||
type: UserNotificationType.LAB_COMMENT_CLINIC,
|
||||
href,
|
||||
@@ -538,7 +538,7 @@ export class LabCaseCommentsService {
|
||||
if (labCase.origin === LabCaseOrigin.LAB_OUTSOURCE) {
|
||||
const parentLabId = labCase.parentLabCase?.destinationOrganizationId;
|
||||
if (!parentLabId || !labCase.parentLabCaseId) return;
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: parentLabId,
|
||||
type: UserNotificationType.LAB_COMMENT,
|
||||
href: `/cases?caseId=${encodeURIComponent(labCase.parentLabCaseId)}`,
|
||||
@@ -552,7 +552,7 @@ export class LabCaseCommentsService {
|
||||
const clinicOrgId =
|
||||
labCase.treatment?.organizationId ?? labCase.partnerClinicOrganizationId ?? null;
|
||||
if (!clinicOrgId) return;
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: clinicOrgId,
|
||||
type: UserNotificationType.LAB_COMMENT_CLINIC,
|
||||
href: `/treatment?labCaseId=${encodeURIComponent(caseId)}`,
|
||||
|
||||
@@ -179,7 +179,12 @@ export class MailService {
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error(message.failureLog, error);
|
||||
throw new AppException(ErrorCode.AUTH_EMAIL_SEND_FAILED, HttpStatus.BAD_GATEWAY);
|
||||
throw new AppException(
|
||||
ErrorCode.AUTH_EMAIL_SEND_FAILED,
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
undefined,
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Prisma, UserNotificationType } from '@prisma/client';
|
||||
import { PrismaService } from '../../../prisma/prisma.service';
|
||||
import { hasEffectivePermission } from '../../common/membership-permissions';
|
||||
import { reportBackgroundFailure } from '../../common/observability/report-failure';
|
||||
import { isActorTreatmentProvider } from '../../common/treatment-provider-scope';
|
||||
import { RealtimeEmitter } from '../../realtime/realtime.emitter';
|
||||
|
||||
@@ -39,13 +40,40 @@ type FanoutInput = RecipientQuery & {
|
||||
recipientUserIds?: string[];
|
||||
};
|
||||
|
||||
type CaseSectionChangedInput = {
|
||||
organizationId: string;
|
||||
actorUserId: string;
|
||||
labCaseId: string;
|
||||
requiredPermissions: string[];
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class UserNotificationService {
|
||||
private readonly logger = new Logger(UserNotificationService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly realtime: RealtimeEmitter,
|
||||
) {}
|
||||
|
||||
/** `notify()` for callers that do not await it: reports the failure instead of an unhandled rejection. */
|
||||
notifyInBackground(input: FanoutInput): void {
|
||||
this.runInBackground('user-notification.notify', this.notify(input));
|
||||
}
|
||||
|
||||
emitCaseSectionChangedInBackground(input: CaseSectionChangedInput): void {
|
||||
this.runInBackground(
|
||||
'case-section-changed',
|
||||
this.emitCaseSectionChanged(input),
|
||||
);
|
||||
}
|
||||
|
||||
private runInBackground(task: string, work: Promise<unknown>): void {
|
||||
void work.catch((error: unknown) => {
|
||||
reportBackgroundFailure(task, error, this.logger);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Lean lab-case snapshot for inbox cards. Used only inside `notify()` so
|
||||
* inbox list/read never joins patients/orgs/tasks.
|
||||
@@ -199,12 +227,7 @@ export class UserNotificationService {
|
||||
* Tell other lab members a case section changed, without writing an inbox row.
|
||||
* The client treats `case-section.changed` like a tab-badge refresh.
|
||||
*/
|
||||
async emitCaseSectionChanged(input: {
|
||||
organizationId: string;
|
||||
actorUserId: string;
|
||||
labCaseId: string;
|
||||
requiredPermissions: string[];
|
||||
}): Promise<void> {
|
||||
async emitCaseSectionChanged(input: CaseSectionChangedInput): Promise<void> {
|
||||
const recipientIds = await this.resolveRecipients({
|
||||
organizationId: input.organizationId,
|
||||
actorUserId: input.actorUserId,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { HttpStatus, Injectable, Logger } from '@nestjs/common';
|
||||
import { AppException, ErrorCode } from '../../common/errors';
|
||||
import { reportHandledFailure } from '../../common/observability/report-failure';
|
||||
import { LinkStatus, UserNotificationType } from '@prisma/client';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { createHash, randomBytes } from 'crypto';
|
||||
@@ -317,7 +318,7 @@ export class OrganizationService {
|
||||
},
|
||||
});
|
||||
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: dto.targetOrganizationId,
|
||||
type: UserNotificationType.CONNECTION_REQUEST,
|
||||
href: '/organizations',
|
||||
@@ -1017,7 +1018,8 @@ export class OrganizationService {
|
||||
locale: normalizeEmailLocale(inviter?.language),
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to email invitation link to ${params.email}`, error);
|
||||
// The invite exists and the inviter sees success. The failure must still be visible.
|
||||
reportHandledFailure('invitation-email', error, this.logger);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { Injectable, InternalServerErrorException, Logger } from '@nestjs/common';
|
||||
import {
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
interface SmsIrVerifyResponse {
|
||||
@@ -21,7 +25,15 @@ export class SmsService {
|
||||
const templateId = this.configService.get<number>('sms.templateId');
|
||||
|
||||
if (!apiKey) {
|
||||
this.logger.warn(`SMS_IR_API_KEY not set — verification code for ${mobile}: ${code}`);
|
||||
if (this.configService.get<string>('NODE_ENV') === 'development') {
|
||||
this.logger.warn(
|
||||
`[dev] SMS_IR_API_KEY not set — verification code for ${mobile}: ${code}`,
|
||||
);
|
||||
} else {
|
||||
this.logger.warn(
|
||||
'SMS_IR_API_KEY not set: the verification SMS was not sent',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -40,24 +52,35 @@ export class SmsService {
|
||||
parameters: [{ name: 'Code', value: code }],
|
||||
}),
|
||||
});
|
||||
console.log('request', templateId , apiKey,mobile, code);
|
||||
console.log('response', response);
|
||||
|
||||
} catch (error) {
|
||||
this.logger.error('sms.ir request failed', error);
|
||||
throw new InternalServerErrorException('Failed to send verification code');
|
||||
throw new InternalServerErrorException(
|
||||
'Failed to send verification code',
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
|
||||
let payload: SmsIrVerifyResponse;
|
||||
try {
|
||||
payload = (await response.json()) as SmsIrVerifyResponse;
|
||||
} catch {
|
||||
throw new InternalServerErrorException('Invalid response from SMS provider');
|
||||
} catch (error) {
|
||||
throw new InternalServerErrorException(
|
||||
'Invalid response from SMS provider',
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
|
||||
if (!response.ok || payload.status !== 1) {
|
||||
this.logger.error(`sms.ir error: ${payload.message}`);
|
||||
throw new InternalServerErrorException('Failed to send verification code');
|
||||
const providerError = new Error(
|
||||
`sms.ir status ${payload.status}: ${payload.message}`,
|
||||
);
|
||||
throw new InternalServerErrorException(
|
||||
'SMS provider rejected the verification code',
|
||||
{
|
||||
cause: providerError,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { AppException, ErrorCode } from '../../common/errors';
|
||||
import { reportHandledFailure } from '../../common/observability/report-failure';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { createHash, randomBytes } from 'crypto';
|
||||
import { UserNotificationType } from '@prisma/client';
|
||||
@@ -232,7 +233,7 @@ export class StaffService {
|
||||
});
|
||||
}
|
||||
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId,
|
||||
type: UserNotificationType.STAFF_INVITE,
|
||||
href: '/staff',
|
||||
@@ -720,7 +721,8 @@ export class StaffService {
|
||||
locale: normalizeEmailLocale(inviter?.language),
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to email invitation link to ${params.email}`, error);
|
||||
// The invite exists and the inviter sees success. The failure must still be visible.
|
||||
reportHandledFailure('invitation-email', error, this.logger);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { Observable } from 'rxjs';
|
||||
import { AppException, ErrorCode } from '../../common/errors';
|
||||
import { reportBackgroundFailure } from '../../common/observability/report-failure';
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
import { isSubscriptionWriteAllowed } from './subscription-write.rules';
|
||||
import { SubscriptionService } from './subscription.service';
|
||||
@@ -24,7 +25,11 @@ export class SubscriptionWriteInterceptor implements NestInterceptor {
|
||||
const method = (request.method ?? 'GET').toUpperCase();
|
||||
const user = request.user;
|
||||
if (user?.id && user.organizationId) {
|
||||
void this.subscriptions.ensureExpiryNotices(user.organizationId).catch(() => undefined);
|
||||
void this.subscriptions
|
||||
.ensureExpiryNotices(user.organizationId)
|
||||
.catch((error: unknown) => {
|
||||
reportBackgroundFailure('seat-expiry-notices', error);
|
||||
});
|
||||
}
|
||||
if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') {
|
||||
return next.handle();
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import {
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { AppException, ErrorCode } from '../../common/errors';
|
||||
import {
|
||||
reportBackgroundFailure,
|
||||
reportHandledFailure,
|
||||
} from '../../common/observability/report-failure';
|
||||
import { CatalogEntityKind, LabCaseActivityType, LabCaseOrigin, LabTaskStatus, Prisma, UserNotificationType } from '@prisma/client';
|
||||
import { PrismaService } from '../../../prisma/prisma.service';
|
||||
import { normalizeMobile } from '../../common/phone';
|
||||
@@ -63,6 +68,8 @@ const CASE_SCOPED_SCAN_STEP_CODE = 'intraoral_scan';
|
||||
|
||||
@Injectable()
|
||||
export class TasksService {
|
||||
private readonly logger = new Logger(TasksService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly catalogLabels: CatalogLabelService,
|
||||
@@ -422,11 +429,13 @@ export class TasksService {
|
||||
});
|
||||
|
||||
for (const notice of updated.debtNotices) {
|
||||
void this.billing.notifyCaseFee(notice).catch(() => undefined);
|
||||
void this.billing.notifyCaseFee(notice).catch((error: unknown) => {
|
||||
reportBackgroundFailure('case-fee-notice', error);
|
||||
});
|
||||
}
|
||||
|
||||
if (updated.caseCompleted) {
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: labOrganizationId,
|
||||
type: UserNotificationType.CASE_COMPLETED,
|
||||
href: `/cases?caseId=${encodeURIComponent(task.labCaseId)}`,
|
||||
@@ -437,7 +446,7 @@ export class TasksService {
|
||||
|
||||
const clinicOrgId = task.labCase?.treatment?.organization?.id;
|
||||
if (clinicOrgId && task.labCase.origin !== LabCaseOrigin.LAB_OUTSOURCE) {
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: clinicOrgId,
|
||||
type: UserNotificationType.CASE_COMPLETED,
|
||||
href: `/treatment?labCaseId=${encodeURIComponent(task.labCaseId)}`,
|
||||
@@ -450,13 +459,19 @@ export class TasksService {
|
||||
|
||||
try {
|
||||
await this.notifyPartnerCaseCompleted(task.labCase, actorUserId);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// The step is already completed. A notice failure must not turn that into a 500.
|
||||
reportHandledFailure(
|
||||
'partner-case-completed-notice',
|
||||
error,
|
||||
this.logger,
|
||||
{ lab_case_id: task.labCaseId },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (const notice of updated.ancestorCompletions) {
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: notice.organizationId,
|
||||
type: UserNotificationType.CASE_COMPLETED,
|
||||
href: `/cases?caseId=${encodeURIComponent(notice.labCaseId)}`,
|
||||
@@ -465,7 +480,7 @@ export class TasksService {
|
||||
requiredPermission: 'TAB_TASKS_READ',
|
||||
});
|
||||
if (notice.clinicOrganizationId) {
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: notice.clinicOrganizationId,
|
||||
type: UserNotificationType.CASE_COMPLETED,
|
||||
href: `/treatment?labCaseId=${encodeURIComponent(notice.labCaseId)}`,
|
||||
@@ -486,8 +501,14 @@ export class TasksService {
|
||||
},
|
||||
null,
|
||||
);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// The parent step is already completed.
|
||||
reportHandledFailure(
|
||||
'parent-case-completed-notice',
|
||||
error,
|
||||
this.logger,
|
||||
{ lab_case_id: notice.labCaseId },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1033,7 +1054,7 @@ export class TasksService {
|
||||
if (!requiredPermission) return;
|
||||
const href = await this.partnerShareHref(labCase.id);
|
||||
if (!href) return;
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: labCase.partnerClinicOrganizationId,
|
||||
type: UserNotificationType.CASE_COMPLETED,
|
||||
href,
|
||||
|
||||
@@ -1232,7 +1232,7 @@ export class TreatmentsService {
|
||||
});
|
||||
|
||||
if (isFirstSend && labCase.destinationOrganizationId) {
|
||||
void this.userNotifications.notify({
|
||||
this.userNotifications.notifyInBackground({
|
||||
organizationId: labCase.destinationOrganizationId,
|
||||
type: UserNotificationType.CASE_SENT,
|
||||
href: `/cases?caseId=${encodeURIComponent(labCaseId)}`,
|
||||
|
||||
@@ -360,7 +360,8 @@ export class VoiceService {
|
||||
: ErrorCode.VOICE_EXTRACT_FAILED;
|
||||
// No details: the transcript used to ride along here for a salvage dialog that was never
|
||||
// built, so it was serialized onto the wire and dropped. It stays on the server now.
|
||||
return new AppException(code, HttpStatus.BAD_GATEWAY);
|
||||
// The cause rides to the error tracker only.
|
||||
return new AppException(code, HttpStatus.BAD_GATEWAY, undefined, error);
|
||||
}
|
||||
|
||||
/** Structured and patient-free: never the transcript, never audio, never a patient id. */
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
WebSocketServer,
|
||||
} from '@nestjs/websockets';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { reportHandledFailure } from '../common/observability/report-failure';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Server, Socket } from 'socket.io';
|
||||
@@ -62,6 +63,15 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection {
|
||||
client.data.organizationId = payload.organizationId;
|
||||
} catch (error) {
|
||||
this.logger.debug(`Realtime auth failed: ${String(error)}`);
|
||||
// An expired or malformed token is expected. Anything else (for example a database failure) is not.
|
||||
const isTokenError =
|
||||
error instanceof Error &&
|
||||
(error.name === 'JsonWebTokenError' ||
|
||||
error.name === 'TokenExpiredError' ||
|
||||
error.name === 'NotBeforeError');
|
||||
if (!isTokenError) {
|
||||
reportHandledFailure('realtime-connection', error, this.logger);
|
||||
}
|
||||
client.disconnect(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,11 @@ ARG NEXT_PUBLIC_APP_URL
|
||||
ARG NEXT_PUBLIC_APP_NAME
|
||||
ARG NEXT_PUBLIC_SENTRY_DSN
|
||||
ARG NEXT_PUBLIC_SENTRY_ENVIRONMENT
|
||||
# Source maps and release name, used at build time only (upload to GlitchTip). See next.config.ts.
|
||||
ARG SENTRY_AUTH_TOKEN
|
||||
ARG SENTRY_ORG
|
||||
ARG SENTRY_PROJECT
|
||||
ARG SENTRY_RELEASE
|
||||
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
ENV NODE_ENV=production
|
||||
|
||||
@@ -560,7 +560,7 @@
|
||||
"sendToExocad": "Send to Exocad",
|
||||
"sendToExocadSaved": "Exported {fileName}. DentalDB will import it from the Auto-Import folder.",
|
||||
"sendToExocadSavedWithFolder": "Exported {fileName} to {folder}. DentalDB will import it from that Auto-Import folder.",
|
||||
"sendToExocadSkipped": "Not exported: {lines}.",
|
||||
"sendToExocadSkipped": "File exported. Exocad has no match for: {lines}. Set those in DentalDB if needed.",
|
||||
"sendToExocadConnectTitle": "Choose Exocad Auto-Import folder",
|
||||
"sendToExocadChangeFolderTitle": "Change Exocad Auto-Import folder",
|
||||
"sendToExocadFolderHint": "Select the Project Auto-Import folder configured in DentalDB. The next export reuses that folder when it is still available.",
|
||||
|
||||
@@ -560,7 +560,7 @@
|
||||
"sendToExocad": "ارسال به Exocad",
|
||||
"sendToExocadSaved": "پرونده {fileName} صادر شد. DentalDB آن را از پوشه Auto-Import وارد میکند.",
|
||||
"sendToExocadSavedWithFolder": "پرونده {fileName} در {folder} صادر شد. DentalDB آن را از همان پوشه Auto-Import وارد میکند.",
|
||||
"sendToExocadSkipped": "صادر نشد: {lines}.",
|
||||
"sendToExocadSkipped": "پرونده صادر شد. اکزوکد معادلی برای این موارد ندارد: {lines}. در صورت نیاز در DentalDB تنظیم کنید.",
|
||||
"sendToExocadConnectTitle": "انتخاب پوشه Auto-Import اکزوکد",
|
||||
"sendToExocadChangeFolderTitle": "تغییر پوشه Auto-Import اکزوکد",
|
||||
"sendToExocadFolderHint": "پوشه Project Auto-Import تنظیمشده در DentalDB را انتخاب کنید. ارسال بعدی در صورت در دسترس بودن همان پوشه را دوباره استفاده میکند.",
|
||||
|
||||
@@ -560,7 +560,7 @@
|
||||
"sendToExocad": "Naar Exocad sturen",
|
||||
"sendToExocadSaved": "{fileName} geëxporteerd. DentalDB importeert dit vanuit de Auto-Import-map.",
|
||||
"sendToExocadSavedWithFolder": "{fileName} geëxporteerd naar {folder}. DentalDB importeert dit vanuit die Auto-Import-map.",
|
||||
"sendToExocadSkipped": "Niet geëxporteerd: {lines}.",
|
||||
"sendToExocadSkipped": "Bestand geëxporteerd. Exocad heeft geen match voor: {lines}. Stel dit indien nodig in DentalDB in.",
|
||||
"sendToExocadConnectTitle": "Exocad Auto-Import-map kiezen",
|
||||
"sendToExocadChangeFolderTitle": "Exocad Auto-Import-map wijzigen",
|
||||
"sendToExocadFolderHint": "Selecteer de Project Auto-Import-map die in DentalDB is geconfigureerd. De volgende export hergebruikt die map wanneer die nog beschikbaar is.",
|
||||
|
||||
@@ -45,6 +45,11 @@ const nextConfig: NextConfig = {
|
||||
|
||||
export default withSentryConfig(withNextIntl(nextConfig), {
|
||||
silent: true,
|
||||
sourcemaps: { disable: true },
|
||||
disableLogger: true,
|
||||
// GlitchTip. The upload needs SENTRY_AUTH_TOKEN, SENTRY_ORG and SENTRY_PROJECT.
|
||||
sentryUrl: process.env.SENTRY_URL || 'https://errors.wixur.ir',
|
||||
telemetry: false,
|
||||
errorHandler: (error) => {
|
||||
// A failed upload must not stop a deploy.
|
||||
console.warn(`[@sentry/nextjs] ${error.message}`);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -15,7 +15,10 @@ export default function LocaleError({
|
||||
const t = useTranslations('common');
|
||||
|
||||
useEffect(() => {
|
||||
Sentry.captureException(error);
|
||||
// An error with a digest was already sent by the server (onRequestError).
|
||||
if (!error.digest) {
|
||||
Sentry.captureException(error);
|
||||
}
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -11,7 +11,10 @@ export default function GlobalError({
|
||||
reset: () => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
Sentry.captureException(error);
|
||||
// An error with a digest was already sent by the server (onRequestError).
|
||||
if (!error.digest) {
|
||||
Sentry.captureException(error);
|
||||
}
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -96,14 +96,21 @@ describe('buildExocadDentalProject', () => {
|
||||
expect(project.xml).toContain('<PatientFirstName>John</PatientFirstName>');
|
||||
expect(project.xml).toContain('<Notes>Please check occlusion</Notes>');
|
||||
expect(project.xml).toContain('<Number>16</Number>');
|
||||
expect(project.xml).toContain('<ReconstructionType>Coping</ReconstructionType>');
|
||||
expect(project.xml).toContain('<Material>ZI</Material>');
|
||||
expect(project.xml).toContain('<Material>NP</Material>');
|
||||
expect(project.xml).toContain('<ReconstructionType>AnatomicCrown</ReconstructionType>');
|
||||
expect(project.xml).toContain('<ReconstructionType>Coping</ReconstructionType>');
|
||||
expect(project.xml).toContain('<Material>LS2</Material>');
|
||||
expect(project.xml).toContain('<ToothShade>VCL:A2</ToothShade>');
|
||||
expect(project.xml).toContain('<ImplantType>None</ImplantType>');
|
||||
expect(project.xml).not.toContain('Antagonist');
|
||||
// Monolithic is full-contour (AnatomicCrown); PFM is cutback (Coping).
|
||||
expect(project.xml).toMatch(
|
||||
/<Number>16<\/Number>\s*<ReconstructionType>AnatomicCrown<\/ReconstructionType>[\s\S]*?<Material>ZI<\/Material>/,
|
||||
);
|
||||
expect(project.xml).toMatch(
|
||||
/<Number>26<\/Number>\s*<ReconstructionType>Coping<\/ReconstructionType>[\s\S]*?<Material>NP<\/Material>/,
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the export date for the file name, not the due date', () => {
|
||||
@@ -211,18 +218,38 @@ describe('buildExocadDentalProject', () => {
|
||||
expect(screw.xml).not.toContain('MaterialAbutment');
|
||||
});
|
||||
|
||||
it('omits ImplantType None when an unmapped implant stack is present and lists it as skipped', () => {
|
||||
it('maps prefabricated, Ti-base, and multi-unit abutments as CustomAbutment/TI', () => {
|
||||
for (const code of [
|
||||
'prefabricated_abutment',
|
||||
'ti_base_abutment',
|
||||
'multi_unit_abutment',
|
||||
] as const) {
|
||||
const project = buildExocadDentalProject(
|
||||
baseInput({
|
||||
teeth: [
|
||||
{ tooth: '14', prosthesisTypeCode: 'pfz_crown' },
|
||||
{ tooth: '14', prosthesisTypeCode: code },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(project.skipped).toEqual([]);
|
||||
expect(project.xml).toContain('<ImplantType>CustomAbutment</ImplantType>');
|
||||
expect(project.xml).toContain('<MaterialAbutment>TI</MaterialAbutment>');
|
||||
}
|
||||
});
|
||||
|
||||
it('omits ImplantType None when an unmapped post-and-core stack is present and lists it as skipped', () => {
|
||||
const project = buildExocadDentalProject(
|
||||
baseInput({
|
||||
teeth: [
|
||||
{ tooth: '16', prosthesisTypeCode: 'pfz_crown' },
|
||||
{ tooth: '16', prosthesisTypeCode: 'ti_base_abutment' },
|
||||
{ tooth: '16', prosthesisTypeCode: 'cast_post_core' },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(project.xml).not.toContain('<ImplantType>');
|
||||
expect(project.skipped).toEqual([
|
||||
{ tooth: '16', prosthesisTypeCode: 'ti_base_abutment', reason: 'unmapped' },
|
||||
{ tooth: '16', prosthesisTypeCode: 'cast_post_core', reason: 'unmapped' },
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
/**
|
||||
* Build an official Exocad `.dentalProject` XML file (3rd-party auto-import).
|
||||
* Prosthesis → ReconstructionType / Material pairs follow the prior DentalDB mapping
|
||||
* where those values appear in the official specification tables.
|
||||
*
|
||||
* Source of truth for allowed XML values: exocad’s
|
||||
* `.dentalProject` 3rd-party specification (Tables 2–4). Dyolink catalog codes are
|
||||
* mapped onto those values by the PDF definitions (e.g. full-contour → AnatomicCrown,
|
||||
* cutback framework → Coping). Older DentalDB reverse-engineering is kept only when
|
||||
* it does not contradict those tables.
|
||||
*/
|
||||
|
||||
export type ExocadExportFailure = 'PATIENT_NAME_INCOMPLETE' | 'NOTHING_TO_EXPORT';
|
||||
@@ -19,12 +23,13 @@ type MaterialMatch = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Catalog codes with one obvious Exocad work type and material.
|
||||
* OverlayCrown is not in the official 3rd-party ReconstructionType table, so overlays
|
||||
* use AnatomicInlay. Active indirect leaves use Veneer / AnatomicInlay / OffsetInlay.
|
||||
* Catalog → ReconstructionType / Material (PDF Tables 2–3).
|
||||
* - Full-contour crowns → AnatomicCrown; cutback frameworks (PFZ/PFM) → Coping.
|
||||
* - OverlayCrown is outside Table 2, so overlays use AnatomicInlay / OffsetInlay.
|
||||
* - Active indirect leaves use Veneer / AnatomicInlay / OffsetInlay.
|
||||
*/
|
||||
const MATERIAL_MATCH: Record<string, MaterialMatch> = {
|
||||
monolithic_zirconia: { reconstructionType: 'Coping', material: 'ZI' },
|
||||
monolithic_zirconia: { reconstructionType: 'AnatomicCrown', material: 'ZI' },
|
||||
pfz_crown: { reconstructionType: 'Coping', material: 'ZI' },
|
||||
pfm_crown: { reconstructionType: 'Coping', material: 'NP' },
|
||||
full_metal_crown: { reconstructionType: 'AnatomicCrown', material: 'NP' },
|
||||
@@ -55,27 +60,30 @@ type ImplantMatch = {
|
||||
materialAbutment?: string;
|
||||
};
|
||||
|
||||
/** Implant stacks we can express with official ImplantType / MaterialAbutment values. */
|
||||
/**
|
||||
* Implant stacks → PDF Table 4 ImplantType (and MaterialAbutment when CustomAbutment).
|
||||
* Table 4 only lists None / CustomAbutment / WithoutAbutment. DentalDB’s separate
|
||||
* “On stock abutment” UI option is not writable here, so stock / Ti-base / multi-unit
|
||||
* abutments use CustomAbutment + TI — the only Table 4 value that means implant with
|
||||
* abutment (sample tooth 33 in the PDF uses the same pair).
|
||||
*/
|
||||
const IMPLANT_MATCH: Record<string, ImplantMatch> = {
|
||||
customized_abutment: { implantType: 'CustomAbutment', materialAbutment: 'TI' },
|
||||
zirconia_abutment: { implantType: 'CustomAbutment', materialAbutment: 'ZI' },
|
||||
prefabricated_abutment: { implantType: 'CustomAbutment', materialAbutment: 'TI' },
|
||||
ti_base_abutment: { implantType: 'CustomAbutment', materialAbutment: 'TI' },
|
||||
multi_unit_abutment: { implantType: 'CustomAbutment', materialAbutment: 'TI' },
|
||||
screw_retained: { implantType: 'WithoutAbutment' },
|
||||
};
|
||||
|
||||
/**
|
||||
* Implant / post stacks that are not representable in the official ImplantType table.
|
||||
* When present with a restoration, they are listed as skipped and ImplantType is omitted
|
||||
* (never written as None — that would claim a natural prep).
|
||||
* Stacks with no ReconstructionType / ImplantType in the official tables.
|
||||
* When present with a restoration they are listed as skipped and ImplantType is
|
||||
* omitted (never written as None — that would claim a natural prep).
|
||||
*/
|
||||
const UNMAPPED_STACK_CODES = new Set([
|
||||
'ti_base_abutment',
|
||||
'prefabricated_abutment',
|
||||
'multi_unit_abutment',
|
||||
'cast_post_core',
|
||||
'fiber_post_core',
|
||||
]);
|
||||
const UNMAPPED_STACK_CODES = new Set(['cast_post_core', 'fiber_post_core']);
|
||||
|
||||
/** Reconstruction types that may carry ImplantType in the official table. */
|
||||
/** Reconstruction types that may carry ImplantType (PDF Table 2 “yes” column). */
|
||||
const IMPLANT_ALLOWED = new Set([
|
||||
'AnatomicCrown',
|
||||
'AnatomicWaxup',
|
||||
@@ -83,7 +91,6 @@ const IMPLANT_ALLOWED = new Set([
|
||||
'Coping',
|
||||
'OverpressCrown',
|
||||
'PrimaryTelescope',
|
||||
'ProvisionalCrown',
|
||||
'ReducedWaxup',
|
||||
]);
|
||||
|
||||
@@ -310,8 +317,8 @@ function planTeeth(jobs: ExocadToothJob[]): { writes: ToothWrite[]; skipped: Exo
|
||||
let materialAbutment: string | undefined;
|
||||
if (allowImplant) {
|
||||
if (implant.implantType === 'None') {
|
||||
// Natural prep: only Coping historically always carried an explicit None.
|
||||
implantType = mapped.reconstructionType === 'Coping' ? 'None' : null;
|
||||
// Natural prep on an implant-capable type (PDF Example II sets None explicitly).
|
||||
implantType = 'None';
|
||||
} else if (implant.implantType) {
|
||||
implantType = implant.implantType;
|
||||
materialAbutment = implant.materialAbutment;
|
||||
|
||||
52
frontend/src/components/shared/formatApiError.spec.ts
Normal file
52
frontend/src/components/shared/formatApiError.spec.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { AxiosError } from 'axios';
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { getUserFacingError } from './formatApiError';
|
||||
|
||||
vi.mock('@sentry/nextjs', () => ({ captureException: vi.fn() }));
|
||||
|
||||
const captureException = vi.mocked(Sentry.captureException);
|
||||
|
||||
const t = (key: string) => `errors.${key}`;
|
||||
|
||||
describe('getUserFacingError', () => {
|
||||
beforeEach(() => {
|
||||
captureException.mockClear();
|
||||
});
|
||||
|
||||
it('given a coded API error, when getUserFacingError runs, then the text of the code is returned and nothing is reported', () => {
|
||||
const message = getUserFacingError({ statusCode: 409, code: 'CONFLICT' }, t, 'Fallback');
|
||||
|
||||
expect(message).toBe('errors.CONFLICT');
|
||||
expect(captureException).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('given a lost connection, when getUserFacingError runs, then the network text is returned', () => {
|
||||
expect(getUserFacingError({ statusCode: 0, code: 'NETWORK_ERROR' }, t, 'Fallback')).toBe('errors.NETWORK_ERROR');
|
||||
expect(getUserFacingError(new Error('Network Error'), t, 'Fallback')).toBe('errors.NETWORK_ERROR');
|
||||
});
|
||||
|
||||
it('given a timeout, when getUserFacingError runs, then the timeout text is returned', () => {
|
||||
expect(getUserFacingError(new Error('timeout of 10000ms exceeded'), t, 'Fallback')).toBe('errors.TIMEOUT');
|
||||
});
|
||||
|
||||
it('given the same bug twice, when getUserFacingError runs, then the fallback text is returned and the bug is reported once', () => {
|
||||
const bug = new TypeError("Cannot read properties of undefined (reading 'id')");
|
||||
|
||||
expect(getUserFacingError(bug, t, 'cases.errorLoadList')).toBe('cases.errorLoadList');
|
||||
expect(getUserFacingError(bug, t, 'cases.errorLoadList')).toBe('cases.errorLoadList');
|
||||
|
||||
expect(captureException).toHaveBeenCalledTimes(1);
|
||||
expect(captureException.mock.calls[0]?.[0]).toBe(bug);
|
||||
});
|
||||
|
||||
it('given an axios error, when getUserFacingError runs, then nothing is reported', () => {
|
||||
getUserFacingError(new AxiosError('Request failed with status code 500'), t, 'Fallback');
|
||||
|
||||
expect(captureException).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('given no error, when getUserFacingError runs, then the generic text is returned', () => {
|
||||
expect(getUserFacingError(undefined, t)).toBe('errors.GENERIC');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { asApiError, isApiError, type ApiError, type ApiErrorDetail } from '@/types/api';
|
||||
import { reportUnexpectedError } from '@/lib/error-tracking/reportUnexpectedError';
|
||||
|
||||
type TranslateFn = (key: string) => string;
|
||||
|
||||
@@ -76,6 +77,10 @@ export function getUserFacingError(
|
||||
): string {
|
||||
const apiError = asApiError(err) ?? normalizeLegacyError(err);
|
||||
|
||||
// Not an API failure: a bug. Report it before the caller drops it.
|
||||
if (!apiError) {
|
||||
reportUnexpectedError(err);
|
||||
}
|
||||
if (apiError?.code === 'VALIDATION_FAILED' && apiError.details?.length) {
|
||||
const validationMessage = formatValidationDetails(apiError.details, t);
|
||||
if (validationMessage) {
|
||||
|
||||
@@ -16,6 +16,7 @@ import { labTaskStatusVariant } from '@/components/lab/labTaskStatusDisplay';
|
||||
import { LabCaseDueDateBadge } from '@/components/lab/LabCaseDueDateBadge';
|
||||
import { LabCaseOriginBadge } from '@/components/ui/lab/LabCaseOriginBadge';
|
||||
import { ProsthesisJobLineLabel } from '@/components/ui/lab/ProsthesisJobLineLabel';
|
||||
import { prosthesisJobPathLabel } from '@/components/treatment/prosthesisJobPath';
|
||||
import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog';
|
||||
import {
|
||||
buildCaseLinkedEdges,
|
||||
@@ -311,6 +312,7 @@ export function CaseDetailPanel({
|
||||
const tComments = useTranslations('caseComments');
|
||||
const tErrors = useTranslations('errors');
|
||||
const tCommon = useTranslations('common');
|
||||
const tProsthesis = useTranslations('prosthesis');
|
||||
const intlLocale = useLocale();
|
||||
const { settings: currencySettings } = useBillingCurrency(true);
|
||||
const { currentOrganization } = useAuth();
|
||||
@@ -494,7 +496,10 @@ export function CaseDetailPanel({
|
||||
toast.showInfo(
|
||||
t('sendToExocadSkipped', {
|
||||
lines: project.skipped
|
||||
.map((line) => `${line.tooth} ${line.prosthesisTypeCode}`)
|
||||
.map(
|
||||
(line) =>
|
||||
`${line.tooth} ${prosthesisJobPathLabel(line.prosthesisTypeCode, prosthesisCatalog, (key) => tProsthesis(key as never))}`,
|
||||
)
|
||||
.join(', '),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
ResponsiveDialogPanel,
|
||||
} from '@/components/ui/shared/ResponsiveDialog';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { getUserFacingError } from '@/components/shared/formatApiError';
|
||||
import { useToast } from '@/lib/hooks/useToast';
|
||||
import type { LabCaseAttachmentMeta } from '@/types/cases';
|
||||
|
||||
interface LabCaseAttachmentsDialogProps {
|
||||
@@ -136,6 +138,8 @@ export function LabCaseAttachmentsDialog({
|
||||
loadBlob,
|
||||
}: LabCaseAttachmentsDialogProps) {
|
||||
const t = useTranslations('cases');
|
||||
const tErrors = useTranslations('errors');
|
||||
const toast = useToast();
|
||||
|
||||
const sortedAttachments = [...attachments].sort(
|
||||
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
|
||||
@@ -155,10 +159,13 @@ export function LabCaseAttachmentsDialog({
|
||||
const blob = await loadBlob(caseId, attachment.id);
|
||||
downloadBlob(blob, attachment.fileName);
|
||||
}
|
||||
} catch (error) {
|
||||
// "Download all" must not fail silently.
|
||||
toast.showError(getUserFacingError(error, tErrors));
|
||||
} finally {
|
||||
setDownloadingAll(false);
|
||||
}
|
||||
}, [caseId, loadBlob, sortedAttachments]);
|
||||
}, [caseId, loadBlob, sortedAttachments, tErrors, toast]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
|
||||
@@ -148,7 +148,10 @@ export function OrganizationSelectorContent() {
|
||||
{organizations.map((org) => (
|
||||
<button
|
||||
key={org.id}
|
||||
onClick={() => selectOrganization(org.id)}
|
||||
// apiError is set and rendered above.
|
||||
onClick={() => {
|
||||
void selectOrganization(org.id).catch(() => undefined);
|
||||
}}
|
||||
className="surface-card p-4 sm:p-6 transition-all text-left flex items-center gap-3 sm:gap-4 hover:border-primary/60 w-full min-w-0"
|
||||
>
|
||||
<div className="p-2.5 sm:p-3 bg-primary-soft rounded-[var(--radius-sm)] text-primary shrink-0">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useRef, useState } from 'react';
|
||||
import { reportUnexpectedError } from '@/lib/error-tracking/reportUnexpectedError';
|
||||
|
||||
type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'danger' | 'ghost';
|
||||
type ButtonSize = 'sm' | 'md' | 'lg';
|
||||
@@ -77,10 +78,15 @@ export const Button: React.FC<ButtonProps> = ({
|
||||
if (result != null && typeof (result as Promise<void>).then === 'function') {
|
||||
autoPendingRef.current = true;
|
||||
setAutoPending(true);
|
||||
void Promise.resolve(result).finally(() => {
|
||||
autoPendingRef.current = false;
|
||||
setAutoPending(false);
|
||||
});
|
||||
void Promise.resolve(result)
|
||||
// A rejected handler would be an unhandled rejection.
|
||||
.catch((error: unknown) => {
|
||||
reportUnexpectedError(error);
|
||||
})
|
||||
.finally(() => {
|
||||
autoPendingRef.current = false;
|
||||
setAutoPending(false);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -29,10 +29,13 @@ export function DetailLabCaseCommentsSection({
|
||||
}: DetailLabCaseCommentsSectionProps) {
|
||||
useEffect(() => {
|
||||
if (!labCaseId) return;
|
||||
void notificationsApi.markCaseRead(labCaseId).then(() => {
|
||||
notifyTabBadgesChanged();
|
||||
onMarkRead?.(labCaseId);
|
||||
});
|
||||
void notificationsApi.markCaseRead(labCaseId)
|
||||
.then(() => {
|
||||
notifyTabBadgesChanged();
|
||||
onMarkRead?.(labCaseId);
|
||||
})
|
||||
// Best effort: not an unhandled rejection.
|
||||
.catch(() => undefined);
|
||||
}, [labCaseId, onMarkRead]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -28,11 +28,14 @@ export function LabCaseTrackerCard({
|
||||
|
||||
useEffect(() => {
|
||||
if (!expanded || !summary.hasUnread) return;
|
||||
void notificationsApi.markCaseRead(summary.labCaseId).then(() => {
|
||||
notifyTabBadgesChanged();
|
||||
onSummaryChange?.({ ...summary, hasUnread: false });
|
||||
onMarkedRead?.(summary.labCaseId);
|
||||
});
|
||||
void notificationsApi.markCaseRead(summary.labCaseId)
|
||||
.then(() => {
|
||||
notifyTabBadgesChanged();
|
||||
onSummaryChange?.({ ...summary, hasUnread: false });
|
||||
onMarkedRead?.(summary.labCaseId);
|
||||
})
|
||||
// Best effort: not an unhandled rejection.
|
||||
.catch(() => undefined);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- mark read once per expand
|
||||
}, [expanded, summary.labCaseId, summary.hasUnread, onSummaryChange, onMarkedRead]);
|
||||
|
||||
|
||||
@@ -1802,7 +1802,8 @@ export function TreatmentWorkspace({
|
||||
isDetailsDirty(detailsRef.current, savedSnapshotRef.current) ||
|
||||
isLabCasesDirty(labCaseDraftsRef.current, savedLabCasesSnapshotRef.current)
|
||||
) {
|
||||
void runDraftSave();
|
||||
// runDraftSave already shows the toast.
|
||||
void runDraftSave().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1855,7 +1856,8 @@ export function TreatmentWorkspace({
|
||||
if (autosaveTimerRef.current) clearTimeout(autosaveTimerRef.current);
|
||||
autosaveTimerRef.current = setTimeout(() => {
|
||||
autosaveTimerRef.current = null;
|
||||
void runDraftSave();
|
||||
// runDraftSave already shows the toast.
|
||||
void runDraftSave().catch(() => undefined);
|
||||
}, AUTOSAVE_DEBOUNCE_MS);
|
||||
|
||||
return () => {
|
||||
|
||||
@@ -99,6 +99,16 @@ apiClient.interceptors.response.use(
|
||||
| { message?: string | string[] }
|
||||
| undefined;
|
||||
|
||||
// No response: the server was not reached. Say so, instead of "something went wrong on our end".
|
||||
if (!error.response) {
|
||||
const timedOut = error.code === AxiosError.ETIMEDOUT || error.code === AxiosError.ECONNABORTED;
|
||||
const networkError: ApiError = {
|
||||
statusCode: 0,
|
||||
code: timedOut ? 'TIMEOUT' : 'NETWORK_ERROR',
|
||||
};
|
||||
return Promise.reject(networkError);
|
||||
}
|
||||
|
||||
if (responseData && 'error' in responseData && responseData.error?.code) {
|
||||
const apiError: ApiError = {
|
||||
statusCode: responseData.error.statusCode ?? error.response?.status ?? 500,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { AxiosError, CanceledError, type InternalAxiosRequestConfig } from 'axios';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import { reportUnexpectedApiFailure } from './reportUnexpectedApiFailure';
|
||||
|
||||
vi.mock('@sentry/nextjs', () => ({ captureException: vi.fn() }));
|
||||
|
||||
const captureException = vi.mocked(Sentry.captureException);
|
||||
|
||||
const config = (method: string, url: string) => ({ method, url }) as InternalAxiosRequestConfig;
|
||||
|
||||
function axiosError(status: number | undefined, data?: unknown, code = AxiosError.ERR_BAD_RESPONSE) {
|
||||
return new AxiosError('Request failed', code, config('get', '/cases'), undefined, data === undefined && status === undefined ? undefined : ({ status, data } as never));
|
||||
}
|
||||
|
||||
function backendError(status: number) {
|
||||
return axiosError(status, { success: false, error: { code: 'INTERNAL_ERROR', statusCode: status } });
|
||||
}
|
||||
|
||||
describe('reportUnexpectedApiFailure', () => {
|
||||
beforeEach(() => {
|
||||
captureException.mockClear();
|
||||
});
|
||||
|
||||
it('given a 5xx that the backend filter produced, when the failure is reported, then no event is sent', () => {
|
||||
reportUnexpectedApiFailure(backendError(500));
|
||||
|
||||
expect(captureException).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('given a 4xx, when the failure is reported, then no event is sent', () => {
|
||||
reportUnexpectedApiFailure(backendError(409));
|
||||
|
||||
expect(captureException).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('given a canceled request, when the failure is reported, then no event is sent', () => {
|
||||
reportUnexpectedApiFailure(new CanceledError('canceled'));
|
||||
|
||||
expect(captureException).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('given a request with no response, when the failure is reported, then one event names the endpoint as unreachable', () => {
|
||||
const error = new AxiosError('Network Error', AxiosError.ERR_NETWORK, config('post', '/cases'), undefined, undefined);
|
||||
|
||||
reportUnexpectedApiFailure(error);
|
||||
|
||||
const [reported, context] = captureException.mock.calls[0] as [Error, { tags: Record<string, string> }];
|
||||
expect(reported.message).toBe('API unreachable (network): POST /cases');
|
||||
expect(reported.cause).toBe(error);
|
||||
expect(context.tags).toEqual({ failure_kind: 'network', api_status: 'network', api_endpoint: 'POST /cases' });
|
||||
});
|
||||
|
||||
it('given a request that timed out, when the failure is reported, then the event says timeout', () => {
|
||||
const error = new AxiosError('timeout of 10000ms exceeded', AxiosError.ECONNABORTED, config('get', '/patients'), undefined, undefined);
|
||||
|
||||
reportUnexpectedApiFailure(error);
|
||||
|
||||
const [reported] = captureException.mock.calls[0] as [Error];
|
||||
expect(reported.message).toBe('API unreachable (timeout): GET /patients');
|
||||
});
|
||||
|
||||
it('given a 5xx without a backend error body, when the failure is reported, then one event names the status and the endpoint', () => {
|
||||
reportUnexpectedApiFailure(axiosError(502, '<html>502 Bad Gateway</html>'));
|
||||
|
||||
const [reported, context] = captureException.mock.calls[0] as [Error, { tags: Record<string, string> }];
|
||||
expect(reported.message).toBe('API answered 502 without a backend error: GET /cases');
|
||||
expect(context.tags.api_status).toBe('502');
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,43 @@
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import type { AxiosError } from 'axios';
|
||||
import axios, { AxiosError } from 'axios';
|
||||
|
||||
/** Report network failures and HTTP 5xx only — not coded 4xx AppExceptions. */
|
||||
/** The backend filter answers each failure with `{ success: false, error: { code } }`. */
|
||||
function isBackendErrorResponse(data: unknown): boolean {
|
||||
return (
|
||||
typeof data === 'object' &&
|
||||
data !== null &&
|
||||
typeof (data as { error?: { code?: unknown } }).error?.code === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
function isTimeout(error: AxiosError): boolean {
|
||||
return error.code === AxiosError.ETIMEDOUT || error.code === AxiosError.ECONNABORTED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports only the API failures that no backend event covers: no response (network, timeout),
|
||||
* or a 5xx without a backend error body. The backend filter owns each 5xx that it produced.
|
||||
*/
|
||||
export function reportUnexpectedApiFailure(error: AxiosError): void {
|
||||
const status = error.response?.status;
|
||||
if (status !== undefined && status < 500) {
|
||||
if (axios.isCancel(error)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Sentry.captureException(error, {
|
||||
tags: {
|
||||
api_status: status ? String(status) : 'network',
|
||||
},
|
||||
extra: {
|
||||
url: error.config?.url,
|
||||
method: error.config?.method,
|
||||
},
|
||||
const endpoint = `${(error.config?.method ?? 'get').toUpperCase()} ${error.config?.url ?? '(unknown url)'}`;
|
||||
const status = error.response?.status;
|
||||
|
||||
if (status !== undefined) {
|
||||
if (status < 500 || isBackendErrorResponse(error.response?.data)) {
|
||||
return;
|
||||
}
|
||||
Sentry.captureException(new Error(`API answered ${status} without a backend error: ${endpoint}`, { cause: error }), {
|
||||
tags: { failure_kind: 'no-backend-error', api_status: String(status), api_endpoint: endpoint },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const kind = isTimeout(error) ? 'timeout' : 'network';
|
||||
Sentry.captureException(new Error(`API unreachable (${kind}): ${endpoint}`, { cause: error }), {
|
||||
tags: { failure_kind: kind, api_status: kind, api_endpoint: endpoint },
|
||||
});
|
||||
}
|
||||
|
||||
16
frontend/src/lib/error-tracking/reportUnexpectedError.ts
Normal file
16
frontend/src/lib/error-tracking/reportUnexpectedError.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
|
||||
const reportedErrors = new WeakSet<object>();
|
||||
|
||||
/** Reports a bug (an error that is not an API failure) once per error object. */
|
||||
export function reportUnexpectedError(err: unknown): void {
|
||||
if (!(err instanceof Error) || reportedErrors.has(err)) {
|
||||
return;
|
||||
}
|
||||
// API failures belong to the interceptor and to the backend.
|
||||
if ((err as { isAxiosError?: boolean }).isAxiosError) {
|
||||
return;
|
||||
}
|
||||
reportedErrors.add(err);
|
||||
Sentry.captureException(err, { tags: { handled: 'frontend-catch' } });
|
||||
}
|
||||
76
frontend/src/lib/error-tracking/sentrySharedOptions.spec.ts
Normal file
76
frontend/src/lib/error-tracking/sentrySharedOptions.spec.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import type { Breadcrumb, ErrorEvent } from '@sentry/core';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { scrubUrl, sentrySharedOptions } from './sentrySharedOptions';
|
||||
|
||||
describe('sentrySharedOptions', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe('scrubUrl', () => {
|
||||
it('given a page URL with a query string and a hash, when scrubUrl runs, then only the path stays', () => {
|
||||
expect(scrubUrl('https://app/billing?partyName=John&partyId=1#top')).toBe('https://app/billing');
|
||||
});
|
||||
|
||||
it('given the URL of the lab case share page, when scrubUrl runs, then the token is masked', () => {
|
||||
expect(scrubUrl('https://app/en/lab-case/abc123')).toBe('https://app/en/lab-case/[token]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('beforeSend', () => {
|
||||
const makeEvent = () =>
|
||||
({
|
||||
transaction: '/lab-case/abc123',
|
||||
request: {
|
||||
url: 'https://app/billing?partyName=John',
|
||||
cookies: { accessToken: 'JWT' },
|
||||
data: '{"password":"x"}',
|
||||
headers: { cookie: 'a=b', authorization: 'Bearer x', accept: 'text/html' },
|
||||
},
|
||||
user: { id: 'u1', email: 'a@b.co', ip_address: '203.0.113.9', username: 'amin' },
|
||||
}) as unknown as ErrorEvent;
|
||||
|
||||
it('given an event with cookies, body, query string, and user contact data, when beforeSend runs, then that data is gone', () => {
|
||||
const result = sentrySharedOptions().beforeSend(makeEvent());
|
||||
|
||||
expect(result?.request).toEqual({ url: 'https://app/billing', headers: { accept: 'text/html' } });
|
||||
expect(result?.user).toEqual({ id: 'u1' });
|
||||
});
|
||||
|
||||
it('given a route name with a share-link token, when beforeSend runs, then the token is masked', () => {
|
||||
const result = sentrySharedOptions().beforeSend(makeEvent());
|
||||
|
||||
expect(result?.transaction).toBe('/lab-case/[token]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('beforeBreadcrumb', () => {
|
||||
it('given a request breadcrumb with a query string in its URL, when it is filtered, then the query string is gone', () => {
|
||||
const breadcrumb = { category: 'xhr', level: 'info', data: { url: '/api/patients?q=john' } } as Breadcrumb;
|
||||
|
||||
sentrySharedOptions().beforeBreadcrumb(breadcrumb);
|
||||
|
||||
expect(breadcrumb.data).toEqual({ url: '/api/patients' });
|
||||
});
|
||||
|
||||
it('given console output of level log in production, when it is filtered, then it is dropped', () => {
|
||||
vi.stubEnv('NODE_ENV', 'production');
|
||||
|
||||
expect(sentrySharedOptions().beforeBreadcrumb({ category: 'console', level: 'log', message: 'x' })).toBeNull();
|
||||
});
|
||||
|
||||
it('given console output of level log outside production, when it is filtered, then it stays', () => {
|
||||
vi.stubEnv('NODE_ENV', 'development');
|
||||
|
||||
expect(sentrySharedOptions().beforeBreadcrumb({ category: 'console', level: 'log', message: 'x' })).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('given the shared options, when they are built, then no tracing option and no session replay is set', () => {
|
||||
const options = sentrySharedOptions();
|
||||
|
||||
expect(options).not.toHaveProperty('tracesSampleRate');
|
||||
expect(options.sendDefaultPii).toBe(false);
|
||||
expect(options.replaysOnErrorSampleRate).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,22 +1,42 @@
|
||||
import type { ErrorEvent } from '@sentry/core';
|
||||
import type { Breadcrumb, ErrorEvent } from '@sentry/core';
|
||||
|
||||
/** Path prefixes whose next segment is a secret token (the lab case share page). */
|
||||
const TOKEN_PATH_PREFIXES = ['/lab-case/'];
|
||||
|
||||
const TOKEN_PATH_PATTERNS = TOKEN_PATH_PREFIXES.map(
|
||||
(prefix) => new RegExp(`(${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})[^/?#]+`, 'g'),
|
||||
);
|
||||
|
||||
export function scrubUrl(url: string): string {
|
||||
const [path] = url.split(/[?#]/);
|
||||
return TOKEN_PATH_PATTERNS.reduce((value, pattern) => value.replace(pattern, '$1[token]'), path);
|
||||
}
|
||||
|
||||
/** Shared Sentry/GlitchTip options — no session replay, no PII in payloads. */
|
||||
export function sentrySharedOptions() {
|
||||
return {
|
||||
sendDefaultPii: false as const,
|
||||
tracesSampleRate: 0,
|
||||
replaysSessionSampleRate: 0,
|
||||
replaysOnErrorSampleRate: 0,
|
||||
// No tracesSampleRate here: without it no tracing code loads, and errors still share a trace id.
|
||||
beforeSend(event: ErrorEvent): ErrorEvent {
|
||||
if (event.request) {
|
||||
// Page URLs can carry names and ids in the query string; the share page carries a token.
|
||||
if (typeof event.request.url === 'string') {
|
||||
event.request.url = scrubUrl(event.request.url);
|
||||
}
|
||||
delete event.request.cookies;
|
||||
delete event.request.data;
|
||||
if (event.request.headers) {
|
||||
delete event.request.headers.cookie;
|
||||
delete event.request.headers.Cookie;
|
||||
delete event.request.headers.authorization;
|
||||
delete event.request.headers.Authorization;
|
||||
}
|
||||
}
|
||||
if (typeof event.transaction === 'string') {
|
||||
event.transaction = scrubUrl(event.transaction);
|
||||
}
|
||||
if (event.user) {
|
||||
delete event.user.email;
|
||||
delete event.user.ip_address;
|
||||
@@ -24,5 +44,21 @@ export function sentrySharedOptions() {
|
||||
}
|
||||
return event;
|
||||
},
|
||||
// Request breadcrumbs carry the API URL with its query string (search text, tokens).
|
||||
// In production, console output of level log and info is dropped.
|
||||
beforeBreadcrumb(breadcrumb: Breadcrumb): Breadcrumb | null {
|
||||
const data = breadcrumb.data as { url?: unknown } | undefined;
|
||||
if (data && typeof data.url === 'string') {
|
||||
data.url = scrubUrl(data.url);
|
||||
}
|
||||
if (
|
||||
process.env.NODE_ENV === 'production' &&
|
||||
breadcrumb.category === 'console' &&
|
||||
(breadcrumb.level === 'log' || breadcrumb.level === 'info')
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return breadcrumb;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRouter } from '@/i18n/navigation';
|
||||
import { useRouter, usePathname } from '@/i18n/navigation';
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import { reportUnexpectedError } from '@/lib/error-tracking/reportUnexpectedError';
|
||||
import { scrubUrl } from '@/lib/error-tracking/sentrySharedOptions';
|
||||
import { authApi } from '@/lib/api/auth';
|
||||
import {
|
||||
clearRememberedEmail,
|
||||
@@ -90,6 +93,19 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [apiError, setApiError] = useState<ApiError | null>(null);
|
||||
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
// Error tracking: who is affected, and on which page. Only ids go out, never email or name.
|
||||
useEffect(() => {
|
||||
if (!isAuthReady) return;
|
||||
Sentry.setUser(user ? { id: user.id } : null);
|
||||
Sentry.setTag('organization_id', currentOrganization?.id ?? '');
|
||||
Sentry.setTag('organization_type', currentOrganization?.type ?? '');
|
||||
}, [isAuthReady, user, currentOrganization]);
|
||||
|
||||
useEffect(() => {
|
||||
Sentry.setTag('route', scrubUrl(pathname));
|
||||
}, [pathname]);
|
||||
|
||||
const normalizeProfilePayload = useCallback((payload: any): { user: User | null; organizations: Organization[] } => {
|
||||
const organizations = payload?.organizations || [];
|
||||
@@ -199,6 +215,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
// 401 on profile is expected when there is no session — not an application error.
|
||||
if (status !== 401) {
|
||||
console.error('Auth check failed:', err);
|
||||
reportUnexpectedError(err);
|
||||
}
|
||||
|
||||
// Only clear state — DO NOT redirect here
|
||||
@@ -267,6 +284,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
} catch (err: any) {
|
||||
setApiError(toApiError(err));
|
||||
reportUnexpectedError(err);
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
@@ -310,6 +328,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
return { organizations: orgs };
|
||||
} catch (err: any) {
|
||||
setApiError(toApiError(err));
|
||||
reportUnexpectedError(err);
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
@@ -323,6 +342,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
await authApi.logout();
|
||||
} catch (err) {
|
||||
console.error('Logout API failed:', err);
|
||||
reportUnexpectedError(err);
|
||||
} finally {
|
||||
const rememberedEmail = getRememberedEmail();
|
||||
localStorage.clear();
|
||||
@@ -356,6 +376,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
} catch (err: any) {
|
||||
setApiError(toApiError(err));
|
||||
reportUnexpectedError(err);
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
@@ -385,6 +406,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
return createResponse.data.organization.id as string;
|
||||
} catch (err: any) {
|
||||
setApiError(toApiError(err));
|
||||
reportUnexpectedError(err);
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
|
||||
@@ -53,8 +53,11 @@ export function useMarkTabReadOnVisit() {
|
||||
// Cases and Treatment tab badges clear per opened case (mark-case-read), not on tab visit.
|
||||
if (!tab || tab === 'CASES' || tab === 'TREATMENT' || !currentOrganization?.id) return;
|
||||
|
||||
void notificationsApi.markTabRead(tab).then(() => {
|
||||
window.dispatchEvent(new Event(tabBadgesChangedEventName()));
|
||||
});
|
||||
void notificationsApi.markTabRead(tab)
|
||||
.then(() => {
|
||||
window.dispatchEvent(new Event(tabBadgesChangedEventName()));
|
||||
})
|
||||
// Best effort: not an unhandled rejection.
|
||||
.catch(() => undefined);
|
||||
}, [pathname, currentOrganization?.id]);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import createMiddleware from 'next-intl/middleware';
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
import * as Sentry from '@sentry/nextjs';
|
||||
import {
|
||||
getLocaleFromPathname,
|
||||
routing,
|
||||
@@ -27,6 +28,16 @@ function isRedirectResponse(response: Response): boolean {
|
||||
}
|
||||
|
||||
export function proxy(request: NextRequest) {
|
||||
try {
|
||||
return handleProxy(request);
|
||||
} catch (error) {
|
||||
// onRequestError does not reach the proxy on the Node.js runtime (Next.js 16).
|
||||
Sentry.captureException(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function handleProxy(request: NextRequest) {
|
||||
const intlResponse = handleI18nRouting(request);
|
||||
|
||||
if (isRedirectResponse(intlResponse)) {
|
||||
|
||||
@@ -45,6 +45,7 @@ services:
|
||||
PORT: "3000"
|
||||
ADMIN_JS_TMP_DIR: /app/adminjs-tmp
|
||||
SENTRY_ENVIRONMENT: staging
|
||||
SENTRY_RELEASE: ${TAG:-staging}
|
||||
expose:
|
||||
- "3000"
|
||||
networks:
|
||||
|
||||
Reference in New Issue
Block a user