mirror of
https://github.com/temetro/temetro.git
synced 2026-07-26 20:08:14 +00:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b29fdff1cb | |||
| d237504af9 | |||
| 46c32b432c | |||
| 5bbfe551fc | |||
| 7838dd68a5 | |||
| 06810f861e | |||
| 2bb03633ff | |||
| dc5f55f87d | |||
| a4970df334 | |||
| 6c074b54f3 |
@@ -35,6 +35,11 @@ jobs:
|
||||
id: meta
|
||||
run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# QEMU lets the amd64 runner emulate arm64 so the images below build for
|
||||
# both platforms (Intel + Apple Silicon self-hosters).
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
@@ -49,6 +54,7 @@ jobs:
|
||||
with:
|
||||
context: ./backend
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: |
|
||||
${{ env.REGISTRY_NAMESPACE }}/temetro-backend:${{ steps.meta.outputs.version }}
|
||||
${{ env.REGISTRY_NAMESPACE }}/temetro-backend:latest
|
||||
@@ -58,6 +64,7 @@ jobs:
|
||||
with:
|
||||
context: ./frontend
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: |
|
||||
${{ env.REGISTRY_NAMESPACE }}/temetro-frontend:${{ steps.meta.outputs.version }}
|
||||
${{ env.REGISTRY_NAMESPACE }}/temetro-frontend:latest
|
||||
|
||||
@@ -7,6 +7,74 @@ for how releases are cut and published.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.4.0] — 2026-07-03
|
||||
|
||||
### Added
|
||||
- **Ambient AI visit scribe** — a **Record visit** action on the patient sheet turns a
|
||||
clinician↔patient conversation into a draft **SOAP** encounter note. Record with the
|
||||
microphone (`MediaRecorder`, stored as an auditable patient attachment) or paste a
|
||||
transcript; the backend transcribes via the user's **OpenAI (Whisper)** or **Gemini**
|
||||
key, de-identifies the transcript + patient context through **Veil**, and the model
|
||||
drafts a structured note that the clinician **reviews and edits before saving** — the
|
||||
same write-approval gate as the chat agent. New `POST /api/scribe/{transcribe,draft,save}`
|
||||
(`backend/src/routes/scribe.ts`, `services/ai/transcribe.ts`), a `veil.redactText()`
|
||||
free-text redactor, and an `appendEncounter` service that adds one note without touching
|
||||
the rest of the record. Gated by `patient:write` + the clinic AI policy (reception and
|
||||
disabled-AI accounts don't see it). New `scribe` locale namespace across all five
|
||||
languages. Drafting also works with local Ollama from a pasted transcript.
|
||||
|
||||
## [0.3.0] — 2026-07-02
|
||||
|
||||
### Added
|
||||
- **Three new interface languages** — Somali (`so`), Arabic (`ar`) and German
|
||||
(`de`) join English and French, selectable in Settings → Profile → Language.
|
||||
Each locale carries a full translation of the ~1,660 UI strings, with native
|
||||
names shown in the selector (Soomaali, العربية, Deutsch).
|
||||
- **Right-to-left (RTL) support** — selecting Arabic sets `dir="rtl"` on the
|
||||
document (applied before first paint via an inline script, so no flash), flips
|
||||
physical spacing/alignment to logical CSS utilities, mirrors directional icons,
|
||||
and loads an Arabic-capable typeface (IBM Plex Sans Arabic) appended to the
|
||||
font stack for per-character fallback.
|
||||
- **Language roams across devices** — the chosen language is persisted to the
|
||||
per-user `user_settings` preferences and re-applied on sign-in, with
|
||||
localStorage remaining the offline source of truth.
|
||||
- **`frontend/scripts/check-locales.mjs`** (+ `npm run check-locales`) — a parity
|
||||
check that fails on missing/extra keys or `{{placeholder}}` mismatches across
|
||||
locales and warns when Arabic count-keys lack the full CLDR plural forms.
|
||||
|
||||
## [0.2.5] — 2026-07-01
|
||||
|
||||
### Fixed
|
||||
- **Multi-arch Docker images** — the `release` workflow now builds and publishes
|
||||
`khalidxv/temetro-backend` and `khalidxv/temetro-frontend` for both
|
||||
`linux/amd64` and `linux/arm64`. Previously the images were amd64-only, so
|
||||
`docker compose pull` on Apple Silicon failed with *no matching manifest for
|
||||
linux/arm64/v8* and fell back to building from source.
|
||||
|
||||
### Changed
|
||||
- **Language switcher** in Settings → Profile is now a **select** that asks for
|
||||
confirmation before switching the interface language, instead of applying the
|
||||
change instantly on a button tap.
|
||||
|
||||
## [0.2.4] — 2026-06-29
|
||||
|
||||
### Added
|
||||
- **Pagination** on the Activity and Invoices pages (10 per page), matching the
|
||||
Patients page, via a shared `ListPagination` component.
|
||||
- **French (Français)** interface language, with a language switcher in
|
||||
Settings → Profile. The choice persists on the device.
|
||||
- **"Check for updates"** button in Settings → About & updates that forces a
|
||||
fresh check.
|
||||
|
||||
### Changed
|
||||
- **Update detection** now reads the latest version from **Docker Hub** image
|
||||
tags (the channel clinics actually pull), falling back to the GitHub release
|
||||
if Docker Hub is unreachable. This fixes "About & updates" showing *Up to
|
||||
date* when a newer image was already published.
|
||||
- **docker compose** host ports are now configurable (`BACKEND_PORT`,
|
||||
`FRONTEND_PORT`, `ADMINER_PORT`, alongside `POSTGRES_PORT`) so a port clash on
|
||||
`docker compose up -d` can be resolved from `.env` without editing the file.
|
||||
|
||||
## [0.2.3] — 2026-06-29
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -80,6 +80,11 @@ accurate (e.g. a new backend route needs an `content/docs/api/*.mdx` entry; a UI
|
||||
in the matching guide; status changes belong in the roadmap). Commit docs changes inside that
|
||||
repo, separately from this one.
|
||||
|
||||
**Every release must also get a dated entry in the docs changelog**
|
||||
(`content/docs/changelog.mdx`, newest first) — not just the monorepo `CHANGELOG.md`. When you cut a
|
||||
version (see "Always release after pushing"), add a matching, user-facing section to that page in the
|
||||
same session so `../temetro/docs` never falls behind the shipped version.
|
||||
|
||||
## Running the stack
|
||||
|
||||
From `backend/`: ensure a `.env` exists (`cp .env.example .env`, then set `BETTER_AUTH_SECRET` via
|
||||
|
||||
@@ -73,9 +73,11 @@ missing secrets on first start. Then open:
|
||||
Prefer to **build from source** (for development)? Use `docker compose up
|
||||
--build` instead. Migrations apply automatically on backend start.
|
||||
|
||||
> **Port conflict?** If another Postgres holds host port `5432`, set
|
||||
> `POSTGRES_PORT` (e.g. `5433`) in `backend/.env`. The app still talks to
|
||||
> Postgres internally on `db:5432`; only the published host port changes.
|
||||
> **Port conflict?** If host ports `5432`, `4000` or `3000` are already in use,
|
||||
> set `POSTGRES_PORT`, `BACKEND_PORT` and/or `FRONTEND_PORT` (e.g. `5433` /
|
||||
> `4001` / `3001`) in `backend/.env`. The services still talk to each other on
|
||||
> their internal ports (`db:5432`, `backend:4000`); only the published host
|
||||
> ports change.
|
||||
|
||||
### Access from other computers (hospital LAN)
|
||||
|
||||
|
||||
@@ -26,9 +26,11 @@ FRONTEND_URL=http://localhost:3000
|
||||
PORT=4000
|
||||
NODE_ENV=development
|
||||
|
||||
# Host port Postgres is published on by docker compose. Change it if 5432 is
|
||||
# already in use on your machine (the app still talks to Postgres internally).
|
||||
# Host ports docker compose publishes. Change any that are already in use on
|
||||
# this machine (the services still talk to each other on their internal ports).
|
||||
POSTGRES_PORT=5432
|
||||
BACKEND_PORT=4000
|
||||
FRONTEND_PORT=3000
|
||||
|
||||
# --- Patient wallet relay -------------------------------------------------
|
||||
# The URL baked into the QR a patient scans to import their record. Their phone
|
||||
|
||||
@@ -25,6 +25,12 @@
|
||||
#
|
||||
# Optional DB browser (Adminer) lives behind a profile:
|
||||
# docker compose --profile tools up adminer # http://localhost:8080
|
||||
#
|
||||
# Host ports are configurable to avoid clashing with software already running on
|
||||
# this machine. Override any of them in a .env file (or inline), e.g.:
|
||||
# POSTGRES_PORT=5433 BACKEND_PORT=4001 FRONTEND_PORT=3001 docker compose up -d
|
||||
# Only the published host port changes; the services still talk to each other on
|
||||
# their internal ports (db:5432, backend:4000).
|
||||
|
||||
services:
|
||||
db:
|
||||
@@ -76,7 +82,8 @@ services:
|
||||
# Persists uploaded files across restarts/rebuilds.
|
||||
- temetro_uploads:/var/lib/temetro/uploads
|
||||
ports:
|
||||
- "4000:4000"
|
||||
# Host port is configurable to avoid clashing with an existing service.
|
||||
- "${BACKEND_PORT:-4000}:4000"
|
||||
|
||||
frontend:
|
||||
image: khalidxv/temetro-frontend:${TEMETRO_VERSION:-latest}
|
||||
@@ -90,7 +97,8 @@ services:
|
||||
depends_on:
|
||||
- backend
|
||||
ports:
|
||||
- "3000:3000"
|
||||
# Host port is configurable to avoid clashing with an existing service.
|
||||
- "${FRONTEND_PORT:-3000}:3000"
|
||||
|
||||
adminer:
|
||||
image: adminer:5
|
||||
@@ -99,7 +107,7 @@ services:
|
||||
depends_on:
|
||||
- db
|
||||
ports:
|
||||
- "8080:8080"
|
||||
- "${ADMINER_PORT:-8080}:8080"
|
||||
|
||||
volumes:
|
||||
temetro_pgdata:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "temetro-backend",
|
||||
"version": "0.2.3",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "temetro backend — Express + Postgres API with Better Auth (email/password, organizations) and org-scoped patient records.",
|
||||
|
||||
@@ -28,6 +28,7 @@ import { patientsRouter } from "./routes/patients.js";
|
||||
import { patientsWalletRouter } from "./routes/patients-wallet.js";
|
||||
import { portalRouter } from "./routes/portal.js";
|
||||
import { prescriptionsRouter } from "./routes/prescriptions.js";
|
||||
import { scribeRouter } from "./routes/scribe.js";
|
||||
import { settingsRouter } from "./routes/settings.js";
|
||||
import { signingRouter } from "./routes/signing.js";
|
||||
import { staffRouter } from "./routes/staff.js";
|
||||
@@ -104,6 +105,7 @@ app.use("/api/notifications", notificationsRouter);
|
||||
app.use("/api/settings", settingsRouter);
|
||||
app.use("/api/ai", aiRouter);
|
||||
app.use("/api/chat", chatRouter);
|
||||
app.use("/api/scribe", scribeRouter);
|
||||
app.use("/api/integrations", integrationsRouter);
|
||||
app.use("/api/portal", portalRouter);
|
||||
app.use("/api/auth-helpers", authHelpersRouter);
|
||||
|
||||
@@ -41,6 +41,14 @@ const ALLOWED_MIME = new Set([
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/vnd.ms-excel",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
// Ambient visit-scribe recordings (stored as a patient attachment so they're
|
||||
// auditable). Voice Opus/AAC stays well under the 15 MB cap for a long visit.
|
||||
"audio/webm",
|
||||
"audio/ogg",
|
||||
"audio/mp4",
|
||||
"audio/mpeg",
|
||||
"audio/wav",
|
||||
"audio/x-m4a",
|
||||
]);
|
||||
|
||||
// Disk storage under UPLOAD_DIR/<orgId>/, keyed by a random id so original
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { generateText } from "ai";
|
||||
import { Router } from "express";
|
||||
import { z } from "zod";
|
||||
|
||||
import { HttpError } from "../lib/http-error.js";
|
||||
import { isReceptionOnly, providerScope } from "../lib/role-scope.js";
|
||||
import {
|
||||
requireAuth,
|
||||
requireOrg,
|
||||
requirePermission,
|
||||
} from "../middleware/auth.js";
|
||||
import { recordActivity } from "../services/activity.js";
|
||||
import { getAiSettings } from "../services/ai/config.js";
|
||||
import { aiAllowedFor, getPolicy } from "../services/ai/policy.js";
|
||||
import { resolveModel } from "../services/ai/provider.js";
|
||||
import { transcribeAudio } from "../services/ai/transcribe.js";
|
||||
import { createVeil } from "../services/ai/veil.js";
|
||||
import { absolutePath, getAttachmentRow } from "../services/attachments.js";
|
||||
import { appendEncounter, getPatient } from "../services/patients.js";
|
||||
import type { Encounter } from "../types/patient.js";
|
||||
|
||||
export const scribeRouter = Router();
|
||||
|
||||
// The ambient scribe drafts and saves a clinical encounter note, so it needs
|
||||
// full clinical write access — never reception (demographics only).
|
||||
scribeRouter.use(
|
||||
requireAuth,
|
||||
requireOrg,
|
||||
requirePermission({ patient: ["write"] }),
|
||||
);
|
||||
|
||||
// Guard shared by every scribe route: the clinic AI kill-switch must allow this
|
||||
// member, and reception (demographics-only) can never draft clinical notes.
|
||||
async function ensureScribeAllowed(req: {
|
||||
organizationId?: string;
|
||||
memberRole?: string;
|
||||
}): Promise<void> {
|
||||
if (isReceptionOnly(req.memberRole)) {
|
||||
throw new HttpError(403, "The visit scribe is not available for your role.");
|
||||
}
|
||||
const policy = await getPolicy(req.organizationId!);
|
||||
if (!aiAllowedFor(policy, req.memberRole)) {
|
||||
throw new HttpError(403, "The AI assistant is disabled for your account.");
|
||||
}
|
||||
}
|
||||
|
||||
const transcribeSchema = z.object({
|
||||
attachmentId: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
// POST /api/scribe/transcribe — turn a stored audio attachment into a raw
|
||||
// transcript via the user's speech provider (OpenAI/Gemini). The audio does NOT
|
||||
// pass through Veil or the chat loop.
|
||||
scribeRouter.post("/transcribe", async (req, res, next) => {
|
||||
try {
|
||||
await ensureScribeAllowed(req);
|
||||
const { attachmentId } = transcribeSchema.parse(req.body);
|
||||
const row = await getAttachmentRow(req.organizationId!, attachmentId);
|
||||
if (!row) throw new HttpError(404, "Recording not found.");
|
||||
if (!row.mimeType.startsWith("audio/")) {
|
||||
throw new HttpError(400, "That attachment is not an audio recording.");
|
||||
}
|
||||
|
||||
const settings = await getAiSettings(req.user!.id);
|
||||
const buffer = await readFile(absolutePath(row.storagePath));
|
||||
const { transcript, provider } = await transcribeAudio(settings, {
|
||||
buffer,
|
||||
mimeType: row.mimeType,
|
||||
filename: row.filename,
|
||||
});
|
||||
|
||||
void recordActivity({
|
||||
orgId: req.organizationId!,
|
||||
actor: { id: req.user!.id, name: req.user!.name },
|
||||
action: `Transcribed a visit recording (${provider})`,
|
||||
entityType: "patient",
|
||||
patientFileNumber: row.fileNumber,
|
||||
});
|
||||
|
||||
res.json({ transcript });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const draftSchema = z.object({
|
||||
fileNumber: z.string().trim().min(1),
|
||||
transcript: z.string().trim().min(1).max(100_000),
|
||||
visitType: z.string().trim().max(120).optional(),
|
||||
date: z.string().trim().max(40).optional(),
|
||||
});
|
||||
|
||||
// Strip ```json fences and parse; returns null if the text isn't JSON.
|
||||
function parseDraftJson(text: string): { type?: string; summary?: string } | null {
|
||||
const cleaned = text
|
||||
.replace(/^\s*```(?:json)?/i, "")
|
||||
.replace(/```\s*$/i, "")
|
||||
.trim();
|
||||
try {
|
||||
const parsed = JSON.parse(cleaned);
|
||||
return typeof parsed === "object" && parsed ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const DRAFT_SYSTEM = [
|
||||
"You are a clinical scribe. From a visit transcript, write a concise, structured",
|
||||
"encounter note in SOAP format (Subjective, Objective, Assessment, Plan).",
|
||||
"Rules:",
|
||||
"- Use ONLY what the transcript supports. Never invent vitals, doses, or findings.",
|
||||
"- If a SOAP section has nothing to report, write \"Not discussed.\" under it.",
|
||||
"- Identifiers may appear as tokens like [PATIENT_1] or [PROVIDER_1]; keep them",
|
||||
" verbatim — do not guess real names.",
|
||||
"Respond with a JSON object ONLY (no prose, no code fences):",
|
||||
'{ "type": "<short visit type, e.g. Follow-up / New patient / Telehealth>",',
|
||||
' "summary": "<the SOAP note as markdown with **Subjective** / **Objective** /',
|
||||
' **Assessment** / **Plan** headings>" }',
|
||||
].join("\n");
|
||||
|
||||
// POST /api/scribe/draft — draft an encounter note from a transcript. The
|
||||
// transcript + patient context are Veil-redacted before any external call and
|
||||
// the output is rehydrated. Nothing is written — the clinician reviews and
|
||||
// approves via POST /save (the same write-approval gate as the chat agent).
|
||||
scribeRouter.post("/draft", async (req, res, next) => {
|
||||
try {
|
||||
await ensureScribeAllowed(req);
|
||||
const { fileNumber, transcript, visitType, date } = draftSchema.parse(
|
||||
req.body,
|
||||
);
|
||||
|
||||
const patient = await getPatient(
|
||||
req.organizationId!,
|
||||
fileNumber,
|
||||
false,
|
||||
providerScope(req.memberRole, req.user!.id),
|
||||
);
|
||||
if (!patient) throw new HttpError(404, "Patient not found.");
|
||||
|
||||
const settings = await getAiSettings(req.user!.id);
|
||||
const resolved = resolveModel(settings, settings.defaultModel);
|
||||
const veil = createVeil(settings.veilLevel, resolved.isExternal);
|
||||
|
||||
// Seed Veil's token maps with this patient's identifiers, then redact the
|
||||
// free-text transcript against them before it leaves the clinic.
|
||||
const redactedPatient = veil.redactPatient(patient);
|
||||
const redactedTranscript = veil.redactText(transcript);
|
||||
|
||||
const context = [
|
||||
`Patient: ${redactedPatient.name} (MRN ${redactedPatient.fileNumber}), ${patient.age}y ${patient.sex}.`,
|
||||
patient.problems.length
|
||||
? `Known problems: ${patient.problems.map((p) => p.label).join(", ")}.`
|
||||
: "",
|
||||
patient.medications.length
|
||||
? `Current medications: ${patient.medications
|
||||
.map((m) => `${m.name} ${m.dose}`)
|
||||
.join(", ")}.`
|
||||
: "",
|
||||
visitType ? `Visit type hint: ${visitType}.` : "",
|
||||
"",
|
||||
"Transcript:",
|
||||
redactedTranscript,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
const result = await generateText({
|
||||
model: resolved.model,
|
||||
system: DRAFT_SYSTEM,
|
||||
prompt: context,
|
||||
});
|
||||
|
||||
const parsed = parseDraftJson(result.text);
|
||||
const summary = veil.rehydrate(
|
||||
(parsed?.summary ?? result.text ?? "").trim(),
|
||||
);
|
||||
const type = (parsed?.type ?? visitType ?? "Visit").trim() || "Visit";
|
||||
|
||||
const draft: Encounter = {
|
||||
date: date || new Date().toISOString().slice(0, 10),
|
||||
type,
|
||||
// The responsible clinician is the signed-in user, not the model's guess.
|
||||
provider: req.user!.name ?? "",
|
||||
summary,
|
||||
};
|
||||
|
||||
res.json({
|
||||
draft,
|
||||
veil: {
|
||||
active: veil.active,
|
||||
level: veil.level,
|
||||
classes: veil.usedClasses(),
|
||||
provider: resolved.providerLabel,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const saveSchema = z.object({
|
||||
fileNumber: z.string().trim().min(1),
|
||||
encounter: z.object({
|
||||
date: z.string().trim().min(1),
|
||||
type: z.string().trim().min(1),
|
||||
provider: z.string().trim().default(""),
|
||||
summary: z.string().trim().min(1),
|
||||
}),
|
||||
});
|
||||
|
||||
// POST /api/scribe/save — the approval step: append the reviewed encounter note
|
||||
// to the patient record. Re-validates server-side and audits like any add.
|
||||
scribeRouter.post("/save", async (req, res, next) => {
|
||||
try {
|
||||
await ensureScribeAllowed(req);
|
||||
const { fileNumber, encounter } = saveSchema.parse(req.body);
|
||||
const updated = await appendEncounter(
|
||||
req.organizationId!,
|
||||
fileNumber,
|
||||
encounter,
|
||||
);
|
||||
if (!updated) throw new HttpError(404, "Patient not found.");
|
||||
|
||||
void recordActivity({
|
||||
orgId: req.organizationId!,
|
||||
actor: { id: req.user!.id, name: req.user!.name },
|
||||
action: `Added a scribe visit note for ${updated.name}`,
|
||||
entityType: "patient",
|
||||
entityId: updated.fileNumber,
|
||||
patientName: updated.name,
|
||||
patientFileNumber: updated.fileNumber,
|
||||
});
|
||||
|
||||
res.status(201).json(updated);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
// GET /api/version — reports the running version and whether a newer release
|
||||
// exists on GitHub. Public (no PHI); the frontend uses it for the Settings
|
||||
// "About & Updates" panel and the optional update banner.
|
||||
// GET /api/version — reports the running version and whether a newer image is
|
||||
// available. The latest version is read from Docker Hub (the actual update
|
||||
// channel: clinics run `docker compose pull`), falling back to the GitHub
|
||||
// release if Docker Hub's API is unreachable. Public (no PHI); the frontend uses
|
||||
// it for the Settings "About & Updates" panel and the optional update banner.
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
import { Router } from "express";
|
||||
@@ -13,16 +15,24 @@ const require = createRequire(import.meta.url);
|
||||
const pkg = require("../../package.json") as { version?: string };
|
||||
const CURRENT = env.APP_VERSION ?? pkg.version ?? "0.0.0";
|
||||
|
||||
const LATEST_RELEASE_URL =
|
||||
// The published image whose tags reflect what `docker compose pull` would fetch.
|
||||
const DOCKERHUB_TAGS_URL =
|
||||
"https://hub.docker.com/v2/repositories/khalidxv/temetro-backend/tags?page_size=100";
|
||||
// GitHub release of a given version — used for the human-readable "what's new"
|
||||
// link, and as a fallback source for the latest version.
|
||||
const GITHUB_LATEST_RELEASE_URL =
|
||||
"https://api.github.com/repos/temetro/temetro/releases/latest";
|
||||
const CACHE_TTL = 6 * 60 * 60 * 1000; // 6h — releases are infrequent.
|
||||
const releaseUrlFor = (version: string) =>
|
||||
`https://github.com/temetro/temetro/releases/tag/v${version}`;
|
||||
|
||||
const CACHE_TTL = 60 * 60 * 1000; // 1h — surface a new release reasonably fast.
|
||||
const ERROR_TTL = 10 * 60 * 1000; // back off ~10m after a failed lookup.
|
||||
|
||||
type LatestInfo = { latest: string | null; releaseUrl: string | null };
|
||||
let cache: { at: number; ttl: number; info: LatestInfo } | null = null;
|
||||
|
||||
function parseSemver(v: string): [number, number, number] | null {
|
||||
const m = v.trim().replace(/^v/, "").match(/^(\d+)\.(\d+)\.(\d+)/);
|
||||
const m = v.trim().replace(/^v/, "").match(/^(\d+)\.(\d+)\.(\d+)$/);
|
||||
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
||||
}
|
||||
|
||||
@@ -38,18 +48,52 @@ function isNewer(latest: string, current: string): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
async function fetchLatest(): Promise<LatestInfo> {
|
||||
if (cache && Date.now() - cache.at < cache.ttl) return cache.info;
|
||||
// Highest strict X.Y.Z tag in the list (ignores `latest` and any non-semver).
|
||||
function maxSemver(versions: string[]): string | null {
|
||||
let best: string | null = null;
|
||||
for (const v of versions) {
|
||||
if (parseSemver(v) && (best === null || isNewer(v, best))) best = v;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// Primary source: the published Docker Hub image tags.
|
||||
async function fetchFromDockerHub(): Promise<string | null> {
|
||||
const res = await fetch(DOCKERHUB_TAGS_URL, {
|
||||
headers: { Accept: "application/json", "User-Agent": "temetro" },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Docker Hub responded ${res.status}`);
|
||||
const body = (await res.json()) as { results?: Array<{ name?: string }> };
|
||||
const names = (body.results ?? [])
|
||||
.map((r) => r.name)
|
||||
.filter((n): n is string => typeof n === "string");
|
||||
return maxSemver(names);
|
||||
}
|
||||
|
||||
// Fallback source: the latest GitHub release tag (used if Docker Hub is blocked).
|
||||
async function fetchFromGitHub(): Promise<string | null> {
|
||||
const res = await fetch(GITHUB_LATEST_RELEASE_URL, {
|
||||
headers: { Accept: "application/vnd.github+json", "User-Agent": "temetro" },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`GitHub responded ${res.status}`);
|
||||
const body = (await res.json()) as { tag_name?: string };
|
||||
return body.tag_name ? body.tag_name.replace(/^v/, "") : null;
|
||||
}
|
||||
|
||||
async function fetchLatest(force = false): Promise<LatestInfo> {
|
||||
if (!force && cache && Date.now() - cache.at < cache.ttl) return cache.info;
|
||||
try {
|
||||
const res = await fetch(LATEST_RELEASE_URL, {
|
||||
headers: { Accept: "application/vnd.github+json", "User-Agent": "temetro" },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`GitHub responded ${res.status}`);
|
||||
const body = (await res.json()) as { tag_name?: string; html_url?: string };
|
||||
let latest: string | null = null;
|
||||
try {
|
||||
latest = await fetchFromDockerHub();
|
||||
} catch {
|
||||
latest = await fetchFromGitHub();
|
||||
}
|
||||
const info: LatestInfo = {
|
||||
latest: body.tag_name ? body.tag_name.replace(/^v/, "") : null,
|
||||
releaseUrl: body.html_url ?? null,
|
||||
latest,
|
||||
releaseUrl: latest ? releaseUrlFor(latest) : null,
|
||||
};
|
||||
cache = { at: Date.now(), ttl: CACHE_TTL, info };
|
||||
return info;
|
||||
@@ -63,8 +107,10 @@ async function fetchLatest(): Promise<LatestInfo> {
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get("/", async (_req, res) => {
|
||||
const { latest, releaseUrl } = await fetchLatest();
|
||||
router.get("/", async (req, res) => {
|
||||
// `?refresh=1` powers the "Check for updates" button — bypass the cache.
|
||||
const force = req.query.refresh === "1" || req.query.refresh === "true";
|
||||
const { latest, releaseUrl } = await fetchLatest(force);
|
||||
res.json({
|
||||
current: CURRENT,
|
||||
latest,
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { HttpError } from "../../lib/http-error.js";
|
||||
import type { userAiSettings } from "../../db/schema/ai.js";
|
||||
import { getApiKey } from "./config.js";
|
||||
|
||||
type AiSettingsRow = typeof userAiSettings.$inferSelect;
|
||||
|
||||
export type AudioInput = {
|
||||
buffer: Buffer;
|
||||
mimeType: string;
|
||||
filename: string;
|
||||
};
|
||||
|
||||
// Which transcription backend a user's AI settings can reach. Anthropic has no
|
||||
// speech-to-text API, so an Anthropic-only user must paste a transcript instead.
|
||||
export type TranscribeProvider = "openai" | "gemini";
|
||||
|
||||
export function transcribeProviderFor(
|
||||
settings: AiSettingsRow,
|
||||
): TranscribeProvider | null {
|
||||
if (getApiKey(settings, "openai")) return "openai";
|
||||
if (getApiKey(settings, "gemini")) return "gemini";
|
||||
return null;
|
||||
}
|
||||
|
||||
const OPENAI_MODEL = "whisper-1";
|
||||
const GEMINI_MODEL = "gemini-2.5-flash";
|
||||
|
||||
const TRANSCRIBE_PROMPT =
|
||||
"Transcribe this clinical visit recording verbatim. Return only the spoken words as plain text, with no commentary, headings, or timestamps.";
|
||||
|
||||
async function transcribeWithOpenAI(
|
||||
apiKey: string,
|
||||
audio: AudioInput,
|
||||
): Promise<string> {
|
||||
const form = new FormData();
|
||||
form.append(
|
||||
"file",
|
||||
new Blob([new Uint8Array(audio.buffer)], { type: audio.mimeType }),
|
||||
audio.filename,
|
||||
);
|
||||
form.append("model", OPENAI_MODEL);
|
||||
form.append("response_format", "json");
|
||||
|
||||
const res = await fetch("https://api.openai.com/v1/audio/transcriptions", {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
body: form,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const detail = await res.text().catch(() => "");
|
||||
throw new HttpError(
|
||||
502,
|
||||
`Transcription failed (OpenAI ${res.status}). ${detail.slice(0, 300)}`,
|
||||
);
|
||||
}
|
||||
const json = (await res.json()) as { text?: string };
|
||||
return (json.text ?? "").trim();
|
||||
}
|
||||
|
||||
async function transcribeWithGemini(
|
||||
apiKey: string,
|
||||
audio: AudioInput,
|
||||
): Promise<string> {
|
||||
const url = `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent?key=${encodeURIComponent(
|
||||
apiKey,
|
||||
)}`;
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
contents: [
|
||||
{
|
||||
parts: [
|
||||
{
|
||||
inline_data: {
|
||||
mime_type: audio.mimeType,
|
||||
data: audio.buffer.toString("base64"),
|
||||
},
|
||||
},
|
||||
{ text: TRANSCRIBE_PROMPT },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const detail = await res.text().catch(() => "");
|
||||
throw new HttpError(
|
||||
502,
|
||||
`Transcription failed (Gemini ${res.status}). ${detail.slice(0, 300)}`,
|
||||
);
|
||||
}
|
||||
const json = (await res.json()) as {
|
||||
candidates?: { content?: { parts?: { text?: string }[] } }[];
|
||||
};
|
||||
const text =
|
||||
json.candidates?.[0]?.content?.parts
|
||||
?.map((p) => p.text ?? "")
|
||||
.join("")
|
||||
.trim() ?? "";
|
||||
return text;
|
||||
}
|
||||
|
||||
// Send an audio recording to the user's transcription provider and return the
|
||||
// raw transcript. The audio never passes through the chat loop or Veil — Veil
|
||||
// cannot redact speech, so the caller must warn the clinician that audio leaves
|
||||
// the clinic when an external provider is used (only the DRAFTING step is
|
||||
// Veil-protected). Throws a 400 when no speech-capable provider is configured.
|
||||
export async function transcribeAudio(
|
||||
settings: AiSettingsRow,
|
||||
audio: AudioInput,
|
||||
): Promise<{ transcript: string; provider: TranscribeProvider }> {
|
||||
const provider = transcribeProviderFor(settings);
|
||||
if (!provider) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
"Transcription needs an OpenAI or Gemini API key. Add one in Settings → AI, or paste the visit transcript instead.",
|
||||
);
|
||||
}
|
||||
const apiKey = getApiKey(settings, provider)!;
|
||||
const transcript =
|
||||
provider === "openai"
|
||||
? await transcribeWithOpenAI(apiKey, audio)
|
||||
: await transcribeWithGemini(apiKey, audio);
|
||||
if (!transcript) {
|
||||
throw new HttpError(
|
||||
502,
|
||||
"The transcription came back empty — try again or paste the transcript.",
|
||||
);
|
||||
}
|
||||
return { transcript, provider };
|
||||
}
|
||||
@@ -26,6 +26,15 @@ export type Veil = {
|
||||
redactPatient: (patient: Patient) => Patient;
|
||||
/** Map a possibly-tokenized file number from a tool call back to the real one. */
|
||||
resolveFileNumber: (input: string) => string;
|
||||
/**
|
||||
* De-identify free text (e.g. a visit transcript) by swapping any KNOWN
|
||||
* identifiers — the patient name, MRN and provider names already seen via
|
||||
* redactPatient — for their tokens. Seed the token maps by calling
|
||||
* redactPatient(patient) first. Note: this only catches identifiers we know
|
||||
* about; free-text PHI spoken aloud (addresses, relatives' names) is not
|
||||
* covered — see the ambient-scribe consent notice.
|
||||
*/
|
||||
redactText: (text: string) => string;
|
||||
/** Swap any tokens in model output back to real identifiers. */
|
||||
rehydrate: (text: string) => string;
|
||||
/** Token classes actually emitted — for the audit log. */
|
||||
@@ -81,6 +90,21 @@ export function createVeil(level: VeilLevel, active: boolean): Veil {
|
||||
return mrnByToken.get(input.trim()) ?? input;
|
||||
}
|
||||
|
||||
function redactText(text: string): string {
|
||||
if (!isActive || fromToken.size === 0) return text;
|
||||
let out = text;
|
||||
// Longest real values first so a provider name containing the patient name
|
||||
// (or similar overlap) is replaced whole before its substrings.
|
||||
const byLength = [...fromToken.entries()]
|
||||
.filter(([, real]) => real.trim().length > 0)
|
||||
.sort((a, b) => b[1].length - a[1].length);
|
||||
for (const [token, real] of byLength) {
|
||||
const escaped = real.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
out = out.replace(new RegExp(escaped, "gi"), token);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function rehydrate(text: string): string {
|
||||
if (!isActive || fromToken.size === 0) return text;
|
||||
let out = text;
|
||||
@@ -101,6 +125,7 @@ export function createVeil(level: VeilLevel, active: boolean): Veil {
|
||||
level,
|
||||
redactPatient,
|
||||
resolveFileNumber,
|
||||
redactText,
|
||||
rehydrate,
|
||||
usedClasses,
|
||||
};
|
||||
|
||||
@@ -570,6 +570,46 @@ export async function appendLabs(
|
||||
return getPatient(orgId, fileNumber);
|
||||
}
|
||||
|
||||
// Append a single encounter (visit note) without touching the rest of the
|
||||
// record — used by the ambient AI scribe, which drafts one note at a time and
|
||||
// must not go through updatePatient's wholesale child replacement. Position
|
||||
// continues after the current max so the new note sorts last.
|
||||
export async function appendEncounter(
|
||||
orgId: string,
|
||||
fileNumber: string,
|
||||
entry: Encounter,
|
||||
): Promise<Patient | null> {
|
||||
const inserted = await db.transaction(async (tx) => {
|
||||
const [existing] = await tx
|
||||
.select({ id: patients.id })
|
||||
.from(patients)
|
||||
.where(
|
||||
and(
|
||||
eq(patients.organizationId, orgId),
|
||||
eq(patients.fileNumber, fileNumber),
|
||||
),
|
||||
);
|
||||
if (!existing) return false;
|
||||
|
||||
const [pos] = await tx
|
||||
.select({ max: sql<number>`coalesce(max(${encounters.position}), -1)` })
|
||||
.from(encounters)
|
||||
.where(eq(encounters.patientId, existing.id));
|
||||
await tx.insert(encounters).values({
|
||||
patientId: existing.id,
|
||||
position: (pos?.max ?? -1) + 1,
|
||||
...entry,
|
||||
});
|
||||
await tx
|
||||
.update(patients)
|
||||
.set({ updatedAt: new Date() })
|
||||
.where(eq(patients.id, existing.id));
|
||||
return true;
|
||||
});
|
||||
if (!inserted) return null;
|
||||
return getPatient(orgId, fileNumber);
|
||||
}
|
||||
|
||||
// Remove a single lab result from a patient, identified by its
|
||||
// name/value/takenAt (the frontend has no row id). Scoped to the org via the
|
||||
// owning patient. Returns the reloaded patient, or null when the chart is gone.
|
||||
|
||||
@@ -7,9 +7,11 @@
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-sans);
|
||||
/* Append the Arabic face so Arabic codepoints fall through per-character even
|
||||
in LTR locales; Latin text still renders in Inter. See app/layout.tsx. */
|
||||
--font-sans: var(--font-sans), var(--font-arabic);
|
||||
--font-mono: var(--font-mono);
|
||||
--font-heading: var(--font-heading);
|
||||
--font-heading: var(--font-heading), var(--font-arabic);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
|
||||
+30
-4
@@ -1,5 +1,5 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist_Mono, Inter } from "next/font/google";
|
||||
import { Geist_Mono, IBM_Plex_Sans_Arabic, Inter } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ThemeProvider } from "@/components/theme-provider";
|
||||
@@ -10,6 +10,27 @@ import { ToastProvider } from "@/components/ui/toast";
|
||||
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" });
|
||||
const interHeading = Inter({ subsets: ["latin"], variable: "--font-heading" });
|
||||
const geistMono = Geist_Mono({ subsets: ["latin"], variable: "--font-mono" });
|
||||
// Arabic-capable fallback: Inter has no Arabic glyphs, so we append this to the
|
||||
// sans/heading stacks (see globals.css) for per-character fallback in every
|
||||
// locale, and rely on it fully when dir="rtl". Not a variable font — pin weights.
|
||||
const plexArabic = IBM_Plex_Sans_Arabic({
|
||||
subsets: ["arabic"],
|
||||
weight: ["400", "500", "600", "700"],
|
||||
variable: "--font-arabic",
|
||||
});
|
||||
|
||||
// Runs before first paint: mirror lib/i18n/config.ts `dirFor` so an Arabic user
|
||||
// gets dir="rtl" immediately instead of a flash of LTR. Detection order matches
|
||||
// i18next-browser-languagedetector (localStorage key "i18nextLng", then the
|
||||
// browser language). suppressHydrationWarning on <html> ignores the attr diff.
|
||||
const setInitialDir = `
|
||||
(function(){try{
|
||||
var l=localStorage.getItem("i18nextLng")||navigator.language||"en";
|
||||
var e=document.documentElement;
|
||||
e.lang=l;
|
||||
e.dir=l.indexOf("ar")===0?"rtl":"ltr";
|
||||
}catch(_){}})();
|
||||
`;
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "temetro — AI assistant for clinicians",
|
||||
@@ -33,17 +54,22 @@ export default function RootLayout({
|
||||
inter.variable,
|
||||
interHeading.variable,
|
||||
geistMono.variable,
|
||||
plexArabic.variable,
|
||||
"font-sans"
|
||||
)}
|
||||
>
|
||||
{/* suppressHydrationWarning: next-themes sets the theme class on <html>
|
||||
before hydration, and browser extensions (e.g. ColorZilla's
|
||||
cz-shortcut-listen) mutate <body>. Only ignores attribute diffs on
|
||||
those elements, not their children. */}
|
||||
before hydration, the dir script below sets lang/dir, and browser
|
||||
extensions (e.g. ColorZilla's cz-shortcut-listen) mutate <body>. Only
|
||||
ignores attribute diffs on those elements, not their children. */}
|
||||
<body
|
||||
className="h-dvh overflow-hidden flex flex-col"
|
||||
suppressHydrationWarning
|
||||
>
|
||||
<script
|
||||
// Sets <html dir/lang> before paint; see setInitialDir above.
|
||||
dangerouslySetInnerHTML={{ __html: setInitialDir }}
|
||||
/>
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
defaultTheme="dark"
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ListPagination } from "@/components/ui/list-pagination";
|
||||
import {
|
||||
type ActivityEntityType,
|
||||
type ActivityEntry,
|
||||
@@ -103,15 +104,19 @@ function DetailRow({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<span className="shrink-0 text-muted-foreground text-xs">{label}</span>
|
||||
<span className="text-right text-foreground text-sm">{value}</span>
|
||||
<span className="text-end text-foreground text-sm">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Entries shown per page in the activity feed before paginating.
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
export function ActivityView() {
|
||||
const { t } = useTranslation();
|
||||
const [entries, setEntries] = useState<ActivityEntry[]>([]);
|
||||
const [selected, setSelected] = useState<ActivityEntry | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
@@ -153,6 +158,15 @@ export function ActivityView() {
|
||||
];
|
||||
}, [entries, t]);
|
||||
|
||||
// Client-side pagination over the feed (10/page). `page` is clamped at render
|
||||
// so a shrinking feed never leaves us past the last page.
|
||||
const totalPages = Math.max(1, Math.ceil(entries.length / PAGE_SIZE));
|
||||
const safePage = Math.min(page, totalPages);
|
||||
const pageRows = entries.slice(
|
||||
(safePage - 1) * PAGE_SIZE,
|
||||
safePage * PAGE_SIZE,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-10 px-6 py-10">
|
||||
<div>
|
||||
@@ -173,10 +187,11 @@ export function ActivityView() {
|
||||
{t("activity.empty")}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<ol className="flex flex-col">
|
||||
{entries.map((entry, i) => {
|
||||
{pageRows.map((entry, i) => {
|
||||
const Icon = entityIcon[entry.entityType] ?? FileText;
|
||||
const isLast = i === entries.length - 1;
|
||||
const isLast = i === pageRows.length - 1;
|
||||
const context = [
|
||||
entry.actorName,
|
||||
entry.patientName &&
|
||||
@@ -197,7 +212,7 @@ export function ActivityView() {
|
||||
|
||||
<button
|
||||
className={cn(
|
||||
"-mx-2 flex-1 rounded-lg px-2 py-1 text-left transition-colors hover:bg-accent/40",
|
||||
"-mx-2 flex-1 rounded-lg px-2 py-1 text-start transition-colors hover:bg-accent/40",
|
||||
isLast ? "pb-1" : "mb-5",
|
||||
)}
|
||||
onClick={() => setSelected(entry)}
|
||||
@@ -226,6 +241,13 @@ export function ActivityView() {
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
<ListPagination
|
||||
onPageChange={setPage}
|
||||
page={safePage}
|
||||
pageSize={PAGE_SIZE}
|
||||
total={entries.length}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
|
||||
@@ -37,7 +37,7 @@ export function TrendCard({
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
className="w-full text-left"
|
||||
className="w-full text-start"
|
||||
disabled={!hasData}
|
||||
onClick={() => setOpen(true)}
|
||||
type="button"
|
||||
|
||||
@@ -314,9 +314,9 @@ export function AppointmentsView() {
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="w-full pl-9 sm:w-64"
|
||||
className="w-full ps-9 sm:w-64"
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder={t("appointments.searchPlaceholder")}
|
||||
value={query}
|
||||
|
||||
@@ -145,7 +145,7 @@ export function CalendarDialog({
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<ChevronLeft />
|
||||
<ChevronLeft className="rtl:rotate-180" />
|
||||
</Button>
|
||||
<Button
|
||||
aria-label="Next month"
|
||||
@@ -154,7 +154,7 @@ export function CalendarDialog({
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<ChevronRight />
|
||||
<ChevronRight className="rtl:rotate-180" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -182,7 +182,7 @@ export function CalendarDialog({
|
||||
return (
|
||||
<button
|
||||
className={cn(
|
||||
"flex min-h-22 flex-col gap-1 rounded-lg border p-1.5 text-left align-top transition-colors hover:bg-accent/50",
|
||||
"flex min-h-22 flex-col gap-1 rounded-lg border p-1.5 text-start align-top transition-colors hover:bg-accent/50",
|
||||
inMonth
|
||||
? "bg-card/30"
|
||||
: "bg-transparent text-muted-foreground/40",
|
||||
|
||||
@@ -5,6 +5,7 @@ import { type ReactNode, useEffect, useRef } from "react";
|
||||
|
||||
import { useAiAccess } from "@/lib/ai-policy";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { applyStoredLanguage } from "@/lib/language";
|
||||
import { canAccessRoute, defaultLandingFor, useActiveRole } from "@/lib/roles";
|
||||
|
||||
// Authoritative client-side gate for the app shell. Requires a session and an
|
||||
@@ -24,6 +25,16 @@ export function AppAuthGuard({ children }: { children: ReactNode }) {
|
||||
const hasUser = Boolean(session?.user);
|
||||
const activeOrgId = session?.session?.activeOrganizationId ?? null;
|
||||
|
||||
// Adopt the language saved on the backend once signed in, so the UI language
|
||||
// roams across devices. Best-effort and one-shot; localStorage stays the
|
||||
// offline source of truth.
|
||||
const languageSynced = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!hasUser || languageSynced.current) return;
|
||||
languageSynced.current = true;
|
||||
void applyStoredLanguage();
|
||||
}, [hasUser]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isPending) return;
|
||||
if (!hasUser) {
|
||||
|
||||
@@ -269,7 +269,7 @@ export function ActionPreviewCard({
|
||||
</span>
|
||||
{editable ? (
|
||||
<Button
|
||||
className="ml-auto"
|
||||
className="ms-auto"
|
||||
onClick={() => setEditOpen(true)}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
|
||||
@@ -60,7 +60,7 @@ export function AiSetupNotice() {
|
||||
</div>
|
||||
<button
|
||||
aria-label={t("chat.setupNotice.dismiss")}
|
||||
className="-mr-1 shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||
className="-me-1 shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||
onClick={() => setDismissed(true)}
|
||||
type="button"
|
||||
>
|
||||
|
||||
@@ -115,7 +115,7 @@ export function BatchActionPreviewCard({
|
||||
<span className="font-medium text-sm">
|
||||
{t("chat.actionCard.batch.title", { count: items.length })}
|
||||
</span>
|
||||
<Badge className="ml-auto gap-1" variant="secondary">
|
||||
<Badge className="ms-auto gap-1" variant="secondary">
|
||||
<Sparkles className="size-3" />
|
||||
AI
|
||||
</Badge>
|
||||
|
||||
@@ -104,9 +104,9 @@ export function ChatHistoryPanel() {
|
||||
{t("chat.history.startNew")}
|
||||
</Button>
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-2.5 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-2.5 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="pl-8"
|
||||
className="ps-8"
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={t("chat.history.search")}
|
||||
value={query}
|
||||
@@ -123,7 +123,7 @@ export function ChatHistoryPanel() {
|
||||
return (
|
||||
<button
|
||||
className={cn(
|
||||
"group flex items-center gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors hover:bg-accent",
|
||||
"group flex items-center gap-2 rounded-md px-2 py-2 text-start text-sm transition-colors hover:bg-accent",
|
||||
active
|
||||
? "bg-accent text-foreground"
|
||||
: "text-muted-foreground",
|
||||
|
||||
@@ -242,7 +242,7 @@ export function ChatInput({
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={cn(contextPill, "ml-0.5")}
|
||||
className={cn(contextPill, "ms-0.5")}
|
||||
onClick={() => {
|
||||
setAddKey((k) => k + 1);
|
||||
setAddOpen(true);
|
||||
@@ -258,7 +258,7 @@ export function ChatInput({
|
||||
<ModePicker
|
||||
mode={mode}
|
||||
onModeChange={onModeChange}
|
||||
triggerClassName={cn(pillButton, "mr-1")}
|
||||
triggerClassName={cn(pillButton, "me-1")}
|
||||
/>
|
||||
<button
|
||||
aria-label={
|
||||
|
||||
@@ -421,7 +421,7 @@ export function ChatPanel() {
|
||||
</div>
|
||||
<button
|
||||
aria-label={t("chat.error.dismiss")}
|
||||
className="-mr-1 shrink-0 rounded-md p-1 text-destructive-foreground/70 transition-colors hover:bg-destructive/10 hover:text-destructive-foreground"
|
||||
className="-me-1 shrink-0 rounded-md p-1 text-destructive-foreground/70 transition-colors hover:bg-destructive/10 hover:text-destructive-foreground"
|
||||
onClick={() => setErrorDismissed(true)}
|
||||
type="button"
|
||||
>
|
||||
|
||||
@@ -196,7 +196,7 @@ export function ImportPreviewCard({
|
||||
<span className="text-sm font-medium">{t("chat.importCard.title")}</span>
|
||||
{status === "pending" && records.length > 0 ? (
|
||||
<Button
|
||||
className="ml-auto"
|
||||
className="ms-auto"
|
||||
onClick={() => setReviewOpen(true)}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
@@ -289,7 +289,7 @@ export function ImportPreviewCard({
|
||||
t("chat.importCard.unnamed");
|
||||
return (
|
||||
<button
|
||||
className="flex items-start gap-2 rounded-xl border bg-card/30 p-3 text-left transition-colors hover:bg-accent"
|
||||
className="flex items-start gap-2 rounded-xl border bg-card/30 p-3 text-start transition-colors hover:bg-accent"
|
||||
key={index}
|
||||
onClick={() => setEditingIndex(index)}
|
||||
type="button"
|
||||
|
||||
@@ -16,7 +16,7 @@ export function InventoryListCard({ items }: { items: InventoryItem[] }) {
|
||||
<div className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<Boxes className="size-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">{t("chat.lists.inventory")}</span>
|
||||
<Badge className="ml-auto" variant="secondary">
|
||||
<Badge className="ms-auto" variant="secondary">
|
||||
{items.length}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
@@ -71,11 +71,11 @@ const statusVariant: Record<Patient["status"], BadgeVariant> = {
|
||||
// plus a subtle clickable affordance (they open a detail dialog). Compact cards
|
||||
// size to their own (short) content — see `items-start` in PatientResult.
|
||||
const rowCard =
|
||||
"w-72 shrink-0 cursor-pointer gap-0 text-left outline-none transition hover:bg-accent/30 hover:ring-foreground/20 focus-visible:ring-2 focus-visible:ring-ring";
|
||||
"w-72 shrink-0 cursor-pointer gap-0 text-start outline-none transition hover:bg-accent/30 hover:ring-foreground/20 focus-visible:ring-2 focus-visible:ring-ring";
|
||||
|
||||
// Same footprint as `rowCard` but with no clickable affordance — used when a
|
||||
// card has nothing extra to reveal, so it shouldn't promise "Click for more".
|
||||
const rowCardStatic = "w-72 shrink-0 gap-0 text-left";
|
||||
const rowCardStatic = "w-72 shrink-0 gap-0 text-start";
|
||||
|
||||
// COSS Card has no `size` variant; recreate the old compact ("sm") density by
|
||||
// tightening the inner section padding from p-6 → p-4 via data-slot selectors.
|
||||
@@ -196,7 +196,7 @@ function ExpandableCard({
|
||||
{children}
|
||||
<div className="flex items-center gap-1 px-4 pt-2 pb-3 text-muted-foreground text-xs">
|
||||
{t("patientCard.clickForMore")}
|
||||
<ArrowRight className="size-3" />
|
||||
<ArrowRight className="size-3 rtl:rotate-180" />
|
||||
</div>
|
||||
</DialogTrigger>
|
||||
<DialogPopup className="max-h-[80dvh] sm:max-w-lg">
|
||||
|
||||
@@ -724,7 +724,7 @@ export function PatientFormDialog({
|
||||
|
||||
<DialogFooter className="flex-col items-stretch gap-2 sm:flex-row sm:items-center">
|
||||
{error && (
|
||||
<p className="text-sm text-destructive sm:mr-auto">{error}</p>
|
||||
<p className="text-sm text-destructive sm:me-auto">{error}</p>
|
||||
)}
|
||||
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||
{t("patientForm.cancel")}
|
||||
|
||||
@@ -31,7 +31,7 @@ function Shell({
|
||||
<div className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<Icon className="size-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">{title}</span>
|
||||
<Badge className="ml-auto" variant="secondary">
|
||||
<Badge className="ms-auto" variant="secondary">
|
||||
{rows.length}
|
||||
</Badge>
|
||||
</div>
|
||||
@@ -123,7 +123,7 @@ export function AppointmentListCard({
|
||||
{range ? (
|
||||
<span className="text-muted-foreground text-xs">{range}</span>
|
||||
) : null}
|
||||
<Badge className="ml-auto" variant="secondary">
|
||||
<Badge className="ms-auto" variant="secondary">
|
||||
{appointments.length}
|
||||
</Badge>
|
||||
</div>
|
||||
@@ -157,7 +157,7 @@ export function AppointmentListCard({
|
||||
</span>
|
||||
<Button render={<Link href={href} />} size="sm" variant="ghost">
|
||||
{t("chat.lists.viewInCalendar")}
|
||||
<ChevronRight className="size-4" />
|
||||
<ChevronRight className="size-4 rtl:rotate-180" />
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
@@ -1,10 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import type * as React from "react";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
|
||||
import i18n from "@/lib/i18n/config";
|
||||
import i18n, { dirFor } from "@/lib/i18n/config";
|
||||
|
||||
export function I18nProvider({ children }: { children: React.ReactNode }) {
|
||||
// Keep <html lang/dir> in sync with the active language. The inline script in
|
||||
// app/layout.tsx sets these before first paint (avoiding an RTL flash); this
|
||||
// effect keeps them correct after hydration and on every language switch.
|
||||
useEffect(() => {
|
||||
const apply = (lng: string) => {
|
||||
const root = document.documentElement;
|
||||
root.lang = lng;
|
||||
root.dir = dirFor(lng);
|
||||
};
|
||||
apply(i18n.resolvedLanguage ?? i18n.language);
|
||||
i18n.on("languageChanged", apply);
|
||||
return () => {
|
||||
i18n.off("languageChanged", apply);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return <I18nextProvider i18n={i18n}>{children}</I18nextProvider>;
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ export function InvoiceDetailSheet({
|
||||
<SheetTitle className="flex items-center gap-2">
|
||||
{invoice.number}
|
||||
<AiBadge source={invoice.source} />
|
||||
<Badge className="ml-auto" variant={statusVariant[invoice.status]}>
|
||||
<Badge className="ms-auto" variant={statusVariant[invoice.status]}>
|
||||
{t(`invoices.status.${invoice.status}`)}
|
||||
</Badge>
|
||||
</SheetTitle>
|
||||
@@ -222,7 +222,7 @@ export function InvoiceDetailSheet({
|
||||
<span className="shrink-0 text-muted-foreground text-xs tabular-nums">
|
||||
{li.quantity} × {formatMoney(li.unitPrice)}
|
||||
</span>
|
||||
<span className="w-20 shrink-0 text-right font-medium text-foreground tabular-nums">
|
||||
<span className="w-20 shrink-0 text-end font-medium text-foreground tabular-nums">
|
||||
{formatMoney(li.quantity * li.unitPrice)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ListPagination } from "@/components/ui/list-pagination";
|
||||
import {
|
||||
formatInvoiceDate,
|
||||
formatMoney,
|
||||
@@ -30,10 +31,14 @@ const statusVariant: Record<
|
||||
void: "destructive",
|
||||
};
|
||||
|
||||
// Invoices shown per page before paginating.
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
export function InvoicesView() {
|
||||
const { t } = useTranslation();
|
||||
const [list, setList] = useState<Invoice[]>([]);
|
||||
const [query, setQuery] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
|
||||
const [selected, setSelected] = useState<Invoice | null>(null);
|
||||
@@ -70,6 +75,15 @@ export function InvoicesView() {
|
||||
);
|
||||
}, [list, search]);
|
||||
|
||||
// Client-side pagination over the filtered list (10/page); clamp at render so a
|
||||
// shrinking list never leaves us past the last page.
|
||||
const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
|
||||
const safePage = Math.min(page, totalPages);
|
||||
const pageRows = filtered.slice(
|
||||
(safePage - 1) * PAGE_SIZE,
|
||||
safePage * PAGE_SIZE,
|
||||
);
|
||||
|
||||
const kpis = useMemo(() => {
|
||||
const unpaid = list
|
||||
.filter((i) => i.status === "draft" || i.status === "sent")
|
||||
@@ -121,10 +135,13 @@ export function InvoicesView() {
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="w-full pl-9 sm:w-64"
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
className="w-full ps-9 sm:w-64"
|
||||
onChange={(event) => {
|
||||
setQuery(event.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={t("invoices.searchPlaceholder")}
|
||||
value={query}
|
||||
/>
|
||||
@@ -161,9 +178,9 @@ export function InvoicesView() {
|
||||
</div>
|
||||
|
||||
<div className="divide-y divide-border overflow-hidden rounded-2xl border bg-card/30">
|
||||
{filtered.map((inv) => (
|
||||
{pageRows.map((inv) => (
|
||||
<button
|
||||
className="flex w-full items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-accent/50"
|
||||
className="flex w-full items-center gap-3 px-4 py-3 text-start transition-colors hover:bg-accent/50"
|
||||
key={inv.id}
|
||||
onClick={() => openInvoice(inv)}
|
||||
type="button"
|
||||
@@ -199,6 +216,13 @@ export function InvoicesView() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ListPagination
|
||||
onPageChange={setPage}
|
||||
page={safePage}
|
||||
pageSize={PAGE_SIZE}
|
||||
total={filtered.length}
|
||||
/>
|
||||
|
||||
<InvoiceFormDialog
|
||||
invoice={editing ?? undefined}
|
||||
mode={formMode}
|
||||
|
||||
@@ -92,7 +92,7 @@ export function LabIntegrationCard({
|
||||
{t("integrations.fhir.cardTitle")}
|
||||
</h2>
|
||||
<Badge
|
||||
className="ml-auto"
|
||||
className="ms-auto"
|
||||
variant={
|
||||
config.status === "connected"
|
||||
? "secondary"
|
||||
@@ -141,9 +141,9 @@ export function LabIntegrationCard({
|
||||
) : (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="pl-9"
|
||||
className="ps-9"
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={t("integrations.fhir.searchPlaceholder")}
|
||||
value={query}
|
||||
@@ -153,7 +153,7 @@ export function LabIntegrationCard({
|
||||
<div className="flex flex-col gap-1">
|
||||
{matches.map((p) => (
|
||||
<button
|
||||
className="flex items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-accent"
|
||||
className="flex items-center gap-3 rounded-lg px-2 py-2 text-start transition-colors hover:bg-accent"
|
||||
key={p.fileNumber}
|
||||
onClick={() => setSelected(p)}
|
||||
type="button"
|
||||
|
||||
@@ -336,7 +336,7 @@ function AddResultDialog({
|
||||
{t("lab.addResult.patient")}
|
||||
</span>
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
aria-activedescendant={
|
||||
matches[activeIndex]
|
||||
@@ -344,7 +344,7 @@ function AddResultDialog({
|
||||
: undefined
|
||||
}
|
||||
autoFocus
|
||||
className="pl-9"
|
||||
className="ps-9"
|
||||
onChange={(event) => {
|
||||
setPatientQuery(event.target.value);
|
||||
setActiveIndex(0);
|
||||
@@ -359,7 +359,7 @@ function AddResultDialog({
|
||||
{matches.map((p, index) => (
|
||||
<button
|
||||
className={cn(
|
||||
"flex items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors",
|
||||
"flex items-center gap-3 rounded-lg px-2 py-2 text-start transition-colors",
|
||||
index === activeIndex
|
||||
? "bg-accent"
|
||||
: "hover:bg-accent",
|
||||
@@ -650,7 +650,7 @@ export function LabView() {
|
||||
}
|
||||
onClick={() => toggle(task.id)}
|
||||
/>
|
||||
<CollapsibleTrigger className="group flex min-w-0 flex-1 items-center gap-3 text-left">
|
||||
<CollapsibleTrigger className="group flex min-w-0 flex-1 items-center gap-3 text-start">
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<span
|
||||
className={cn(
|
||||
@@ -679,7 +679,7 @@ export function LabView() {
|
||||
</CollapsibleTrigger>
|
||||
</div>
|
||||
<CollapsibleContent>
|
||||
<div className="space-y-3 px-4 pb-4 pl-12 text-sm">
|
||||
<div className="space-y-3 px-4 pb-4 ps-12 text-sm">
|
||||
<p
|
||||
className={cn(
|
||||
"whitespace-pre-wrap",
|
||||
|
||||
@@ -124,7 +124,7 @@ export function LoginForm({
|
||||
{t("auth.login.passwordLabel")}
|
||||
</FieldLabel>
|
||||
<Link
|
||||
className="ml-auto inline-block text-sm underline-offset-4 hover:underline"
|
||||
className="ms-auto inline-block text-sm underline-offset-4 hover:underline"
|
||||
href="/forgot-password"
|
||||
>
|
||||
{t("auth.login.forgotPassword")}
|
||||
|
||||
@@ -285,10 +285,10 @@ export function MeetingRoom({
|
||||
</DialogHeader>
|
||||
<DialogPanel className="flex flex-col gap-2">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
aria-label={t("meetings.invite.search")}
|
||||
className="pl-9"
|
||||
className="ps-9"
|
||||
onChange={(e) => setMemberQuery(e.target.value)}
|
||||
placeholder={t("meetings.invite.search")}
|
||||
size="sm"
|
||||
|
||||
@@ -246,13 +246,13 @@ export function MeetingsView() {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group flex w-full items-center gap-1 rounded-lg pr-1 transition-colors hover:bg-accent/50",
|
||||
"group flex w-full items-center gap-1 rounded-lg pe-1 transition-colors hover:bg-accent/50",
|
||||
activeRoom?.id === room.id && "bg-accent hover:bg-accent",
|
||||
)}
|
||||
key={room.id}
|
||||
>
|
||||
<button
|
||||
className="flex min-w-0 flex-1 items-center gap-2.5 rounded-lg px-2 py-2 text-left"
|
||||
className="flex min-w-0 flex-1 items-center gap-2.5 rounded-lg px-2 py-2 text-start"
|
||||
onClick={() => setActiveRoom(room)}
|
||||
type="button"
|
||||
>
|
||||
@@ -352,7 +352,7 @@ export function MeetingsView() {
|
||||
<div className="flex flex-col gap-1">
|
||||
{upcoming.map((e) => (
|
||||
<button
|
||||
className="flex flex-col gap-0.5 rounded-xl border bg-card px-2.5 py-2 text-left transition-colors hover:bg-accent/50"
|
||||
className="flex flex-col gap-0.5 rounded-xl border bg-card px-2.5 py-2 text-start transition-colors hover:bg-accent/50"
|
||||
key={e.id}
|
||||
onClick={() => setSelectedDay(new Date(`${e.date}T00:00:00`))}
|
||||
type="button"
|
||||
|
||||
@@ -159,7 +159,7 @@ export function ScheduleMeetingDialog({
|
||||
return (
|
||||
<button
|
||||
className={cn(
|
||||
"flex items-center gap-3 rounded-lg px-2 py-1.5 text-left transition-colors hover:bg-accent/50",
|
||||
"flex items-center gap-3 rounded-lg px-2 py-1.5 text-start transition-colors hover:bg-accent/50",
|
||||
on && "bg-accent",
|
||||
)}
|
||||
key={m.id}
|
||||
|
||||
@@ -28,7 +28,7 @@ function Row({ label, value }: { label: string; value: ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<dt className="text-muted-foreground text-sm">{label}</dt>
|
||||
<dd className="text-right text-foreground text-sm">{value}</dd>
|
||||
<dd className="text-end text-foreground text-sm">{value}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ function SentAttachment({ att }: { att: MessageAttachment }) {
|
||||
<AttachmentContent>
|
||||
<AttachmentTitle>{att.fileName}</AttachmentTitle>
|
||||
</AttachmentContent>
|
||||
<AttachmentActions className="pr-1.5">
|
||||
<AttachmentActions className="pe-1.5">
|
||||
<AttachmentAction
|
||||
aria-label={t("messages.attach.download")}
|
||||
onClick={() => {
|
||||
@@ -491,10 +491,10 @@ export function MessagesView() {
|
||||
</div>
|
||||
<div className="border-border border-b px-3 py-2">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
aria-label={t("messages.searchPlaceholder")}
|
||||
className="pl-9"
|
||||
className="ps-9"
|
||||
onChange={(e) => setInboxQuery(e.target.value)}
|
||||
placeholder={t("messages.searchPlaceholder")}
|
||||
size="sm"
|
||||
@@ -520,7 +520,7 @@ export function MessagesView() {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex w-full items-center gap-1 rounded-lg pr-2 transition-colors hover:bg-accent/50",
|
||||
"flex w-full items-center gap-1 rounded-lg pe-2 transition-colors hover:bg-accent/50",
|
||||
selected?.id === c.id && "bg-accent hover:bg-accent",
|
||||
)}
|
||||
key={c.id}
|
||||
@@ -544,7 +544,7 @@ export function MessagesView() {
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="flex min-w-0 flex-1 items-center gap-3 rounded-lg py-2 pr-1 text-left"
|
||||
className="flex min-w-0 flex-1 items-center gap-3 rounded-lg py-2 pe-1 text-start"
|
||||
onClick={() => open(c.id)}
|
||||
type="button"
|
||||
>
|
||||
@@ -880,10 +880,10 @@ export function MessagesView() {
|
||||
</DialogHeader>
|
||||
<DialogPanel className="flex flex-col gap-2">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
aria-label={t("messages.compose.searchPlaceholder")}
|
||||
className="pl-9"
|
||||
className="ps-9"
|
||||
onChange={(e) => setMemberQuery(e.target.value)}
|
||||
placeholder={t("messages.compose.searchPlaceholder")}
|
||||
size="sm"
|
||||
@@ -902,7 +902,7 @@ export function MessagesView() {
|
||||
) : (
|
||||
visibleMembers.map((m) => (
|
||||
<button
|
||||
className="flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-accent"
|
||||
className="flex w-full items-center gap-3 rounded-lg px-2 py-2 text-start transition-colors hover:bg-accent"
|
||||
key={m.id}
|
||||
onClick={() => startConversation(m.id)}
|
||||
type="button"
|
||||
@@ -932,10 +932,10 @@ export function MessagesView() {
|
||||
</DialogHeader>
|
||||
<DialogPanel className="flex flex-col gap-2">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
aria-label={t("messages.attach.apptSearchPlaceholder")}
|
||||
className="pl-9"
|
||||
className="ps-9"
|
||||
onChange={(e) => setApptQuery(e.target.value)}
|
||||
placeholder={t("messages.attach.apptSearchPlaceholder")}
|
||||
size="sm"
|
||||
@@ -954,7 +954,7 @@ export function MessagesView() {
|
||||
) : (
|
||||
visibleAppts.map((a) => (
|
||||
<button
|
||||
className="flex w-full flex-col gap-0.5 rounded-lg px-2 py-2 text-left transition-colors hover:bg-accent"
|
||||
className="flex w-full flex-col gap-0.5 rounded-lg px-2 py-2 text-start transition-colors hover:bg-accent"
|
||||
key={a.id}
|
||||
onClick={() => attachAppointment(a)}
|
||||
type="button"
|
||||
|
||||
@@ -153,7 +153,7 @@ export function NotesView() {
|
||||
<div className="divide-y divide-border overflow-hidden rounded-2xl border bg-card/30">
|
||||
{notes.map((n) => (
|
||||
<button
|
||||
className="flex w-full flex-col items-start gap-0.5 px-4 py-3 text-left transition-colors hover:bg-accent/50"
|
||||
className="flex w-full flex-col items-start gap-0.5 px-4 py-3 text-start transition-colors hover:bg-accent/50"
|
||||
key={n.id}
|
||||
onClick={() => openNote(n)}
|
||||
type="button"
|
||||
|
||||
@@ -7,6 +7,7 @@ import { AiBadge } from "@/components/ai-badge";
|
||||
import { PatientFormDialog } from "@/components/chat/patient-form-dialog";
|
||||
import { RecordGraph } from "@/components/graph/record-graph";
|
||||
import { PatientDetail } from "@/components/patients/patient-detail";
|
||||
import { ScribeDialog } from "@/components/patients/scribe-dialog";
|
||||
import { TransferPatientDialog } from "@/components/patients/transfer-patient-dialog";
|
||||
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
|
||||
import {
|
||||
@@ -28,6 +29,7 @@ import { type Appointment, listAppointments } from "@/lib/appointments";
|
||||
import { type Invoice, listInvoices } from "@/lib/invoices";
|
||||
import { deletePatient, getPatient, type Patient } from "@/lib/patients";
|
||||
import { listPrescriptions, type Prescription } from "@/lib/prescriptions";
|
||||
import { useAiAccess } from "@/lib/ai-policy";
|
||||
import { hasClinicalAccess, useActiveRole } from "@/lib/roles";
|
||||
import { notify } from "@/lib/toast";
|
||||
|
||||
@@ -76,9 +78,14 @@ export function PatientDetailSheet({
|
||||
// Deleting a chart is destructive — only offer it once we know the role is
|
||||
// a full clinician (patient:delete), never optimistically.
|
||||
const canDelete = role != null && hasClinicalAccess(role);
|
||||
// The ambient scribe writes a clinical note, so it needs full clinical write
|
||||
// access AND the clinic's AI must be enabled for this member.
|
||||
const { allowed: aiAllowed } = useAiAccess();
|
||||
const canScribe = role != null && hasClinicalAccess(role) && aiAllowed;
|
||||
const [patient, setPatient] = useState<Patient | null>(null);
|
||||
const [status, setStatus] = useState<Status>("loading");
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [scribeOpen, setScribeOpen] = useState(false);
|
||||
const [transferOpen, setTransferOpen] = useState(false);
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
// Graph popped out of the sheet into its own dialog (the sheet closes first).
|
||||
@@ -171,6 +178,7 @@ export function PatientDetailSheet({
|
||||
setEditKey((k) => k + 1);
|
||||
setEditOpen(true);
|
||||
}}
|
||||
onScribe={canScribe ? () => setScribeOpen(true) : undefined}
|
||||
onOpenGraph={() => {
|
||||
onOpenChange(false);
|
||||
setGraphOpen(true);
|
||||
@@ -197,6 +205,15 @@ export function PatientDetailSheet({
|
||||
/>
|
||||
)}
|
||||
|
||||
{patient && (
|
||||
<ScribeDialog
|
||||
onOpenChange={setScribeOpen}
|
||||
onSaved={(updated) => setPatient(updated)}
|
||||
open={scribeOpen}
|
||||
patient={patient}
|
||||
/>
|
||||
)}
|
||||
|
||||
{patient && (
|
||||
<TransferPatientDialog
|
||||
onOpenChange={setTransferOpen}
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowLeftRight, FileDown, Network, Pencil, Trash2 } from "lucide-react";
|
||||
import {
|
||||
ArrowLeftRight,
|
||||
FileDown,
|
||||
Mic,
|
||||
Network,
|
||||
Pencil,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { type ReactNode, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -173,6 +180,7 @@ function RecordHistory({ fileNumber }: { fileNumber: string }) {
|
||||
export function PatientDetail({
|
||||
patient,
|
||||
onEdit,
|
||||
onScribe,
|
||||
onTransfer,
|
||||
onDelete,
|
||||
onOpenGraph,
|
||||
@@ -182,6 +190,8 @@ export function PatientDetail({
|
||||
}: {
|
||||
patient: Patient;
|
||||
onEdit?: () => void;
|
||||
// Opens the ambient AI visit scribe (record/transcribe → draft note).
|
||||
onScribe?: () => void;
|
||||
onTransfer?: () => void;
|
||||
onDelete?: () => void;
|
||||
// Pops the record graph out into its own dialog (closing this sheet).
|
||||
@@ -287,6 +297,12 @@ export function PatientDetail({
|
||||
{t("patients.transfer.action")}
|
||||
</Button>
|
||||
)}
|
||||
{onScribe && (
|
||||
<Button onClick={onScribe} size="sm" type="button" variant="outline">
|
||||
<Mic className="size-4" />
|
||||
{t("scribe.recordVisit")}
|
||||
</Button>
|
||||
)}
|
||||
{onEdit && (
|
||||
<Button onClick={onEdit} size="sm" type="button" variant="outline">
|
||||
<Pencil className="size-4" />
|
||||
@@ -296,7 +312,7 @@ export function PatientDetail({
|
||||
{onDelete && (
|
||||
<Button
|
||||
aria-label={t("patients.delete.action")}
|
||||
className="ml-auto"
|
||||
className="ms-auto"
|
||||
onClick={onDelete}
|
||||
size="sm"
|
||||
type="button"
|
||||
@@ -358,7 +374,7 @@ export function PatientDetail({
|
||||
<div className="divide-y divide-border overflow-hidden rounded-xl border bg-card/30">
|
||||
{files.map((file) => (
|
||||
<button
|
||||
className="flex w-full items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-accent"
|
||||
className="flex w-full items-center gap-2.5 px-3 py-2 text-start transition-colors hover:bg-accent"
|
||||
key={file.id}
|
||||
onClick={() => setOpenFile(file)}
|
||||
type="button"
|
||||
|
||||
@@ -210,7 +210,7 @@ export function AttachmentsSection({
|
||||
key={attachment.id}
|
||||
>
|
||||
<button
|
||||
className="flex min-w-0 flex-1 items-center gap-2.5 text-left"
|
||||
className="flex min-w-0 flex-1 items-center gap-2.5 text-start"
|
||||
onClick={() => setPreview(attachment)}
|
||||
type="button"
|
||||
>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronLeft, ChevronRight, Plus, Search, Smartphone } from "lucide-react";
|
||||
import { Plus, Search, Smartphone } from "lucide-react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -12,34 +12,12 @@ import { PatientDetailSheet } from "@/components/patients/patient-detail-sheet";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationEllipsis,
|
||||
PaginationItem,
|
||||
} from "@/components/ui/pagination";
|
||||
import { ListPagination } from "@/components/ui/list-pagination";
|
||||
import { listPatients, type Patient } from "@/lib/patients";
|
||||
|
||||
// Rows shown per page on the patients table before paginating.
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
// Page numbers to render, with `null` marking an ellipsis gap. Keeps the first,
|
||||
// last, and a small window around the current page so the control stays compact
|
||||
// even with many pages.
|
||||
function pageWindow(current: number, total: number): (number | null)[] {
|
||||
if (total <= 7) {
|
||||
return Array.from({ length: total }, (_, i) => i + 1);
|
||||
}
|
||||
const pages: (number | null)[] = [1];
|
||||
const start = Math.max(2, current - 1);
|
||||
const end = Math.min(total - 1, current + 1);
|
||||
if (start > 2) pages.push(null);
|
||||
for (let p = start; p <= end; p++) pages.push(p);
|
||||
if (end < total - 1) pages.push(null);
|
||||
pages.push(total);
|
||||
return pages;
|
||||
}
|
||||
|
||||
type BadgeVariant = "success" | "info" | "outline";
|
||||
|
||||
// Colour the status for at-a-glance scanning: active patients read as success
|
||||
@@ -137,9 +115,9 @@ export function PatientsView() {
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="w-full pl-9 sm:w-64"
|
||||
className="w-full ps-9 sm:w-64"
|
||||
onChange={(event) => {
|
||||
setQuery(event.target.value);
|
||||
setPage(1);
|
||||
@@ -181,7 +159,7 @@ export function PatientsView() {
|
||||
<div className="mt-8 overflow-hidden rounded-2xl border border-border bg-card/30">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-border border-b text-left text-xs text-muted-foreground uppercase">
|
||||
<tr className="border-border border-b text-start text-xs text-muted-foreground uppercase">
|
||||
<th className="px-4 py-3 font-medium">{t("patients.columns.name")}</th>
|
||||
<th className="px-4 py-3 font-medium">{t("patients.columns.mrn")}</th>
|
||||
<th className="px-4 py-3 font-medium">
|
||||
@@ -273,75 +251,13 @@ export function PatientsView() {
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{!loading && !loadError && patients.length > PAGE_SIZE ? (
|
||||
<div className="mt-4 flex flex-col items-center justify-between gap-3 sm:flex-row">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("patients.pagination.summary", {
|
||||
from: (safePage - 1) * PAGE_SIZE + 1,
|
||||
to: Math.min(safePage * PAGE_SIZE, patients.length),
|
||||
total: patients.length,
|
||||
})}
|
||||
</p>
|
||||
<Pagination
|
||||
aria-label={t("patients.pagination.label")}
|
||||
className="mx-0 w-auto justify-end"
|
||||
>
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
aria-label={t("patients.pagination.previous")}
|
||||
className="gap-1"
|
||||
disabled={safePage === 1}
|
||||
onClick={() => setPage(Math.max(1, safePage - 1))}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
<span className="max-sm:hidden">
|
||||
{t("patients.pagination.previous")}
|
||||
</span>
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
{pageWindow(safePage, totalPages).map((p, i) =>
|
||||
p === null ? (
|
||||
<PaginationItem key={`ellipsis-${i}`}>
|
||||
<PaginationEllipsis />
|
||||
</PaginationItem>
|
||||
) : (
|
||||
<PaginationItem key={p}>
|
||||
<Button
|
||||
aria-current={p === safePage ? "page" : undefined}
|
||||
aria-label={t("patients.pagination.page", { page: p })}
|
||||
onClick={() => setPage(p)}
|
||||
size="icon-sm"
|
||||
type="button"
|
||||
variant={p === safePage ? "outline" : "ghost"}
|
||||
>
|
||||
{p}
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
)
|
||||
)}
|
||||
<PaginationItem>
|
||||
<Button
|
||||
aria-label={t("patients.pagination.next")}
|
||||
className="gap-1"
|
||||
disabled={safePage === totalPages}
|
||||
onClick={() => setPage(Math.min(totalPages, safePage + 1))}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<span className="max-sm:hidden">
|
||||
{t("patients.pagination.next")}
|
||||
</span>
|
||||
<ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
{!loading && !loadError ? (
|
||||
<ListPagination
|
||||
onPageChange={setPage}
|
||||
page={safePage}
|
||||
pageSize={PAGE_SIZE}
|
||||
total={patients.length}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<PatientFormDialog
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
"use client";
|
||||
|
||||
import { Mic, Square, Sparkles, Trash2 } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import {
|
||||
Tabs,
|
||||
TabsList,
|
||||
TabsPanel,
|
||||
TabsTab,
|
||||
} from "@/components/ui/tabs";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { uploadAttachment } from "@/lib/attachments";
|
||||
import type { Encounter, Patient } from "@/lib/patients";
|
||||
import { draftNote, saveNote, transcribeRecording } from "@/lib/scribe";
|
||||
import { notify } from "@/lib/toast";
|
||||
import { ApiError } from "@/lib/api-client";
|
||||
|
||||
type Phase = "input" | "processing" | "review";
|
||||
type InputTab = "record" | "paste";
|
||||
type RecState = "idle" | "recording" | "recorded";
|
||||
|
||||
// Pick a supported audio mime for MediaRecorder (Opus in WebM/OGG is tiny for
|
||||
// speech; Safari falls back to mp4). Returns "" to let the browser choose.
|
||||
function pickAudioMime(): string {
|
||||
if (typeof MediaRecorder === "undefined") return "";
|
||||
const candidates = [
|
||||
"audio/webm;codecs=opus",
|
||||
"audio/webm",
|
||||
"audio/ogg;codecs=opus",
|
||||
"audio/mp4",
|
||||
];
|
||||
return candidates.find((m) => MediaRecorder.isTypeSupported(m)) ?? "";
|
||||
}
|
||||
|
||||
function fmtElapsed(sec: number): string {
|
||||
const m = Math.floor(sec / 60);
|
||||
const s = sec % 60;
|
||||
return `${m}:${String(s).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
// The ambient AI scribe: record or paste a visit conversation, draft a SOAP
|
||||
// encounter note, review it, and append it to the patient record.
|
||||
export function ScribeDialog({
|
||||
patient,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSaved,
|
||||
}: {
|
||||
patient: Patient;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSaved: (updated: Patient) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [phase, setPhase] = useState<Phase>("input");
|
||||
const [tab, setTab] = useState<InputTab>("record");
|
||||
const [recState, setRecState] = useState<RecState>("idle");
|
||||
const [elapsed, setElapsed] = useState(0);
|
||||
const [transcript, setTranscript] = useState("");
|
||||
const [visitType, setVisitType] = useState("");
|
||||
const [draft, setDraft] = useState<Encounter | null>(null);
|
||||
const [veilNote, setVeilNote] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const mediaRef = useRef<MediaRecorder | null>(null);
|
||||
const chunksRef = useRef<Blob[]>([]);
|
||||
const blobRef = useRef<Blob | null>(null);
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
// Tear down any live recording + object state when the dialog closes.
|
||||
const stopTracks = () => {
|
||||
mediaRef.current?.stream.getTracks().forEach((track) => track.stop());
|
||||
mediaRef.current = null;
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
};
|
||||
|
||||
// Stop tracks on unmount.
|
||||
useEffect(() => () => stopTracks(), []);
|
||||
|
||||
// Reset all state for the next open. Called on every close (the parent only
|
||||
// ever closes this dialog through our onOpenChange), so no reset-in-effect.
|
||||
const reset = () => {
|
||||
setPhase("input");
|
||||
setTab("record");
|
||||
setRecState("idle");
|
||||
setElapsed(0);
|
||||
setTranscript("");
|
||||
setVisitType("");
|
||||
setDraft(null);
|
||||
setVeilNote(null);
|
||||
setError(null);
|
||||
chunksRef.current = [];
|
||||
blobRef.current = null;
|
||||
};
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next) {
|
||||
stopTracks();
|
||||
reset();
|
||||
}
|
||||
onOpenChange(next);
|
||||
};
|
||||
|
||||
const startRecording = async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
const mime = pickAudioMime();
|
||||
const recorder = new MediaRecorder(
|
||||
stream,
|
||||
mime ? { mimeType: mime } : undefined,
|
||||
);
|
||||
chunksRef.current = [];
|
||||
recorder.ondataavailable = (e) => {
|
||||
if (e.data.size > 0) chunksRef.current.push(e.data);
|
||||
};
|
||||
recorder.onstop = () => {
|
||||
blobRef.current = new Blob(chunksRef.current, {
|
||||
type: recorder.mimeType || "audio/webm",
|
||||
});
|
||||
setRecState("recorded");
|
||||
};
|
||||
recorder.start();
|
||||
mediaRef.current = recorder;
|
||||
setRecState("recording");
|
||||
setElapsed(0);
|
||||
timerRef.current = setInterval(() => setElapsed((s) => s + 1), 1000);
|
||||
} catch {
|
||||
setError(t("scribe.errors.mic"));
|
||||
}
|
||||
};
|
||||
|
||||
const stopRecording = () => {
|
||||
mediaRef.current?.stop();
|
||||
mediaRef.current?.stream.getTracks().forEach((track) => track.stop());
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
};
|
||||
|
||||
const discardRecording = () => {
|
||||
blobRef.current = null;
|
||||
chunksRef.current = [];
|
||||
setRecState("idle");
|
||||
setElapsed(0);
|
||||
};
|
||||
|
||||
const filenameFor = (blob: Blob): string => {
|
||||
const ext = blob.type.includes("mp4")
|
||||
? "m4a"
|
||||
: blob.type.includes("ogg")
|
||||
? "ogg"
|
||||
: "webm";
|
||||
return `visit-${patient.fileNumber}-${Date.now()}.${ext}`;
|
||||
};
|
||||
|
||||
const generate = async () => {
|
||||
setError(null);
|
||||
setPhase("processing");
|
||||
try {
|
||||
let text = transcript.trim();
|
||||
if (tab === "record") {
|
||||
const blob = blobRef.current;
|
||||
if (!blob) {
|
||||
setError(t("scribe.errors.noRecording"));
|
||||
setPhase("input");
|
||||
return;
|
||||
}
|
||||
// Store the recording as a patient attachment (auditable), then
|
||||
// transcribe it server-side.
|
||||
const file = new File([blob], filenameFor(blob), { type: blob.type });
|
||||
const attachment = await uploadAttachment({
|
||||
file,
|
||||
fileNumber: patient.fileNumber,
|
||||
labKey: "scribe",
|
||||
});
|
||||
const res = await transcribeRecording(attachment.id);
|
||||
text = res.transcript.trim();
|
||||
setTranscript(text);
|
||||
}
|
||||
if (!text) {
|
||||
setError(t("scribe.errors.empty"));
|
||||
setPhase("input");
|
||||
return;
|
||||
}
|
||||
const { draft: note, veil } = await draftNote({
|
||||
fileNumber: patient.fileNumber,
|
||||
transcript: text,
|
||||
visitType: visitType.trim() || undefined,
|
||||
});
|
||||
setDraft(note);
|
||||
setVeilNote(
|
||||
veil.active ? t("scribe.review.veil", { provider: veil.provider }) : null,
|
||||
);
|
||||
setPhase("review");
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : t("scribe.errors.generic"),
|
||||
);
|
||||
setPhase("input");
|
||||
}
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (!draft) return;
|
||||
setPhase("processing");
|
||||
try {
|
||||
const updated = await saveNote(patient.fileNumber, draft);
|
||||
notify.success(t("scribe.saved.title"), patient.name);
|
||||
onSaved(updated);
|
||||
handleOpenChange(false);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : t("scribe.errors.generic"),
|
||||
);
|
||||
setPhase("review");
|
||||
}
|
||||
};
|
||||
|
||||
const busy = phase === "processing";
|
||||
|
||||
return (
|
||||
<Dialog onOpenChange={handleOpenChange} open={open}>
|
||||
<DialogPopup className="flex max-h-[85dvh] flex-col sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Sparkles className="size-4 text-primary" />
|
||||
{t("scribe.title")}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t("scribe.subtitle", { name: patient.name })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogPanel className="min-h-0 flex-1 overflow-y-auto">
|
||||
{phase === "review" && draft ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="scribe-type">{t("scribe.review.type")}</Label>
|
||||
<Input
|
||||
id="scribe-type"
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, type: e.target.value })
|
||||
}
|
||||
value={draft.type}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="scribe-date">{t("scribe.review.date")}</Label>
|
||||
<Input
|
||||
id="scribe-date"
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, date: e.target.value })
|
||||
}
|
||||
type="date"
|
||||
value={draft.date}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="scribe-summary">
|
||||
{t("scribe.review.summary")}
|
||||
</Label>
|
||||
<Textarea
|
||||
className="min-h-56"
|
||||
id="scribe-summary"
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, summary: e.target.value })
|
||||
}
|
||||
value={draft.summary}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("scribe.review.provider", { provider: draft.provider })}
|
||||
</p>
|
||||
{veilNote && (
|
||||
<p className="rounded-lg bg-muted px-3 py-2 text-muted-foreground text-xs">
|
||||
{veilNote}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<Tabs
|
||||
onValueChange={(v) => setTab(v as InputTab)}
|
||||
value={tab}
|
||||
>
|
||||
<TabsList className="w-full">
|
||||
<TabsTab value="record">
|
||||
<Mic className="size-4" />
|
||||
{t("scribe.tabs.record")}
|
||||
</TabsTab>
|
||||
<TabsTab value="paste">{t("scribe.tabs.paste")}</TabsTab>
|
||||
</TabsList>
|
||||
|
||||
<TabsPanel className="pt-3" value="record">
|
||||
<div className="flex flex-col items-center gap-4 py-4">
|
||||
{recState === "recording" ? (
|
||||
<>
|
||||
<div className="flex items-center gap-2 text-destructive">
|
||||
<span className="size-2.5 animate-pulse rounded-full bg-destructive" />
|
||||
<span className="font-mono text-lg tabular-nums">
|
||||
{fmtElapsed(elapsed)}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
onClick={stopRecording}
|
||||
type="button"
|
||||
variant="destructive"
|
||||
>
|
||||
<Square className="size-4" />
|
||||
{t("scribe.record.stop")}
|
||||
</Button>
|
||||
</>
|
||||
) : recState === "recorded" ? (
|
||||
<>
|
||||
<p className="text-foreground text-sm">
|
||||
{t("scribe.record.ready", {
|
||||
duration: fmtElapsed(elapsed),
|
||||
})}
|
||||
</p>
|
||||
<Button
|
||||
onClick={discardRecording}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
{t("scribe.record.discard")}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button onClick={startRecording} type="button">
|
||||
<Mic className="size-4" />
|
||||
{t("scribe.record.start")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</TabsPanel>
|
||||
|
||||
<TabsPanel className="pt-3" value="paste">
|
||||
<Textarea
|
||||
className="min-h-40"
|
||||
onChange={(e) => setTranscript(e.target.value)}
|
||||
placeholder={t("scribe.paste.placeholder")}
|
||||
value={transcript}
|
||||
/>
|
||||
</TabsPanel>
|
||||
|
||||
<div className="mt-4 flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="scribe-visit-type">
|
||||
{t("scribe.visitType.label")}
|
||||
</Label>
|
||||
<Input
|
||||
id="scribe-visit-type"
|
||||
onChange={(e) => setVisitType(e.target.value)}
|
||||
placeholder={t("scribe.visitType.placeholder")}
|
||||
value={visitType}
|
||||
/>
|
||||
</div>
|
||||
<p className="rounded-lg bg-muted px-3 py-2 text-muted-foreground text-xs">
|
||||
{t("scribe.consent")}
|
||||
</p>
|
||||
</div>
|
||||
</Tabs>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="mt-3 text-destructive text-sm" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</DialogPanel>
|
||||
|
||||
<DialogFooter>
|
||||
{phase === "review" ? (
|
||||
<>
|
||||
<Button
|
||||
disabled={busy}
|
||||
onClick={() => setPhase("input")}
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
{t("scribe.review.back")}
|
||||
</Button>
|
||||
<Button disabled={busy} onClick={save} type="button">
|
||||
{busy && <Spinner className="size-4" />}
|
||||
{t("scribe.review.save")}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
disabled={busy}
|
||||
onClick={() => handleOpenChange(false)}
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
{t("scribe.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={
|
||||
busy ||
|
||||
(tab === "record"
|
||||
? recState !== "recorded"
|
||||
: transcript.trim().length === 0)
|
||||
}
|
||||
onClick={generate}
|
||||
type="button"
|
||||
>
|
||||
{busy && <Spinner className="size-4" />}
|
||||
{busy ? t("scribe.processing") : t("scribe.generate")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -35,7 +35,7 @@ function Row({ label, value }: { label: string; value: ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-4 py-2">
|
||||
<span className="text-muted-foreground text-sm">{label}</span>
|
||||
<span className="text-right text-foreground text-sm">{value}</span>
|
||||
<span className="text-end text-foreground text-sm">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -68,7 +68,7 @@ export function InventoryDetailDialog({
|
||||
</span>
|
||||
<span className="min-w-0 truncate">{item.name}</span>
|
||||
<Badge
|
||||
className="ml-auto shrink-0"
|
||||
className="ms-auto shrink-0"
|
||||
variant={availabilityVariant[availability]}
|
||||
>
|
||||
{t(`inventory.availability.${availability}`)}
|
||||
|
||||
@@ -67,7 +67,7 @@ function ItemRow({
|
||||
const descriptor = [item.strength, item.form].filter(Boolean).join(" · ");
|
||||
return (
|
||||
<div
|
||||
className="flex w-full cursor-pointer items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-accent/50"
|
||||
className="flex w-full cursor-pointer items-center gap-3 px-4 py-3 text-start transition-colors hover:bg-accent/50"
|
||||
onClick={onOpen}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
@@ -205,9 +205,9 @@ export function InventoryView() {
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="w-full pl-9 sm:w-64"
|
||||
className="w-full ps-9 sm:w-64"
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder={t("inventory.searchPlaceholder")}
|
||||
value={query}
|
||||
|
||||
@@ -330,9 +330,9 @@ export function PharmacyView() {
|
||||
<p className="text-muted-foreground text-sm">{t("pharmacy.subtitle")}</p>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="w-full pl-9 sm:w-64"
|
||||
className="w-full ps-9 sm:w-64"
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder={t("pharmacy.searchPlaceholder")}
|
||||
value={query}
|
||||
|
||||
@@ -43,7 +43,7 @@ function Field({
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<label className="flex flex-col gap-1.5 text-left">
|
||||
<label className="flex flex-col gap-1.5 text-start">
|
||||
<span className="font-medium text-foreground text-sm">{label}</span>
|
||||
{children}
|
||||
</label>
|
||||
@@ -122,7 +122,7 @@ function ChooseStep({ onPick }: { onPick: (step: Step) => void }) {
|
||||
<div className="grid w-full gap-4 sm:grid-cols-2">
|
||||
{cards.map((c) => (
|
||||
<button
|
||||
className="group flex flex-col items-start gap-4 rounded-3xl border bg-card/40 p-6 text-left transition-colors hover:border-primary/50 hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="group flex flex-col items-start gap-4 rounded-3xl border bg-card/40 p-6 text-start transition-colors hover:border-primary/50 hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
key={c.step}
|
||||
onClick={() => onPick(c.step)}
|
||||
type="button"
|
||||
@@ -133,7 +133,7 @@ function ChooseStep({ onPick }: { onPick: (step: Step) => void }) {
|
||||
<span className="flex flex-col gap-1">
|
||||
<span className="flex items-center gap-1 font-semibold text-lg text-foreground">
|
||||
{c.title}
|
||||
<ChevronRight className="size-4 text-muted-foreground transition-transform group-hover:translate-x-0.5" />
|
||||
<ChevronRight className="size-4 text-muted-foreground transition-transform group-hover:translate-x-0.5 rtl:rotate-180" />
|
||||
</span>
|
||||
<span className="text-muted-foreground text-sm">{c.desc}</span>
|
||||
</span>
|
||||
@@ -151,7 +151,7 @@ function BackButton({ onBack }: { onBack: () => void }) {
|
||||
onClick={onBack}
|
||||
type="button"
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
<ArrowLeft className="size-4 rtl:rotate-180" />
|
||||
{t("portal.back")}
|
||||
</button>
|
||||
);
|
||||
|
||||
@@ -378,11 +378,11 @@ export function AddPrescriptionDialog({
|
||||
) : (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
aria-autocomplete="list"
|
||||
autoFocus
|
||||
className="pl-9"
|
||||
className="ps-9"
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
onKeyDown={onPatientKeyDown}
|
||||
placeholder={t("prescriptions.dialog.searchPlaceholder")}
|
||||
@@ -399,7 +399,7 @@ export function AddPrescriptionDialog({
|
||||
matches.map((p, i) => (
|
||||
<button
|
||||
className={cn(
|
||||
"flex w-full items-center justify-between gap-2 rounded-lg px-2 py-1.5 text-left transition-colors",
|
||||
"flex w-full items-center justify-between gap-2 rounded-lg px-2 py-1.5 text-start transition-colors",
|
||||
i === activeIndex
|
||||
? "bg-accent"
|
||||
: "hover:bg-accent",
|
||||
@@ -442,7 +442,7 @@ export function AddPrescriptionDialog({
|
||||
return (
|
||||
<button
|
||||
className={cn(
|
||||
"flex w-full items-center justify-between gap-2 rounded-lg px-2 py-1.5 text-left transition-colors",
|
||||
"flex w-full items-center justify-between gap-2 rounded-lg px-2 py-1.5 text-start transition-colors",
|
||||
i === medIndex ? "bg-accent" : "hover:bg-accent",
|
||||
)}
|
||||
// Use onMouseDown so the pick fires before the input's
|
||||
|
||||
@@ -147,7 +147,7 @@ export function PrescriptionDetailSheet({
|
||||
<SheetFooter>
|
||||
{onDelete && (
|
||||
<Button
|
||||
className="sm:mr-auto"
|
||||
className="sm:me-auto"
|
||||
onClick={onDelete}
|
||||
type="button"
|
||||
variant="destructive"
|
||||
|
||||
@@ -244,9 +244,9 @@ export function PrescriptionsView() {
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 start-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="w-full pl-9 sm:w-64"
|
||||
className="w-full ps-9 sm:w-64"
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder={t("prescriptions.searchPlaceholder")}
|
||||
value={query}
|
||||
|
||||
@@ -422,7 +422,7 @@ export function EmployeeDetailDialog({
|
||||
<DialogFooter>
|
||||
{editable && member && (
|
||||
<Button
|
||||
className="sm:mr-auto"
|
||||
className="sm:me-auto"
|
||||
onClick={() => onRemove(member)}
|
||||
type="button"
|
||||
variant="destructive"
|
||||
|
||||
@@ -109,7 +109,7 @@ export function SigningPanel() {
|
||||
: t("settings.signing.rotateKey")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="sm:text-right">
|
||||
<div className="sm:text-end">
|
||||
<p className="text-3xl font-semibold tracking-tight">Ed25519</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{key
|
||||
|
||||
@@ -164,11 +164,11 @@ export function CareTeamPanel({
|
||||
{initials(m.name, m.email)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0 flex-1 text-left">
|
||||
<div className="min-w-0 flex-1 text-start">
|
||||
<p className="truncate text-sm font-medium">
|
||||
{m.name || m.email || m.userId}
|
||||
{isSelf && (
|
||||
<span className="ml-1 text-xs text-muted-foreground">
|
||||
<span className="ms-1 text-xs text-muted-foreground">
|
||||
{t("settings.careTeam.you")}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -179,7 +179,7 @@ function IntegrationCard({
|
||||
: t("settings.integrations.test")}
|
||||
</Button>
|
||||
{config.lastSyncAt ? (
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
<span className="ms-auto text-xs text-muted-foreground">
|
||||
{t("settings.integrations.lastSync", {
|
||||
when: new Date(config.lastSyncAt).toLocaleString(),
|
||||
})}
|
||||
|
||||
@@ -108,7 +108,7 @@ export function CopyField({
|
||||
<p className="text-xs text-muted-foreground">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex h-9 w-full items-center gap-2 rounded-3xl bg-input/50 pr-1 pl-3 sm:w-80">
|
||||
<div className="flex h-9 w-full items-center gap-2 rounded-3xl bg-input/50 pe-1 ps-3 sm:w-80">
|
||||
<span className="flex-1 truncate text-sm text-muted-foreground">
|
||||
{value}
|
||||
</span>
|
||||
|
||||
@@ -6,7 +6,15 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Select,
|
||||
SelectItem,
|
||||
SelectPopup,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { DeleteAccountDialog } from "@/components/settings/delete-account-dialog";
|
||||
import {
|
||||
CopyField,
|
||||
@@ -16,6 +24,8 @@ import {
|
||||
ToggleRow,
|
||||
} from "@/components/settings/settings-parts";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { supportedLanguages } from "@/lib/i18n/config";
|
||||
import { persistLanguage } from "@/lib/language";
|
||||
import {
|
||||
getSettings,
|
||||
saveSettings,
|
||||
@@ -53,16 +63,24 @@ const DEFAULT_PREFS: UserPreferences = {
|
||||
};
|
||||
|
||||
export function ProfilePanel() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const { data: session } = authClient.useSession();
|
||||
const user = session?.user;
|
||||
|
||||
// The active UI language — `i18n.changeLanguage` persists the choice to
|
||||
// localStorage (the detector's cache), so it survives reloads.
|
||||
const activeLang = i18n.resolvedLanguage ?? i18n.language;
|
||||
|
||||
const [prefs, setPrefs] = useState<UserPreferences>(DEFAULT_PREFS);
|
||||
const [baseline, setBaseline] = useState<UserPreferences>(DEFAULT_PREFS);
|
||||
const [name, setName] = useState("");
|
||||
const [baselineName, setBaselineName] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
// A language picked in the Select but not yet applied — its presence opens the
|
||||
// confirmation dialog. The Select stays bound to `activeLang`, so cancelling
|
||||
// (clearing this) automatically reverts the shown selection.
|
||||
const [pendingLang, setPendingLang] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
@@ -211,6 +229,32 @@ export function ProfilePanel() {
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
description={t("settings.profile.language.description")}
|
||||
title={t("settings.profile.language.title")}
|
||||
>
|
||||
<SettingsCard className="space-y-1.5 p-5">
|
||||
<FieldLabel>{t("settings.profile.language.label")}</FieldLabel>
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
if (value !== activeLang) setPendingLang(value);
|
||||
}}
|
||||
value={activeLang}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
{supportedLanguages.map((lng) => (
|
||||
<SelectItem key={lng} value={lng}>
|
||||
{t(`settings.profile.language.${lng}`)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
description={t("settings.profile.patientNotificationsDescription")}
|
||||
title={t("settings.profile.patientNotifications")}
|
||||
@@ -287,6 +331,30 @@ export function ProfilePanel() {
|
||||
|
||||
<DeleteAccountDialog onOpenChange={setDeleteOpen} open={deleteOpen} />
|
||||
|
||||
<ConfirmDialog
|
||||
cancelLabel={t("settings.profile.language.cancel")}
|
||||
confirmLabel={t("settings.profile.language.confirmCta")}
|
||||
description={
|
||||
pendingLang
|
||||
? t("settings.profile.language.confirmBody", {
|
||||
language: t(`settings.profile.language.${pendingLang}`),
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
onConfirm={() => {
|
||||
if (pendingLang) {
|
||||
void i18n.changeLanguage(pendingLang);
|
||||
void persistLanguage(pendingLang);
|
||||
}
|
||||
}}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPendingLang(null);
|
||||
}}
|
||||
open={pendingLang !== null}
|
||||
title={t("settings.profile.language.confirmTitle")}
|
||||
variant="default"
|
||||
/>
|
||||
|
||||
{dirty ? (
|
||||
<div className="sticky bottom-4 z-10">
|
||||
<div className="flex items-center justify-between gap-4 rounded-2xl border border-border bg-background/95 px-4 py-3 shadow-lg backdrop-blur">
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { RefreshCw } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
SettingsCard,
|
||||
SettingsSection,
|
||||
} from "@/components/settings/settings-parts";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { getNetworkInfo, getVersionInfo, type VersionInfo } from "@/lib/version";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
@@ -45,6 +47,7 @@ export function VersionPanel() {
|
||||
const { t } = useTranslation();
|
||||
const [info, setInfo] = useState<VersionInfo | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [networkUrls, setNetworkUrls] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -54,6 +57,17 @@ export function VersionPanel() {
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
// "Check for updates" — force a fresh, cache-bypassing lookup on the backend.
|
||||
const checkForUpdates = () => {
|
||||
setChecking(true);
|
||||
getVersionInfo(true)
|
||||
.then(setInfo)
|
||||
.catch(() => {
|
||||
/* keep the last known info on a failed manual check */
|
||||
})
|
||||
.finally(() => setChecking(false));
|
||||
};
|
||||
|
||||
// The most reliable shareable URL is the one the browser is already using —
|
||||
// unless that's localhost, in which case we fall back to the backend's
|
||||
// detected LAN addresses (accurate when not running in Docker's bridge net).
|
||||
@@ -72,7 +86,7 @@ export function VersionPanel() {
|
||||
.catch(() => setNetworkUrls([]));
|
||||
}, [localShareUrl]);
|
||||
|
||||
const statusBadge = loading ? (
|
||||
const statusBadge = loading || checking ? (
|
||||
<Badge tone="muted">{t("settings.version.checking")}</Badge>
|
||||
) : !info || info.latest === null ? (
|
||||
<Badge tone="muted">{t("settings.version.offline")}</Badge>
|
||||
@@ -122,6 +136,20 @@ export function VersionPanel() {
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex justify-end border-t border-border pt-4">
|
||||
<Button
|
||||
disabled={loading || checking}
|
||||
onClick={checkForUpdates}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<RefreshCw className={cn("size-4", checking && "animate-spin")} />
|
||||
{checking
|
||||
? t("settings.version.checking")
|
||||
: t("settings.version.checkNow")}
|
||||
</Button>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ export function MobileSidebarTrigger() {
|
||||
return (
|
||||
<Button
|
||||
aria-label={t("nav.openSidebar")}
|
||||
className="fixed top-3 right-3 z-50 size-9 rounded-full bg-background/80 shadow-sm backdrop-blur md:hidden"
|
||||
className="fixed top-3 end-3 z-50 size-9 rounded-full bg-background/80 shadow-sm backdrop-blur md:hidden"
|
||||
onClick={toggleSidebar}
|
||||
size="icon"
|
||||
variant="outline"
|
||||
|
||||
@@ -66,7 +66,7 @@ export default function DashboardNavigation({ routes }: { routes: Route[] }) {
|
||||
>
|
||||
{route.icon}
|
||||
{!isCollapsed && (
|
||||
<span className="ml-2 flex-1 truncate font-medium text-sm">
|
||||
<span className="ms-2 flex-1 truncate font-medium text-sm">
|
||||
{route.title}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -53,7 +53,7 @@ export function NotificationsPopover() {
|
||||
>
|
||||
<BellIcon className="size-5" />
|
||||
{unread > 0 && (
|
||||
<span className="-top-0.5 -right-0.5 absolute flex min-w-4 items-center justify-center rounded-full bg-primary px-1 font-medium text-[10px] text-primary-foreground leading-4">
|
||||
<span className="-top-0.5 -end-0.5 absolute flex min-w-4 items-center justify-center rounded-full bg-primary px-1 font-medium text-[10px] text-primary-foreground leading-4">
|
||||
{unread > 9 ? "9+" : unread}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -146,13 +146,13 @@ export function NavUser() {
|
||||
</Avatar>
|
||||
{!isCollapsed && (
|
||||
<>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<div className="grid flex-1 text-start text-sm leading-tight">
|
||||
<span className="truncate font-medium">{name}</span>
|
||||
<span className="truncate text-muted-foreground text-xs">
|
||||
{secondary}
|
||||
</span>
|
||||
</div>
|
||||
<ChevronsUpDown className="ml-auto size-4" />
|
||||
<ChevronsUpDown className="ms-auto size-4" />
|
||||
</>
|
||||
)}
|
||||
</MenuTrigger>
|
||||
@@ -167,7 +167,7 @@ export function NavUser() {
|
||||
<Avatar className="size-8">
|
||||
<AvatarFallback>{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<div className="grid flex-1 text-start text-sm leading-tight">
|
||||
<span className="truncate font-medium">{name}</span>
|
||||
<span className="truncate text-muted-foreground text-xs">
|
||||
{secondary}
|
||||
|
||||
@@ -33,7 +33,7 @@ export function AccordionTrigger({
|
||||
<AccordionPrimitive.Header className="flex">
|
||||
<AccordionPrimitive.Trigger
|
||||
className={cn(
|
||||
"flex flex-1 cursor-pointer items-start justify-between gap-4 rounded-md py-4 text-left font-medium text-sm outline-none transition-all focus-visible:ring-[3px] focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-64 data-panel-open:*:data-[slot=accordion-indicator]:rotate-180",
|
||||
"flex flex-1 cursor-pointer items-start justify-between gap-4 rounded-md py-4 text-start font-medium text-sm outline-none transition-all focus-visible:ring-[3px] focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-64 data-panel-open:*:data-[slot=accordion-indicator]:rotate-180",
|
||||
className,
|
||||
)}
|
||||
data-slot="accordion-trigger"
|
||||
|
||||
@@ -94,8 +94,8 @@ const bubbleReactionsVariants = cva(
|
||||
bottom: "bottom-0 translate-y-3/4",
|
||||
},
|
||||
align: {
|
||||
start: "left-3",
|
||||
end: "right-3",
|
||||
start: "start-3",
|
||||
end: "end-3",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationEllipsis,
|
||||
PaginationItem,
|
||||
} from "@/components/ui/pagination";
|
||||
|
||||
// Page numbers to render, with `null` marking an ellipsis gap. Keeps the first,
|
||||
// last, and a small window around the current page so the control stays compact
|
||||
// even with many pages.
|
||||
function pageWindow(current: number, total: number): (number | null)[] {
|
||||
if (total <= 7) {
|
||||
return Array.from({ length: total }, (_, i) => i + 1);
|
||||
}
|
||||
const pages: (number | null)[] = [1];
|
||||
const start = Math.max(2, current - 1);
|
||||
const end = Math.min(total - 1, current + 1);
|
||||
if (start > 2) pages.push(null);
|
||||
for (let p = start; p <= end; p++) pages.push(p);
|
||||
if (end < total - 1) pages.push(null);
|
||||
pages.push(total);
|
||||
return pages;
|
||||
}
|
||||
|
||||
type ListPaginationProps = {
|
||||
/** Current (already-clamped) page, 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
/** Total number of items across all pages. */
|
||||
total: number;
|
||||
onPageChange: (page: number) => void;
|
||||
};
|
||||
|
||||
// Shared client-side pagination control (summary line + prev/page/next nav).
|
||||
// Renders nothing when everything fits on one page. Used by the Patients,
|
||||
// Activity and Invoices lists.
|
||||
export function ListPagination({
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
onPageChange,
|
||||
}: ListPaginationProps) {
|
||||
const { t } = useTranslation();
|
||||
if (total <= pageSize) return null;
|
||||
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||
const safePage = Math.min(Math.max(1, page), totalPages);
|
||||
|
||||
return (
|
||||
<div className="mt-4 flex flex-col items-center justify-between gap-3 sm:flex-row">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("common.pagination.summary", {
|
||||
from: (safePage - 1) * pageSize + 1,
|
||||
to: Math.min(safePage * pageSize, total),
|
||||
total,
|
||||
})}
|
||||
</p>
|
||||
<Pagination
|
||||
aria-label={t("common.pagination.label")}
|
||||
className="mx-0 w-auto justify-end"
|
||||
>
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
aria-label={t("common.pagination.previous")}
|
||||
className="gap-1"
|
||||
disabled={safePage === 1}
|
||||
onClick={() => onPageChange(Math.max(1, safePage - 1))}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<ChevronLeft className="size-4 rtl:rotate-180" />
|
||||
<span className="max-sm:hidden">
|
||||
{t("common.pagination.previous")}
|
||||
</span>
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
{pageWindow(safePage, totalPages).map((p, i) =>
|
||||
p === null ? (
|
||||
<PaginationItem key={`ellipsis-${i}`}>
|
||||
<PaginationEllipsis />
|
||||
</PaginationItem>
|
||||
) : (
|
||||
<PaginationItem key={p}>
|
||||
<Button
|
||||
aria-current={p === safePage ? "page" : undefined}
|
||||
aria-label={t("common.pagination.page", { page: p })}
|
||||
onClick={() => onPageChange(p)}
|
||||
size="icon-sm"
|
||||
type="button"
|
||||
variant={p === safePage ? "outline" : "ghost"}
|
||||
>
|
||||
{p}
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
)
|
||||
)}
|
||||
<PaginationItem>
|
||||
<Button
|
||||
aria-label={t("common.pagination.next")}
|
||||
className="gap-1"
|
||||
disabled={safePage === totalPages}
|
||||
onClick={() => onPageChange(Math.min(totalPages, safePage + 1))}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<span className="max-sm:hidden">
|
||||
{t("common.pagination.next")}
|
||||
</span>
|
||||
<ChevronRight className="size-4 rtl:rotate-180" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -275,7 +275,7 @@ export function MenuSubTrigger({
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ms-auto -me-0.5 opacity-80" />
|
||||
<ChevronRightIcon className="ms-auto -me-0.5 opacity-80 rtl:rotate-180" />
|
||||
</MenuPrimitive.SubmenuTrigger>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ export function PaginationPrevious({
|
||||
size="default"
|
||||
{...props}
|
||||
>
|
||||
<ChevronLeftIcon className="sm:-ms-1" />
|
||||
<ChevronLeftIcon className="sm:-ms-1 rtl:rotate-180" />
|
||||
<span className="max-sm:hidden">Previous</span>
|
||||
</PaginationLink>
|
||||
);
|
||||
@@ -107,7 +107,7 @@ export function PaginationNext({
|
||||
{...props}
|
||||
>
|
||||
<span className="max-sm:hidden">Next</span>
|
||||
<ChevronRightIcon className="sm:-me-1" />
|
||||
<ChevronRightIcon className="sm:-me-1 rtl:rotate-180" />
|
||||
</PaginationLink>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import { cn } from "@/lib/utils";
|
||||
export const Select: typeof SelectPrimitive.Root = SelectPrimitive.Root;
|
||||
|
||||
export const selectTriggerVariants = cva(
|
||||
"relative inline-flex min-h-9 w-full min-w-36 select-none items-center justify-between gap-2 rounded-lg border border-input bg-background not-dark:bg-clip-padding px-[calc(--spacing(3)-1px)] text-left text-base text-foreground shadow-xs/5 outline-none ring-ring/24 transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 focus-visible:border-ring focus-visible:ring-[3px] aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/16 data-disabled:pointer-events-none data-disabled:opacity-64 sm:min-h-8 sm:text-sm dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0 [[data-disabled],:focus-visible,[aria-invalid],[data-pressed]]:shadow-none",
|
||||
"relative inline-flex min-h-9 w-full min-w-36 select-none items-center justify-between gap-2 rounded-lg border border-input bg-background not-dark:bg-clip-padding px-[calc(--spacing(3)-1px)] text-start text-base text-foreground shadow-xs/5 outline-none ring-ring/24 transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 focus-visible:border-ring focus-visible:ring-[3px] aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/16 data-disabled:pointer-events-none data-disabled:opacity-64 sm:min-h-8 sm:text-sm dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0 [[data-disabled],:focus-visible,[aria-invalid],[data-pressed]]:shadow-none",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
|
||||
@@ -33,7 +33,7 @@ const SIDEBAR_WIDTH_ICON: string = "3rem";
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT: string = "b";
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-lg p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-lg p-2 text-start text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
|
||||
@@ -40,7 +40,7 @@ export function UpdateBanner() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed right-4 bottom-4 z-50 flex max-w-sm items-start gap-3 rounded-2xl border border-border bg-card px-4 py-3 shadow-lg">
|
||||
<div className="fixed end-4 bottom-4 z-50 flex max-w-sm items-start gap-3 rounded-2xl border border-border bg-card px-4 py-3 shadow-lg">
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-sm text-foreground">
|
||||
{t("settings.version.banner", { version: latest })}
|
||||
@@ -55,7 +55,7 @@ export function UpdateBanner() {
|
||||
</div>
|
||||
<button
|
||||
aria-label={t("settings.version.bannerDismiss")}
|
||||
className="-mr-1 shrink-0 rounded-lg p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||
className="-me-1 shrink-0 rounded-lg p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||
onClick={dismiss}
|
||||
type="button"
|
||||
>
|
||||
|
||||
@@ -5,14 +5,33 @@ import LanguageDetector from "i18next-browser-languagedetector";
|
||||
import { initReactI18next } from "react-i18next";
|
||||
|
||||
import en from "./locales/en/translation.json";
|
||||
import fr from "./locales/fr/translation.json";
|
||||
import so from "./locales/so/translation.json";
|
||||
import ar from "./locales/ar/translation.json";
|
||||
import de from "./locales/de/translation.json";
|
||||
|
||||
export const defaultNS = "translation";
|
||||
|
||||
// Add new languages here (and a matching JSON under locales/<lng>/translation.json).
|
||||
export const resources = {
|
||||
en: { translation: en },
|
||||
fr: { translation: fr },
|
||||
so: { translation: so },
|
||||
ar: { translation: ar },
|
||||
de: { translation: de },
|
||||
} as const;
|
||||
|
||||
// Languages offered in the Settings → Profile switcher (label rendered there).
|
||||
export const supportedLanguages = ["en", "fr", "so", "ar", "de"] as const;
|
||||
|
||||
// Right-to-left languages. Arabic is our only RTL locale today; keep this and the
|
||||
// inline <head> script in app/layout.tsx (which can't import this module) in sync.
|
||||
export const rtlLanguages = ["ar"] as const;
|
||||
|
||||
/** Writing direction for a BCP-47 language tag (e.g. "ar", "ar-SA"). */
|
||||
export const dirFor = (lng: string | undefined): "rtl" | "ltr" =>
|
||||
lng && rtlLanguages.some((r) => lng.startsWith(r)) ? "rtl" : "ltr";
|
||||
|
||||
if (!i18n.isInitialized) {
|
||||
i18n
|
||||
.use(LanguageDetector)
|
||||
@@ -21,8 +40,8 @@ if (!i18n.isInitialized) {
|
||||
resources,
|
||||
defaultNS,
|
||||
fallbackLng: "en",
|
||||
// Only `en` exists today; keep this in sync with `resources` as languages grow.
|
||||
supportedLngs: ["en"],
|
||||
// Keep this in sync with `resources` as languages grow.
|
||||
supportedLngs: ["en", "fr", "so", "ar", "de"],
|
||||
interpolation: { escapeValue: false },
|
||||
detection: {
|
||||
order: ["localStorage", "navigator", "htmlTag"],
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,48 @@
|
||||
{
|
||||
"scribe": {
|
||||
"recordVisit": "Record visit",
|
||||
"title": "Visit scribe",
|
||||
"subtitle": "Record or paste a visit for {{name}}, then review the drafted note before saving.",
|
||||
"tabs": {
|
||||
"record": "Record",
|
||||
"paste": "Paste transcript"
|
||||
},
|
||||
"record": {
|
||||
"start": "Start recording",
|
||||
"stop": "Stop",
|
||||
"ready": "Recording ready ({{duration}})",
|
||||
"discard": "Discard"
|
||||
},
|
||||
"paste": {
|
||||
"placeholder": "Paste the visit transcript here…"
|
||||
},
|
||||
"visitType": {
|
||||
"label": "Visit type (optional)",
|
||||
"placeholder": "e.g. Follow-up"
|
||||
},
|
||||
"consent": "The audio is stored on the patient's chart. When you use an external AI provider, the recording leaves the clinic to be transcribed — Veil cannot redact speech, so only the drafted note is de-identified.",
|
||||
"generate": "Draft note",
|
||||
"processing": "Working…",
|
||||
"cancel": "Cancel",
|
||||
"review": {
|
||||
"type": "Visit type",
|
||||
"date": "Date",
|
||||
"summary": "Note",
|
||||
"provider": "Provider: {{provider}}",
|
||||
"veil": "De-identified through Veil before {{provider}}.",
|
||||
"back": "Back",
|
||||
"save": "Save to record"
|
||||
},
|
||||
"saved": {
|
||||
"title": "Visit note saved"
|
||||
},
|
||||
"errors": {
|
||||
"mic": "Couldn't access the microphone. Check browser permissions or paste a transcript instead.",
|
||||
"noRecording": "Record the visit first, or switch to the paste tab.",
|
||||
"empty": "The transcript is empty.",
|
||||
"generic": "Something went wrong. Please try again."
|
||||
}
|
||||
},
|
||||
"common": {
|
||||
"appName": "temetro",
|
||||
"email": "Email",
|
||||
@@ -6,7 +50,14 @@
|
||||
"signIn": "Sign in",
|
||||
"signUp": "Sign up",
|
||||
"backToSignIn": "Back to sign in",
|
||||
"addedByAi": "Added by AI"
|
||||
"addedByAi": "Added by AI",
|
||||
"pagination": {
|
||||
"label": "Pages",
|
||||
"previous": "Previous",
|
||||
"next": "Next",
|
||||
"page": "Page {{page}}",
|
||||
"summary": "Showing {{from}}–{{to}} of {{total}}"
|
||||
}
|
||||
},
|
||||
"auth": {
|
||||
"login": {
|
||||
@@ -222,13 +273,6 @@
|
||||
"loading": "Loading patients…",
|
||||
"empty": "No patients found.",
|
||||
"loadError": "Failed to load patients.",
|
||||
"pagination": {
|
||||
"label": "Patient pages",
|
||||
"previous": "Previous",
|
||||
"next": "Next",
|
||||
"page": "Page {{page}}",
|
||||
"summary": "Showing {{from}}–{{to}} of {{total}}"
|
||||
},
|
||||
"columns": {
|
||||
"name": "Name",
|
||||
"mrn": "MRN",
|
||||
@@ -1520,6 +1564,7 @@
|
||||
"current": "Current version",
|
||||
"latest": "Latest release",
|
||||
"checking": "Checking for updates…",
|
||||
"checkNow": "Check for updates",
|
||||
"upToDate": "Up to date",
|
||||
"updateAvailable": "Update available",
|
||||
"offline": "Couldn't reach the update server",
|
||||
@@ -1683,6 +1728,20 @@
|
||||
"professionalLinks": "Professional links",
|
||||
"professionalLinksHint": "Registry or institutional profiles used to verify your identity. They are never shown to patients.",
|
||||
"addLink": "Add link",
|
||||
"language": {
|
||||
"title": "Language",
|
||||
"description": "The language temetro's interface is shown in on this device.",
|
||||
"label": "Display language",
|
||||
"en": "English",
|
||||
"fr": "Français",
|
||||
"so": "Soomaali",
|
||||
"ar": "العربية",
|
||||
"de": "Deutsch",
|
||||
"confirmTitle": "Change display language?",
|
||||
"confirmBody": "Switch the interface to {{language}}? The app will reload its text in the new language.",
|
||||
"confirmCta": "Change language",
|
||||
"cancel": "Cancel"
|
||||
},
|
||||
"patientNotifications": "Patient notifications",
|
||||
"patientNotificationsDescription": "Emails sent to patients about their records, results, and pending approvals",
|
||||
"accountNotifications": "Account notifications",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,43 @@
|
||||
import i18n, { supportedLanguages } from "@/lib/i18n/config";
|
||||
import { getSettings, saveSettings } from "@/lib/settings";
|
||||
|
||||
// The user's chosen UI language roams across devices via the backend
|
||||
// `user_settings` preferences map (localStorage stays the offline source of
|
||||
// truth). We store it under this key alongside notification preferences.
|
||||
const LANG_KEY = "language";
|
||||
|
||||
const isSupported = (value: unknown): value is string =>
|
||||
typeof value === "string" &&
|
||||
(supportedLanguages as readonly string[]).includes(value);
|
||||
|
||||
/**
|
||||
* Persist the chosen language to the backend, merging into existing preferences
|
||||
* so notification toggles aren't clobbered (PUT replaces the whole map).
|
||||
* Best-effort: failures are swallowed since localStorage already holds the choice.
|
||||
*/
|
||||
export async function persistLanguage(lang: string): Promise<void> {
|
||||
try {
|
||||
const current = await getSettings();
|
||||
if (current[LANG_KEY] === lang) return;
|
||||
await saveSettings({ ...current, [LANG_KEY]: lang });
|
||||
} catch {
|
||||
// Ignore — the language is already applied and cached in localStorage.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* On app load, adopt the language saved on the backend if it differs from the
|
||||
* locally detected one (roaming to a new device). No-op when offline or when the
|
||||
* stored value matches; localStorage remains authoritative otherwise.
|
||||
*/
|
||||
export async function applyStoredLanguage(): Promise<void> {
|
||||
try {
|
||||
const current = await getSettings();
|
||||
const lang = current[LANG_KEY];
|
||||
if (isSupported(lang) && lang !== (i18n.resolvedLanguage ?? i18n.language)) {
|
||||
await i18n.changeLanguage(lang);
|
||||
}
|
||||
} catch {
|
||||
// Ignore — unauthenticated or offline; keep the detected language.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Client for the ambient AI visit-scribe API. The dialog records (or accepts a
|
||||
// pasted transcript of) a clinician↔patient visit, transcribes it, drafts a
|
||||
// structured encounter note, and — after the clinician reviews it — appends the
|
||||
// note to the patient record (the same write-approval gate as the chat agent).
|
||||
|
||||
import { apiFetch } from "@/lib/api-client";
|
||||
import type { Encounter, Patient } from "@/lib/patients";
|
||||
|
||||
export type ScribeVeil = {
|
||||
active: boolean;
|
||||
level: string;
|
||||
classes: string[];
|
||||
provider: string;
|
||||
};
|
||||
|
||||
// Turn a stored audio attachment into a raw transcript (server streams it to the
|
||||
// user's OpenAI/Gemini speech provider). Audio does NOT pass through Veil.
|
||||
export function transcribeRecording(
|
||||
attachmentId: string,
|
||||
): Promise<{ transcript: string }> {
|
||||
return apiFetch<{ transcript: string }>("/api/scribe/transcribe", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ attachmentId }),
|
||||
});
|
||||
}
|
||||
|
||||
// Draft an encounter note from a transcript. The transcript + patient context
|
||||
// are de-identified through Veil before any external call; the draft is never
|
||||
// saved automatically.
|
||||
export function draftNote(input: {
|
||||
fileNumber: string;
|
||||
transcript: string;
|
||||
visitType?: string;
|
||||
date?: string;
|
||||
}): Promise<{ draft: Encounter; veil: ScribeVeil }> {
|
||||
return apiFetch<{ draft: Encounter; veil: ScribeVeil }>("/api/scribe/draft", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
// The approval step: append the reviewed note to the patient record.
|
||||
export function saveNote(
|
||||
fileNumber: string,
|
||||
encounter: Encounter,
|
||||
): Promise<Patient> {
|
||||
return apiFetch<Patient>("/api/scribe/save", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ fileNumber, encounter }),
|
||||
});
|
||||
}
|
||||
@@ -14,8 +14,8 @@ export type NetworkInfo = {
|
||||
urls: string[];
|
||||
};
|
||||
|
||||
export function getVersionInfo(): Promise<VersionInfo> {
|
||||
return apiFetch<VersionInfo>("/api/version");
|
||||
export function getVersionInfo(force = false): Promise<VersionInfo> {
|
||||
return apiFetch<VersionInfo>(`/api/version${force ? "?refresh=1" : ""}`);
|
||||
}
|
||||
|
||||
export function getNetworkInfo(): Promise<NetworkInfo> {
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.2.3",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
"lint": "eslint",
|
||||
"check-locales": "node scripts/check-locales.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/react": "^3.0.206",
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env node
|
||||
// Locale parity check: every locale under lib/i18n/locales must have the same set
|
||||
// of logical keys as English, with matching {{interpolation}} placeholders.
|
||||
//
|
||||
// "Logical key" collapses i18next plural suffixes: `foo`, `foo_one`, `foo_other`,
|
||||
// `foo_zero`, `foo_two`, `foo_few`, `foo_many` all map to the logical key `foo`.
|
||||
// This lets Arabic carry six CLDR plural forms where English has two, without the
|
||||
// check flagging a mismatch.
|
||||
//
|
||||
// Exit code is non-zero if any locale is missing/extra keys or has a placeholder
|
||||
// mismatch. Arabic count-keys missing the full six CLDR forms are warnings only.
|
||||
|
||||
import { readFileSync, readdirSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const localesDir = join(here, "..", "lib", "i18n", "locales");
|
||||
const REFERENCE = "en";
|
||||
const PLURAL_SUFFIXES = ["zero", "one", "two", "few", "many", "other"];
|
||||
const AR_REQUIRED = ["zero", "one", "two", "few", "many", "other"];
|
||||
|
||||
/** Flatten a nested object into dotted paths → string values. */
|
||||
function flatten(obj, prefix = "", out = {}) {
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
const path = prefix ? `${prefix}.${key}` : key;
|
||||
if (value && typeof value === "object" && !Array.isArray(value)) {
|
||||
flatten(value, path, out);
|
||||
} else {
|
||||
out[path] = value;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Strip a trailing i18next plural suffix, returning [logicalKey, suffix|null]. */
|
||||
function splitPlural(path) {
|
||||
for (const suffix of PLURAL_SUFFIXES) {
|
||||
if (path.endsWith(`_${suffix}`)) {
|
||||
return [path.slice(0, -(suffix.length + 1)), suffix];
|
||||
}
|
||||
}
|
||||
return [path, null];
|
||||
}
|
||||
|
||||
/** All {{placeholder}} names in a string, sorted and de-duplicated. */
|
||||
function placeholders(value) {
|
||||
if (typeof value !== "string") return [];
|
||||
const found = new Set();
|
||||
for (const match of value.matchAll(/\{\{\s*([\w.-]+)\s*\}\}/g)) {
|
||||
found.add(match[1]);
|
||||
}
|
||||
return [...found].sort();
|
||||
}
|
||||
|
||||
function logicalKeys(flat) {
|
||||
// logicalKey → { suffixes: Set, placeholders: string[] }
|
||||
const map = new Map();
|
||||
for (const [path, value] of Object.entries(flat)) {
|
||||
const [logical, suffix] = splitPlural(path);
|
||||
const entry = map.get(logical) ?? { suffixes: new Set(), placeholders: [] };
|
||||
if (suffix) entry.suffixes.add(suffix);
|
||||
// Placeholders should be identical across plural forms; take the richest set.
|
||||
const ph = placeholders(value);
|
||||
if (ph.length > entry.placeholders.length) entry.placeholders = ph;
|
||||
map.set(logical, entry);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
const load = (lng) =>
|
||||
JSON.parse(readFileSync(join(localesDir, lng, "translation.json"), "utf8"));
|
||||
|
||||
const reference = logicalKeys(flatten(load(REFERENCE)));
|
||||
const locales = readdirSync(localesDir, { withFileTypes: true })
|
||||
.filter((d) => d.isDirectory() && d.name !== REFERENCE)
|
||||
.map((d) => d.name);
|
||||
|
||||
let hadError = false;
|
||||
|
||||
for (const lng of locales) {
|
||||
const flat = flatten(load(lng));
|
||||
const keys = logicalKeys(flat);
|
||||
const errors = [];
|
||||
const warnings = [];
|
||||
|
||||
for (const [key, ref] of reference) {
|
||||
if (!keys.has(key)) {
|
||||
errors.push(`missing key: ${key}`);
|
||||
continue;
|
||||
}
|
||||
const got = keys.get(key);
|
||||
const refPh = ref.placeholders.join(",");
|
||||
const gotPh = got.placeholders.join(",");
|
||||
if (refPh !== gotPh) {
|
||||
errors.push(`placeholder mismatch at ${key}: en[${refPh}] vs ${lng}[${gotPh}]`);
|
||||
}
|
||||
if (lng === "ar" && ref.suffixes.size > 0) {
|
||||
const missing = AR_REQUIRED.filter((s) => !got.suffixes.has(s));
|
||||
if (missing.length) {
|
||||
warnings.push(`ar plural ${key} missing CLDR forms: ${missing.join(", ")}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const key of keys.keys()) {
|
||||
if (!reference.has(key)) errors.push(`extra key not in en: ${key}`);
|
||||
}
|
||||
|
||||
if (errors.length) {
|
||||
hadError = true;
|
||||
console.error(`\n✖ ${lng}: ${errors.length} error(s)`);
|
||||
for (const e of errors) console.error(` - ${e}`);
|
||||
} else {
|
||||
console.log(`✔ ${lng}: parity OK (${reference.size} keys)`);
|
||||
}
|
||||
for (const w of warnings) console.warn(` ⚠ ${w}`);
|
||||
}
|
||||
|
||||
process.exit(hadError ? 1 : 0);
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "temetro",
|
||||
"version": "0.2.3",
|
||||
"version": "0.4.0",
|
||||
"private": true,
|
||||
"devDependencies": {
|
||||
"shadcn": "^4.11.0"
|
||||
|
||||
Reference in New Issue
Block a user