Compare commits

...

6 Commits

Author SHA1 Message Date
e7a3e749d9 Make Treatment and lab Cases usable at phone and tablet widths. 2026-09-19 01:05:14 +03:30
c79bba935b Touch on the FDI chart no longer selects a tooth when you scroll. 2026-09-18 14:12:56 +03:30
4141d88bfd Merge pull request 'Make patient identification the unique identity instead of mobile.' (#84) from feature/minore-features-v1 into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 18m7s
Registry — build, push, deploy / deploy (push) Successful in 1m18s
Reviewed-on: #84
Reviewed-by: admin <admin@localhost>
2026-09-18 03:55:41 +03:30
63058828f1 Make patient identification the unique identity instead of mobile.
mobile stays required but is no longer globally unique.
2026-09-17 23:25:08 +03:30
284067d16b Merge pull request 'Remove organization email; unique orgs by owner and name' (#83) from feature/minore-features-v1 into master
All checks were successful
Registry — build, push, deploy / build-and-push (push) Successful in 58s
Registry — build, push, deploy / deploy (push) Successful in 1m8s
Reviewed-on: #83
Reviewed-by: admin <admin@localhost>
2026-09-17 21:47:14 +03:30
da544f18b7 Remove organization email; unique orgs by owner and name 2026-09-17 20:46:32 +03:30
49 changed files with 674 additions and 336 deletions

View File

@@ -11,7 +11,7 @@ Monorepo: `backend/` (NestJS + Prisma), `frontend/` (Next.js + next-intl), `infr
- **CLINIC** orgs: patients, appointments, treatment, staff.
- **LAB** orgs: cases, tasks, lab workflows.
- Named **patients** are scoped to `createdByOrganizationId`. `mobile` stays globally unique — other-org / walk-in hit `PATIENT_MOBILE_UNAVAILABLE` (no shared row).
- Named **patients** are scoped to `createdByOrganizationId`. `identification` stays globally unique — other-org / walk-in hit `PATIENT_IDENTIFICATION_UNAVAILABLE` (no shared row). `mobile` is not unique.
- Tab access: `TAB_*_READ` / `TAB_*_EDIT` in `backend/src/common/permissions.ts`. EDIT implies READ.
## Agent behavior

View File

@@ -7,6 +7,7 @@ alwaysApply: false
# Patients
- List / get / update / create: **this org** + `isWalkIn: false` (`createdByOrganizationId`).
- `Patient.mobile` stays **globally unique**. Same-org named create returns `{ existing: true }`. Other org, walk-in, or null creator → `PATIENT_MOBILE_UNAVAILABLE` (409). Do **not** return or mention the other clinic’s row.
- `Patient.identification` stays **globally unique**. Same-org named create returns `{ existing: true }`. Other org, walk-in, or null creator → `PATIENT_IDENTIFICATION_UNAVAILABLE` (409). Do **not** return or mention the other clinic’s row.
- `Patient.mobile` is required for named patients but **not** unique.
- Appointment create/update and `POST /treatments` named `patientId`: `ensurePatientInOrg` (named + this org). Walk-in sentinel is per clinic (`walk-in-patient.ts`), hidden from Patients/search/booking.
- History / lab-case lists still query treatments for **this** `organizationId` even if the patient UUID is guessed.

View File

@@ -202,7 +202,7 @@ Use shared `Checkbox` (not native `<input type="checkbox">`) to avoid focus-driv
Walk-in uses one sentinel `Patient` per clinic (`isWalkIn`, hidden from Patients/search/booking). Display via i18n, never the stored name. Named patients are this-org only (`createdByOrganizationId`); another clinic’s mobile is `PATIENT_MOBILE_UNAVAILABLE`, not a shared row. Patient search: same workspace patient with a live visit → no-op; else open today’s strip visit if any; else load latest history into the editor; **no history and no strip visit → do not auto-create**. Detach the previous visit, keep the searched patient, and show an inline editor empty state (`noTreatmentFoundTitle` / `noTreatmentFoundBody`) that points to **New treatment** in the rail (Walk-in, current named patient card, or search).
Walk-in uses one sentinel `Patient` per clinic (`isWalkIn`, hidden from Patients/search/booking). Display via i18n, never the stored name. Named patients are this-org only (`createdByOrganizationId`); another clinic’s identification is `PATIENT_IDENTIFICATION_UNAVAILABLE`, not a shared row. Patient search: same workspace patient with a live visit → no-op; else open today’s strip visit if any; else load latest history into the editor; **no history and no strip visit → do not auto-create**. Detach the previous visit, keep the searched patient, and show an inline editor empty state (`noTreatmentFoundTitle` / `noTreatmentFoundBody`) that points to **New treatment** in the rail (Walk-in, current named patient card, or search).
Draft writes for appointments require provider match (`ensureAppointmentProvider`). Standalone requires `treatment.providerUserId === actor`.

View File

@@ -64,7 +64,7 @@ frontend/src/
**Appointments (quick ref):** Do not delete (or change patient) when `hasTreatment`; codes `APPOINTMENT_HAS_TREATMENT` / `APPOINTMENT_PATIENT_LOCKED`. Past days: no new bookings; edit/delete OK without treatment; with treatment → toast. Appointment delete does not cascade-delete treatments. Working hours: client IANA `timeZone` on create/update — never `Date#getHours()`/`getDay()` on the UTC server. Logical API errors: `AppException` + `errors.*` (never Nest English throws). Patient must belong to this org (`ensurePatientInOrg`). See `.cursor/rules/appointments.mdc`, `.cursor/skills/api-errors/SKILL.md`.
**Patients (quick ref):** List/get/update/create are this-org named patients (`createdByOrganizationId`, `isWalkIn: false`). Mobile stays globally unique. Same-org mobile create returns `existing: true`; other org / walk-in / null creator → `PATIENT_MOBILE_UNAVAILABLE` (409, no leak). See `.cursor/rules/patients.mdc`.
**Patients (quick ref):** List/get/update/create are this-org named patients (`createdByOrganizationId`, `isWalkIn: false`). `identification` stays globally unique; `mobile` is not. Same-org identification create returns `existing: true`; other org / walk-in / null creator → `PATIENT_IDENTIFICATION_UNAVAILABLE` (409, no leak). See `.cursor/rules/patients.mdc`.
**Staff (quick ref):** Owner / `TAB_STAFF_EDIT` can **remove** a password (`POST /staff/members/:id/clear-password`) and copy a setup link — never set one for someone else. Login page unchanged (`passwordHash: null` cannot sign in). `/accept-invite` `password_setup` is password-only. See `.cursor/rules/staff.mdc`.

View File

@@ -2,6 +2,7 @@
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"entryFile": "src/main",
"compilerOptions": {
"deleteOutDir": true
}

View File

@@ -0,0 +1,17 @@
-- Disambiguate duplicate (ownerId, name) before adding unique constraint.
UPDATE "organizations" AS o
SET "name" = o."name" || ' (' || LEFT(o."id", 8) || ')'
FROM (
SELECT "id",
ROW_NUMBER() OVER (PARTITION BY "ownerId", LOWER("name") ORDER BY "createdAt" ASC, "id" ASC) AS rn
FROM "organizations"
) AS d
WHERE o."id" = d."id"
AND d.rn > 1;
-- Drop global organization email uniqueness and column.
DROP INDEX IF EXISTS "organizations_email_key";
ALTER TABLE "organizations" DROP COLUMN IF EXISTS "email";
-- One organization name per owner.
CREATE UNIQUE INDEX "organizations_ownerId_name_key" ON "organizations"("ownerId", "name");

View File

@@ -0,0 +1,14 @@
-- Enforce one name per owner case-insensitively (matches app checks).
-- Rename remaining case-only duplicates before swapping the unique index.
UPDATE "organizations" AS o
SET "name" = o."name" || ' (' || LEFT(o."id", 8) || ')'
FROM (
SELECT "id",
ROW_NUMBER() OVER (PARTITION BY "ownerId", LOWER("name") ORDER BY "createdAt" ASC, "id" ASC) AS rn
FROM "organizations"
) AS d
WHERE o."id" = d."id"
AND d.rn > 1;
DROP INDEX IF EXISTS "organizations_ownerId_name_key";
CREATE UNIQUE INDEX "organizations_ownerId_name_key" ON "organizations" ("ownerId", (LOWER("name")));

View File

@@ -0,0 +1,19 @@
-- Move global unique identity from mobile → identification.
ALTER TABLE "patients" ADD COLUMN "identification" TEXT;
-- Walk-ins: reuse walk-in mobile sentinel (already unique per org).
UPDATE "patients"
SET "identification" = "mobile"
WHERE "isWalkIn" = true;
-- Named / other rows: stable unique backfill from id.
UPDATE "patients"
SET "identification" = '__legacy__:' || "id"
WHERE "identification" IS NULL;
ALTER TABLE "patients" ALTER COLUMN "identification" SET NOT NULL;
CREATE UNIQUE INDEX "patients_identification_key" ON "patients"("identification");
DROP INDEX IF EXISTS "patients_mobile_key";

View File

@@ -68,7 +68,6 @@ model OrganizationType {
model Organization {
id String @id @default(uuid())
name String
email String @unique
phone String?
address String?
@@ -95,6 +94,8 @@ model Organization {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
/// One organization name per owner (different owners may share the same name).
@@unique([ownerId, name])
@@map("organizations")
}
@@ -102,7 +103,8 @@ model Patient {
id String @id @default(uuid())
firstName String
lastName String
mobile String @unique
identification String @unique
mobile String
email String?
dateOfBirth DateTime?
notes String?
@@ -729,7 +731,7 @@ model OrganizationLink {
/// be cached in the browser (see frontend useOrganizationInviteLinkCopy). Regenerating rotates
/// tokenHash and expiresAt on the same invitation row.
///
/// `invitedOrganizationId` points at a placeholder Organization (pending-* email) until accept;
/// `invitedOrganizationId` points at a placeholder Organization until accept;
/// list() joins open invitations to links so the UI can offer "copy invitation link" on the
/// pending connection row (pendingInvitationId on the API response).
model OrganizationInvitation {

View File

@@ -84,7 +84,7 @@ export const ErrorCode = {
APPOINTMENT_NOT_PROVIDER: 'APPOINTMENT_NOT_PROVIDER',
PATIENT_NOT_FOUND: 'PATIENT_NOT_FOUND',
PATIENT_MOBILE_UNAVAILABLE: 'PATIENT_MOBILE_UNAVAILABLE',
PATIENT_IDENTIFICATION_UNAVAILABLE: 'PATIENT_IDENTIFICATION_UNAVAILABLE',
WORKING_HOURS_INVALID: 'WORKING_HOURS_INVALID',
WORKING_HOURS_OWNER_NOT_ALLOWED: 'WORKING_HOURS_OWNER_NOT_ALLOWED',
@@ -126,6 +126,9 @@ export const ErrorCode = {
ORG_INVITE_EXPIRED: 'ORG_INVITE_EXPIRED',
ORG_INVITE_TYPE_MISMATCH: 'ORG_INVITE_TYPE_MISMATCH',
ORG_INVITE_OWNER_HAS_ORG: 'ORG_INVITE_OWNER_HAS_ORG',
ORG_NAME_TAKEN_BY_OWNER: 'ORG_NAME_TAKEN_BY_OWNER',
/** Inviter-facing: invitee owner already has an org with this name. */
ORG_INVITE_NAME_TAKEN: 'ORG_INVITE_NAME_TAKEN',
ORG_UNKNOWN_TYPE: 'ORG_UNKNOWN_TYPE',
ORG_COUNTERPART_NOT_LAB: 'ORG_COUNTERPART_NOT_LAB',
ORG_COUNTERPART_NOT_CLINIC: 'ORG_COUNTERPART_NOT_CLINIC',

View File

@@ -0,0 +1,66 @@
import { HttpStatus } from '@nestjs/common';
import { Prisma, type PrismaClient } from '@prisma/client';
import { AppException, ErrorCode } from '../errors';
type DbClient = Prisma.TransactionClient | PrismaClient;
/** Case-insensitive: one organization name per owner. */
export async function assertOwnerOrganizationNameAvailable(
db: DbClient,
ownerId: string,
name: string,
options?: {
excludeOrganizationId?: string;
conflictCode?: typeof ErrorCode.ORG_NAME_TAKEN_BY_OWNER | typeof ErrorCode.ORG_INVITE_NAME_TAKEN;
},
): Promise<string> {
const trimmed = name.trim();
const existing = await db.organization.findFirst({
where: {
ownerId,
name: { equals: trimmed, mode: 'insensitive' },
...(options?.excludeOrganizationId
? { id: { not: options.excludeOrganizationId } }
: {}),
},
select: { id: true },
});
if (existing) {
throw new AppException(
options?.conflictCode ?? ErrorCode.ORG_NAME_TAKEN_BY_OWNER,
HttpStatus.CONFLICT,
);
}
return trimmed;
}
/** Map concurrent unique(ownerId, name) races to a coded AppException. */
export function rethrowIfOrganizationNameConflict(
error: unknown,
conflictCode:
| typeof ErrorCode.ORG_NAME_TAKEN_BY_OWNER
| typeof ErrorCode.ORG_INVITE_NAME_TAKEN = ErrorCode.ORG_NAME_TAKEN_BY_OWNER,
): never {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === 'P2002'
) {
const target = error.meta?.target;
const fields = Array.isArray(target)
? target.map(String)
: typeof target === 'string'
? [target]
: [];
if (
fields.some(
(f) =>
f === 'ownerId_name' ||
f.includes('ownerId_name') ||
(f.includes('ownerId') && f.includes('name')),
)
) {
throw new AppException(conflictCode, HttpStatus.CONFLICT);
}
}
throw error;
}

View File

@@ -26,11 +26,13 @@ export async function ensureWalkInPatient(
return { id: existing.id, isWalkIn: true };
}
const walkInKey = walkInMobileForOrganization(organizationId);
const created = await prisma.patient.create({
data: {
firstName: 'Walk-in',
lastName: 'Walk-in',
mobile: walkInMobileForOrganization(organizationId),
identification: walkInKey,
mobile: walkInKey,
isWalkIn: true,
createdByOrganizationId: organizationId,
},

View File

@@ -102,7 +102,7 @@ export class AppointmentsService {
},
include: {
patient: {
select: { id: true, firstName: true, lastName: true, mobile: true },
select: { id: true, firstName: true, lastName: true, identification: true, mobile: true },
},
treatment: { select: { id: true } },
},
@@ -168,7 +168,7 @@ export class AppointmentsService {
},
include: {
patient: {
select: { id: true, firstName: true, lastName: true, mobile: true },
select: { id: true, firstName: true, lastName: true, identification: true, mobile: true },
},
},
});
@@ -245,7 +245,7 @@ export class AppointmentsService {
},
include: {
patient: {
select: { id: true, firstName: true, lastName: true, mobile: true },
select: { id: true, firstName: true, lastName: true, identification: true, mobile: true },
},
},
});

View File

@@ -30,6 +30,10 @@ import {
ForgotPasswordVerifyDto,
} from './dto/forgot-password.dto';
import { normalizeIranMobile } from '../../common/utils/mobile.util';
import {
assertOwnerOrganizationNameAvailable,
rethrowIfOrganizationNameConflict,
} from '../../common/utils/organization-name.util';
import { sessionExpiresAtFromNow } from '../../common/jwt-duration';
import { AppException, ErrorCode } from '../../common/errors';
import * as crypto from 'crypto';
@@ -237,8 +241,9 @@ export class AuthService {
* @returns Created user info without password
*/
async register(registerDto: RegisterDto) {
const { password, name, organizationName, organizationEmail, organizationType } = registerDto;
const { password, name, organizationName, organizationType } = registerDto;
const email = registerDto.email.trim().toLowerCase();
const trimmedOrganizationName = organizationName.trim();
if (!RegisterDto.isValidMobile(registerDto.mobile)) {
throw new AppException(ErrorCode.AUTH_REGISTRATION_MOBILE_INVALID, HttpStatus.BAD_REQUEST);
@@ -279,17 +284,13 @@ export class AuthService {
// Create organization
const organization = await tx.organization.create({
data: {
name: organizationName,
email: organizationEmail,
name: trimmedOrganizationName,
owner: {
connect: { id: user.id },
},
plan: {
connect: { name: 'trial' }, // make sure this exists in DB
},
type: {
connect: {
name: organizationType, // 'CLINIC' | 'LAB'
@@ -352,40 +353,46 @@ export class AuthService {
throw new AppException(ErrorCode.AUTH_CREATE_ORG_OWNER_ONLY, HttpStatus.FORBIDDEN);
}
const organization = await this.prisma.$transaction(async (tx) => {
const createdOrganization = await tx.organization.create({
data: {
name: dto.organizationName,
email: dto.organizationEmail,
owner: {
connect: { id: userId },
const organizationName = dto.organizationName.trim();
try {
const organization = await this.prisma.$transaction(async (tx) => {
await assertOwnerOrganizationNameAvailable(tx, userId, organizationName);
const createdOrganization = await tx.organization.create({
data: {
name: organizationName,
owner: {
connect: { id: userId },
},
type: {
connect: { name: dto.organizationType },
},
},
type: {
connect: { name: dto.organizationType },
});
await tx.membership.create({
data: {
userId,
organizationId: createdOrganization.id,
isOwner: true,
},
},
});
return createdOrganization;
});
await tx.membership.create({
return {
success: true,
data: {
userId,
organizationId: createdOrganization.id,
isOwner: true,
organization: {
id: organization.id,
name: organization.name,
},
},
});
return createdOrganization;
});
return {
success: true,
data: {
organization: {
id: organization.id,
name: organization.name,
email: organization.email,
},
},
};
};
} catch (error) {
rethrowIfOrganizationNameConflict(error);
}
}
async getProfile(userId: string) {

View File

@@ -1,16 +1,13 @@
import { IsEmail, IsEnum, IsOptional, IsString, MinLength } from 'class-validator';
import { IsEnum, IsOptional, IsString, MinLength } from 'class-validator';
import { ErrorCode } from '../../../common/errors';
export class CreateOrganizationDto {
@IsString()
@MinLength(2, { message: ErrorCode.VALIDATION_ORGANIZATION_NAME_REQUIRED })
organizationName: string;
@IsEmail({}, { message: ErrorCode.VALIDATION_EMAIL_INVALID })
organizationEmail: string;
organizationName!: string;
@IsEnum(['CLINIC', 'LAB'], { message: ErrorCode.VALIDATION_ORGANIZATION_TYPE_INVALID })
organizationType: 'CLINIC' | 'LAB';
organizationType!: 'CLINIC' | 'LAB';
@IsOptional()
@IsString()

View File

@@ -4,29 +4,26 @@ import { ErrorCode } from '../../../common/errors';
export class RegisterDto {
@IsEmail({}, { message: ErrorCode.VALIDATION_EMAIL_INVALID })
email: string;
email!: string;
@IsString()
@Matches(/^[\d+\s()-]+$/, { message: ErrorCode.VALIDATION_MOBILE_INVALID })
mobile: string;
mobile!: string;
@IsString()
@MinLength(8, { message: ErrorCode.VALIDATION_PASSWORD_TOO_SHORT })
password: string;
password!: string;
@IsString()
@MinLength(2, { message: ErrorCode.VALIDATION_NAME_TOO_SHORT })
name: string;
name!: string;
@IsString()
@MinLength(2, { message: ErrorCode.VALIDATION_ORGANIZATION_NAME_REQUIRED })
organizationName: string;
@IsEmail({}, { message: ErrorCode.VALIDATION_EMAIL_INVALID })
organizationEmail: string;
organizationName!: string;
@IsEnum(['CLINIC', 'LAB'], { message: ErrorCode.VALIDATION_ORGANIZATION_TYPE_INVALID })
organizationType: 'CLINIC' | 'LAB';
organizationType!: 'CLINIC' | 'LAB';
static isValidMobile(mobile: string): boolean {
return isValidIranMobile(mobile);

View File

@@ -1,26 +1,23 @@
import { IsEmail, IsEnum, IsString, MinLength } from 'class-validator';
import { IsEnum, IsString, MinLength } from 'class-validator';
import { ErrorCode } from '../../../common/errors';
export class AcceptOrganizationInviteDto {
@IsString()
@MinLength(1, { message: ErrorCode.VALIDATION_TOKEN_REQUIRED })
token: string;
token!: string;
@IsString()
@MinLength(2, { message: ErrorCode.VALIDATION_ORGANIZATION_NAME_REQUIRED })
organizationName: string;
@IsEmail({}, { message: ErrorCode.VALIDATION_EMAIL_INVALID })
organizationEmail: string;
organizationName!: string;
@IsEnum(['CLINIC', 'LAB'], { message: ErrorCode.VALIDATION_ORGANIZATION_TYPE_INVALID })
organizationType: 'CLINIC' | 'LAB';
organizationType!: 'CLINIC' | 'LAB';
@IsString()
@MinLength(2, { message: ErrorCode.VALIDATION_NAME_TOO_SHORT })
ownerName: string;
ownerName!: string;
@IsString()
@MinLength(8, { message: ErrorCode.VALIDATION_PASSWORD_TOO_SHORT })
password: string;
password!: string;
}

View File

@@ -4,6 +4,10 @@ import { LinkStatus, UserNotificationType } from '@prisma/client';
import * as bcrypt from 'bcrypt';
import { createHash, randomBytes } from 'crypto';
import { PrismaService } from '../../../prisma/prisma.service';
import {
assertOwnerOrganizationNameAvailable,
rethrowIfOrganizationNameConflict,
} from '../../common/utils/organization-name.util';
import { ListLabCasesDto } from '../cases/dto/cases.dto';
import { CasesService } from '../cases/cases.service';
import { LabCaseCommentsService } from '../lab-case-comments/lab-case-comments.service';
@@ -59,8 +63,9 @@ export class OrganizationService {
? {
OR: [
{ name: { contains: q, mode: 'insensitive' } },
{ email: { contains: q, mode: 'insensitive' } },
{ phone: { contains: q, mode: 'insensitive' } },
{ owner: { name: { contains: q, mode: 'insensitive' } } },
{ owner: { email: { contains: q, mode: 'insensitive' } } },
],
}
: {}),
@@ -68,7 +73,6 @@ export class OrganizationService {
select: {
id: true,
name: true,
email: true,
phone: true,
owner: { select: { email: true, name: true } },
},
@@ -92,14 +96,30 @@ export class OrganizationService {
this.prisma.organizationLink.findMany({
where: { organizationAId: organizationId },
include: {
organizationB: { select: { id: true, name: true, email: true, phone: true, type: true } },
organizationB: {
select: {
id: true,
name: true,
phone: true,
type: true,
owner: { select: { email: true } },
},
},
},
orderBy: { createdAt: 'desc' },
}),
this.prisma.organizationLink.findMany({
where: { organizationBId: organizationId },
include: {
organizationA: { select: { id: true, name: true, email: true, phone: true, type: true } },
organizationA: {
select: {
id: true,
name: true,
phone: true,
type: true,
owner: { select: { email: true } },
},
},
},
orderBy: { createdAt: 'desc' },
}),
@@ -129,7 +149,12 @@ export class OrganizationService {
const mapLinkItem = (
l: (typeof linksA)[number] | (typeof linksB)[number],
counterpart: { id: string; name: string; email: string; phone: string | null },
counterpart: {
id: string;
name: string;
phone: string | null;
owner: { email: string };
},
) => {
const invitation = invitationByOrgId.get(counterpart.id);
return {
@@ -137,7 +162,7 @@ export class OrganizationService {
id: l.id,
counterpartOrganizationId: counterpart.id,
organizationName: counterpart.name,
ownerEmail: invitation?.invitedOwnerEmail ?? counterpart.email,
ownerEmail: counterpart.owner.email,
phone: counterpart.phone,
status: l.status,
createdAt: l.createdAt.toISOString(),
@@ -559,16 +584,24 @@ export class OrganizationService {
});
if (!invitedOrg) {
// Placeholder org until acceptInvite; real email is set on acceptance.
invitedOrg = await tx.organization.create({
data: {
name: dto.organizationName.trim(),
email: `pending-${plainToken.slice(0, 12)}@dyolink.local`,
owner: { connect: { id: owner.id } },
type: { connect: { name: invitedType } },
},
select: { id: true },
});
const organizationName = dto.organizationName.trim();
try {
await assertOwnerOrganizationNameAvailable(tx, owner.id, organizationName, {
conflictCode: ErrorCode.ORG_INVITE_NAME_TAKEN,
});
// Placeholder org until acceptInvite; plan stays null until acceptance.
invitedOrg = await tx.organization.create({
data: {
name: organizationName,
owner: { connect: { id: owner.id } },
type: { connect: { name: invitedType } },
},
select: { id: true },
});
} catch (error) {
rethrowIfOrganizationNameConflict(error, ErrorCode.ORG_INVITE_NAME_TAKEN);
}
}
const [aId, bId] =
@@ -625,23 +658,12 @@ export class OrganizationService {
async previewInvite(token: string) {
const invitation = await this.findValidInvitation(token);
let organizationEmail = '';
if (invitation.invitedOrganizationId) {
const invitedOrg = await this.prisma.organization.findUnique({
where: { id: invitation.invitedOrganizationId },
select: { email: true },
});
if (invitedOrg?.email && !invitedOrg.email.includes('@dyolink.local')) {
organizationEmail = invitedOrg.email;
}
}
return {
success: true,
data: {
ownerEmail: invitation.invitedOwnerEmail,
organizationName: invitation.invitedOrganizationName,
organizationType: invitation.invitedOrganizationType,
organizationEmail,
inviterOrganizationName: invitation.inviterOrganization.name,
expiresAt: invitation.expiresAt.toISOString(),
status: invitation.acceptedAt ? 'ACCEPTED' : 'PENDING',
@@ -660,53 +682,60 @@ export class OrganizationService {
throw new AppException(ErrorCode.ORG_INVITE_TYPE_MISMATCH, HttpStatus.BAD_REQUEST);
}
const organizationEmail = dto.organizationEmail.trim().toLowerCase();
const organizationName = dto.organizationName.trim();
const organization = await this.prisma.$transaction(async (tx) => {
const passwordHash = await bcrypt.hash(dto.password, 10);
const ownerEmail = invitation.invitedOwnerEmail;
try {
const organization = await this.prisma.$transaction(async (tx) => {
const passwordHash = await bcrypt.hash(dto.password, 10);
const ownerEmail = invitation.invitedOwnerEmail;
let owner = await tx.user.findUnique({ where: { email: ownerEmail } });
if (!owner) {
owner = await tx.user.create({
data: {
email: ownerEmail,
name: dto.ownerName.trim(),
passwordHash,
trialUsedAt: new Date(),
},
});
} else if (!owner.passwordHash) {
owner = await tx.user.update({
where: { id: owner.id },
data: { passwordHash, name: dto.ownerName.trim(), trialUsedAt: owner.trialUsedAt ?? new Date() },
});
}
let owner = await tx.user.findUnique({ where: { email: ownerEmail } });
if (!owner) {
owner = await tx.user.create({
data: {
email: ownerEmail,
name: dto.ownerName.trim(),
passwordHash,
trialUsedAt: new Date(),
},
});
} else if (!owner.passwordHash) {
owner = await tx.user.update({
where: { id: owner.id },
data: {
passwordHash,
name: dto.ownerName.trim(),
trialUsedAt: owner.trialUsedAt ?? new Date(),
},
});
}
let targetOrganizationId = invitation.invitedOrganizationId;
if (targetOrganizationId) {
await tx.organization.update({
where: { id: targetOrganizationId },
data: {
name: dto.organizationName.trim(),
email: organizationEmail,
owner: { connect: { id: owner.id } },
type: { connect: { name: dto.organizationType } },
plan: { connect: { name: 'trial' } },
},
await assertOwnerOrganizationNameAvailable(tx, owner.id, organizationName, {
excludeOrganizationId: invitation.invitedOrganizationId ?? undefined,
});
} else {
const createdOrg = await tx.organization.create({
data: {
name: dto.organizationName.trim(),
email: organizationEmail,
owner: { connect: { id: owner.id } },
type: { connect: { name: dto.organizationType } },
plan: { connect: { name: 'trial' } },
},
});
targetOrganizationId = createdOrg.id;
}
let targetOrganizationId = invitation.invitedOrganizationId;
if (targetOrganizationId) {
await tx.organization.update({
where: { id: targetOrganizationId },
data: {
name: organizationName,
owner: { connect: { id: owner.id } },
type: { connect: { name: dto.organizationType } },
plan: { connect: { name: 'trial' } },
},
});
} else {
const createdOrg = await tx.organization.create({
data: {
name: organizationName,
owner: { connect: { id: owner.id } },
type: { connect: { name: dto.organizationType } },
plan: { connect: { name: 'trial' } },
},
});
targetOrganizationId = createdOrg.id;
}
const ownerMembership = await tx.membership.findFirst({
where: { userId: owner.id, organizationId: targetOrganizationId },
@@ -745,18 +774,21 @@ export class OrganizationService {
data: {
acceptedAt: new Date(),
invitedOrganizationId: targetOrganizationId,
invitedOrganizationName: dto.organizationName.trim(),
invitedOrganizationName: organizationName,
},
});
return targetOrganizationId;
});
return {
success: true,
data: { organizationId: organization },
message: 'Invitation accepted. Organization trial has started and connection is active.',
};
return {
success: true,
data: { organizationId: organization },
message: 'Invitation accepted. Organization trial has started and connection is active.',
};
} catch (error) {
rethrowIfOrganizationNameConflict(error);
}
}
private async resolveActiveConnectionParties(

View File

@@ -13,17 +13,22 @@ export class CreatePatientDto {
@IsString()
@MinLength(1, { message: ErrorCode.VALIDATION_FIELD_REQUIRED })
@MaxLength(80)
firstName: string;
firstName!: string;
@IsString()
@MinLength(1, { message: ErrorCode.VALIDATION_FIELD_REQUIRED })
@MaxLength(80)
lastName: string;
lastName!: string;
@IsString()
@MinLength(1, { message: ErrorCode.VALIDATION_FIELD_REQUIRED })
@MaxLength(80)
identification!: string;
@IsString()
@MinLength(1, { message: ErrorCode.VALIDATION_FIELD_REQUIRED })
@MaxLength(30)
mobile: string;
mobile!: string;
@IsOptional()
@Transform(emptyStringToUndefined)

View File

@@ -25,7 +25,7 @@ export class PatientsController {
constructor(private readonly patientsService: PatientsService) {}
@Post()
@ApiOperation({ summary: 'Create or return this clinic’s patient by mobile' })
@ApiOperation({ summary: 'Create or return this clinic’s patient by identification' })
create(@Body() createPatientDto: CreatePatientDto, @Req() req) {
const organizationId = this.patientsService.getOrganizationIdFromUser(req.user);
return this.patientsService.create(createPatientDto, organizationId);

View File

@@ -14,10 +14,11 @@ export class PatientsService {
async create(createPatientDto: CreatePatientDto, organizationId: string) {
const firstName = this.requireNonEmptyName(createPatientDto.firstName, 'firstName');
const lastName = this.requireNonEmptyName(createPatientDto.lastName, 'lastName');
const identification = this.requireNonEmptyIdentification(createPatientDto.identification);
const mobile = this.resolveMobile(createPatientDto.mobile);
const existing = await this.prisma.patient.findUnique({
where: { mobile },
where: { identification },
});
if (existing) {
@@ -27,13 +28,14 @@ export class PatientsService {
) {
return { success: true, data: existing, existing: true as const };
}
throw new AppException(ErrorCode.PATIENT_MOBILE_UNAVAILABLE, HttpStatus.CONFLICT);
throw new AppException(ErrorCode.PATIENT_IDENTIFICATION_UNAVAILABLE, HttpStatus.CONFLICT);
}
const patient = await this.prisma.patient.create({
data: {
firstName,
lastName,
identification,
mobile,
email: createPatientDto.email?.trim() || null,
notes: createPatientDto.notes?.trim() || null,
@@ -90,6 +92,7 @@ export class PatientsService {
const data: {
firstName?: string;
lastName?: string;
identification?: string;
mobile?: string;
email?: string | null;
notes?: string | null;
@@ -102,16 +105,19 @@ export class PatientsService {
if (updatePatientDto.lastName !== undefined) {
data.lastName = this.requireNonEmptyName(updatePatientDto.lastName, 'lastName');
}
if (updatePatientDto.mobile !== undefined) {
const mobile = this.resolveMobile(updatePatientDto.mobile);
if (updatePatientDto.identification !== undefined) {
const identification = this.requireNonEmptyIdentification(updatePatientDto.identification);
const taken = await this.prisma.patient.findUnique({
where: { mobile },
select: { id: true, createdByOrganizationId: true, isWalkIn: true },
where: { identification },
select: { id: true },
});
if (taken && taken.id !== id) {
throw new AppException(ErrorCode.PATIENT_MOBILE_UNAVAILABLE, HttpStatus.CONFLICT);
throw new AppException(ErrorCode.PATIENT_IDENTIFICATION_UNAVAILABLE, HttpStatus.CONFLICT);
}
data.mobile = mobile;
data.identification = identification;
}
if (updatePatientDto.mobile !== undefined) {
data.mobile = this.resolveMobile(updatePatientDto.mobile);
}
if (updatePatientDto.email !== undefined) {
data.email = updatePatientDto.email?.trim() || null;
@@ -222,6 +228,16 @@ export class PatientsService {
return trimmed;
}
private requireNonEmptyIdentification(value: string): string {
const trimmed = value?.trim() ?? '';
if (!trimmed) {
throw new AppException(ErrorCode.VALIDATION_FIELD_REQUIRED, HttpStatus.BAD_REQUEST, [
{ field: 'identification', code: ErrorCode.VALIDATION_FIELD_REQUIRED },
]);
}
return trimmed;
}
private async assertCanViewPatients(userId: string, organizationId: string) {
const membership = await this.prisma.membership.findUnique({
where: {

View File

@@ -140,8 +140,6 @@
"stepOrganization": "Organization",
"organizationName": "Organization name",
"organizationNamePlaceholder": "Sunshine Dental Clinic",
"organizationEmail": "Organization email",
"organizationEmailPlaceholder": "contact@sunshineclinic.com",
"organizationType": "Organization type",
"dentalClinic": "Dental Clinic",
"dentalLab": "Dental Lab",
@@ -191,7 +189,6 @@
"passwordUppercase": "Password must contain at least one uppercase letter",
"passwordNumber": "Password must contain at least one number",
"organizationNameMinLength": "Organization name must be at least 2 characters",
"organizationEmailInvalid": "Please enter a valid organization email",
"organizationTypeRequired": "Please select organization type",
"passwordsDoNotMatch": "Passwords don't match",
"mobileRequired": "Mobile number is required",
@@ -404,10 +401,13 @@
"errorSavePatient": "Failed to save patient.",
"firstName": "First name",
"lastName": "Last name",
"identification": "Identification",
"identificationLabel": "Identification:",
"identificationRequired": "Identification is required.",
"mobile": "Mobile",
"mobilePlaceholder": "09121234567",
"mobileLabel": "Mobile:",
"patientAlreadyExists": "A patient with this mobile already exists: {firstName} {lastName}. They were selected for you.",
"patientAlreadyExists": "A patient with this identification already exists: {firstName} {lastName}. They were selected for you.",
"savePatient": "Save Patient",
"dialogTitle": "New patient",
"searchPlaceholder": "Search patients by name, mobile, email",
@@ -725,6 +725,7 @@
"noAppointment": "No appointment",
"walkIn": "Walk-in",
"newTreatment": "New treatment",
"mobileOpenRail": "Patient / history",
"newTreatmentPatientPrompt": "Who is this visit for?",
"newTreatmentUseCurrent": "Use {name}",
"newTreatmentUseCurrentHint": "Start a new visit for the patient already open on this page.",
@@ -954,10 +955,11 @@
"loadingOrganization": "Loading organization...",
"subtitle": "Search organizations, send connection requests to existing accounts, or invitation links when they are not on Nudentic yet.",
"invitationHistory": "Invitation History",
"searchPlaceholder": "Search {counterpart} by name, email, or phone...",
"searchPlaceholder": "Search {counterpart} by name, owner email, or phone...",
"backToList": "Back to list",
"tableOrganization": "Organization",
"tableOwnerEmail": "Owner email",
"tableOwnerName": "Owner name",
"tableDate": "Date",
"tableStatus": "Status",
"tableAction": "Action",
@@ -1236,7 +1238,7 @@
"APPOINTMENT_NOT_FOUND": "Appointment not found.",
"APPOINTMENT_NOT_PROVIDER": "You are not the provider for this appointment.",
"PATIENT_NOT_FOUND": "Patient not found.",
"PATIENT_MOBILE_UNAVAILABLE": "This mobile number cannot be added for this clinic.",
"PATIENT_IDENTIFICATION_UNAVAILABLE": "This identification cannot be added for this clinic.",
"WORKING_HOURS_INVALID": "Working hours are invalid. Check that shifts do not overlap.",
"WORKING_HOURS_OWNER_NOT_ALLOWED": "Set owner working hours from account settings.",
"WORKING_HOURS_CONFLICTS_WITH_APPOINTMENTS": "These hours conflict with upcoming appointments. Reschedule or remove those appointments first.",
@@ -1274,6 +1276,8 @@
"ORG_INVITE_EXPIRED": "This invitation has expired.",
"ORG_INVITE_TYPE_MISMATCH": "Organization type does not match this invitation.",
"ORG_INVITE_OWNER_HAS_ORG": "This owner already has an organization. Find it in search instead of sending an invitation.",
"ORG_NAME_TAKEN_BY_OWNER": "You already have an organization with this name. Choose a different name.",
"ORG_INVITE_NAME_TAKEN": "That owner already has an organization with this name. Choose a different name or find them in search.",
"ORG_UNKNOWN_TYPE": "Unknown organization type.",
"ORG_COUNTERPART_NOT_LAB": "The connected organization is not a lab.",
"ORG_COUNTERPART_NOT_CLINIC": "The connected organization is not a clinic.",

View File

@@ -140,8 +140,6 @@
"stepOrganization": "سازمان",
"organizationName": "نام سازمان",
"organizationNamePlaceholder": "کلینیک دندانپزشکی خورشید",
"organizationEmail": "ایمیل سازمان",
"organizationEmailPlaceholder": "contact@sunshineclinic.com",
"organizationType": "نوع سازمان",
"dentalClinic": "کلینیک دندانپزشکی",
"dentalLab": "لابراتوار دندانپزشکی",
@@ -191,7 +189,6 @@
"passwordUppercase": "رمز عبور باید حداقل شامل یک حرف بزرگ باشد",
"passwordNumber": "رمز عبور باید حداقل شامل یک عدد باشد",
"organizationNameMinLength": "نام سازمان باید حداقل ۲ کاراکتر باشد",
"organizationEmailInvalid": "لطفاً یک ایمیل سازمانی معتبر وارد کنید",
"organizationTypeRequired": "لطفاً نوع سازمان را انتخاب کنید",
"passwordsDoNotMatch": "رمزهای عبور مطابقت ندارند",
"mobileRequired": "شماره موبایل الزامی است",
@@ -404,10 +401,13 @@
"errorSavePatient": "ذخیره بیمار ناموفق بود.",
"firstName": "نام",
"lastName": "نام خانوادگی",
"identification": "شناسه",
"identificationLabel": "شناسه:",
"identificationRequired": "شناسه الزامی است.",
"mobile": "موبایل",
"mobilePlaceholder": "09121234567",
"mobileLabel": "موبایل:",
"patientAlreadyExists": "بیماری با این شماره موبایل از قبل وجود دارد: {firstName} {lastName}. برای شما انتخاب شد.",
"patientAlreadyExists": "بیماری با این شناسه از قبل وجود دارد: {firstName} {lastName}. برای شما انتخاب شد.",
"savePatient": "ذخیره بیمار",
"dialogTitle": "بیمار جدید",
"searchPlaceholder": "جستجوی بیماران بر اساس نام، موبایل، ایمیل",
@@ -726,6 +726,7 @@
"noAppointment": "بدون نوبت",
"walkIn": "بدون نوبت (مراجع)",
"newTreatment": "درمان جدید",
"mobileOpenRail": "بیمار / سابقه",
"newTreatmentPatientPrompt": "این ویزیت برای چه کسی است؟",
"newTreatmentUseCurrent": "استفاده از {name}",
"newTreatmentUseCurrentHint": "ویزیت جدیدی برای بیماری که همین حالا در این صفحه باز است شروع کنید.",
@@ -955,10 +956,11 @@
"loadingOrganization": "در حال بارگذاری سازمان...",
"subtitle": "سازمان‌ها را جستجو کنید، درخواست اتصال به حساب‌های موجود ارسال کنید، یا اگر هنوز در Nudentic نیستند، لینک دعوت ارسال کنید.",
"invitationHistory": "تاریخچه دعوت‌نامه‌ها",
"searchPlaceholder": "جستجوی {counterpart} بر اساس نام، ایمیل یا تلفن...",
"searchPlaceholder": "جستجوی {counterpart} بر اساس نام، ایمیل مالک یا تلفن...",
"backToList": "بازگشت به لیست",
"tableOrganization": "سازمان",
"tableOwnerEmail": "ایمیل مالک",
"tableOwnerName": "نام مالک",
"tableDate": "تاریخ",
"tableStatus": "وضعیت",
"tableAction": "عملیات",
@@ -1237,7 +1239,7 @@
"APPOINTMENT_NOT_FOUND": "نوبت یافت نشد.",
"APPOINTMENT_NOT_PROVIDER": "شما ارائه‌دهنده این نوبت نیستید.",
"PATIENT_NOT_FOUND": "بیمار یافت نشد.",
"PATIENT_MOBILE_UNAVAILABLE": "این شماره موبایل را نمی‌توان برای این کلینیک ثبت کرد.",
"PATIENT_IDENTIFICATION_UNAVAILABLE": "این شناسه را نمی‌توان برای این کلینیک ثبت کرد.",
"WORKING_HOURS_INVALID": "ساعات کاری نامعتبر است. هم‌پوشانی شیفت‌ها را بررسی کنید.",
"WORKING_HOURS_OWNER_NOT_ALLOWED": "ساعات کاری مالک را از تنظیمات حساب تنظیم کنید.",
"WORKING_HOURS_CONFLICTS_WITH_APPOINTMENTS": "این ساعات با نوبت‌های آینده تداخل دارد. ابتدا آن نوبت‌ها را تغییر دهید یا حذف کنید.",
@@ -1275,6 +1277,8 @@
"ORG_INVITE_EXPIRED": "این دعوتنامه منقضی شده است.",
"ORG_INVITE_TYPE_MISMATCH": "نوع سازمان با این دعوتنامه مطابقت ندارد.",
"ORG_INVITE_OWNER_HAS_ORG": "این مالک از قبل سازمان دارد. به‌جای ارسال دعوتنامه آن را در جستجو پیدا کنید.",
"ORG_NAME_TAKEN_BY_OWNER": "شما از قبل سازمانی با این نام دارید. نام دیگری انتخاب کنید.",
"ORG_INVITE_NAME_TAKEN": "این مالک از قبل سازمانی با این نام دارد. نام دیگری انتخاب کنید یا در جستجو پیدا کنید.",
"ORG_UNKNOWN_TYPE": "نوع سازمان ناشناخته است.",
"ORG_COUNTERPART_NOT_LAB": "سازمان متصل‌شده لابراتوار نیست.",
"ORG_COUNTERPART_NOT_CLINIC": "سازمان متصل‌شده کلینیک نیست.",

View File

@@ -140,8 +140,6 @@
"stepOrganization": "Organisatie",
"organizationName": "Organisatienaam",
"organizationNamePlaceholder": "Sunshine Tandartspraktijk",
"organizationEmail": "Organisatie e-mail",
"organizationEmailPlaceholder": "contact@sunshineclinic.com",
"organizationType": "Organisatietype",
"dentalClinic": "Tandartspraktijk",
"dentalLab": "Tandtechnisch Laboratorium",
@@ -191,7 +189,6 @@
"passwordUppercase": "Wachtwoord moet minimaal één hoofdletter bevatten",
"passwordNumber": "Wachtwoord moet minimaal één cijfer bevatten",
"organizationNameMinLength": "Organisatienaam moet minimaal 2 tekens bevatten",
"organizationEmailInvalid": "Voer een geldig organisatie-e-mailadres in",
"organizationTypeRequired": "Selecteer een organisatietype",
"passwordsDoNotMatch": "Wachtwoorden komen niet overeen",
"mobileRequired": "Mobiel nummer is verplicht",
@@ -404,10 +401,13 @@
"errorSavePatient": "Patiënt opslaan mislukt.",
"firstName": "Voornaam",
"lastName": "Achternaam",
"identification": "Identificatie",
"identificationLabel": "Identificatie:",
"identificationRequired": "Identificatie is verplicht.",
"mobile": "Mobiel",
"mobilePlaceholder": "0612345678",
"mobileLabel": "Mobiel:",
"patientAlreadyExists": "Er bestaat al een patiënt met dit mobiele nummer: {firstName} {lastName}. Deze is voor u geselecteerd.",
"patientAlreadyExists": "Er bestaat al een patiënt met deze identificatie: {firstName} {lastName}. Deze is voor u geselecteerd.",
"savePatient": "Patiënt opslaan",
"dialogTitle": "Nieuwe patiënt",
"searchPlaceholder": "Zoek patiënten op naam, mobiel, e-mail",
@@ -725,6 +725,7 @@
"noAppointment": "Geen afspraak",
"walkIn": "Inloop",
"newTreatment": "Nieuwe behandeling",
"mobileOpenRail": "Patiënt / geschiedenis",
"newTreatmentPatientPrompt": "Voor wie is dit bezoek?",
"newTreatmentUseCurrent": "{name} gebruiken",
"newTreatmentUseCurrentHint": "Start een nieuw bezoek voor de patiënt die al op deze pagina openstaat.",
@@ -954,10 +955,11 @@
"loadingOrganization": "Organisatie laden...",
"subtitle": "Zoek organisaties, stuur verbindingsverzoeken naar bestaande accounts, of uitnodigingslinks wanneer ze nog niet op Nudentic staan.",
"invitationHistory": "Uitnodigingsgeschiedenis",
"searchPlaceholder": "Zoek {counterpart} op naam, e-mail of telefoon...",
"searchPlaceholder": "Zoek {counterpart} op naam, e-mail van eigenaar of telefoon...",
"backToList": "Terug naar lijst",
"tableOrganization": "Organisatie",
"tableOwnerEmail": "E-mail eigenaar",
"tableOwnerName": "Naam eigenaar",
"tableDate": "Datum",
"tableStatus": "Status",
"tableAction": "Actie",
@@ -1236,7 +1238,7 @@
"APPOINTMENT_NOT_FOUND": "Afspraak niet gevonden.",
"APPOINTMENT_NOT_PROVIDER": "U bent niet de zorgverlener van deze afspraak.",
"PATIENT_NOT_FOUND": "Patiënt niet gevonden.",
"PATIENT_MOBILE_UNAVAILABLE": "Dit mobiele nummer kan niet voor deze kliniek worden toegevoegd.",
"PATIENT_IDENTIFICATION_UNAVAILABLE": "Deze identificatie kan niet voor deze kliniek worden toegevoegd.",
"WORKING_HOURS_INVALID": "De werktijden zijn ongeldig. Controleer of diensten niet overlappen.",
"WORKING_HOURS_OWNER_NOT_ALLOWED": "Stel werktijden van de eigenaar in via accountinstellingen.",
"WORKING_HOURS_CONFLICTS_WITH_APPOINTMENTS": "Deze tijden conflicteren met aankomende afspraken. Plan die eerst om of verwijder ze.",
@@ -1274,6 +1276,8 @@
"ORG_INVITE_EXPIRED": "Deze uitnodiging is verlopen.",
"ORG_INVITE_TYPE_MISMATCH": "Het organisatietype komt niet overeen met deze uitnodiging.",
"ORG_INVITE_OWNER_HAS_ORG": "Deze eigenaar heeft al een organisatie. Zoek die in plaats van een uitnodiging te sturen.",
"ORG_NAME_TAKEN_BY_OWNER": "Je hebt al een organisatie met deze naam. Kies een andere naam.",
"ORG_INVITE_NAME_TAKEN": "Deze eigenaar heeft al een organisatie met deze naam. Kies een andere naam of zoek die op.",
"ORG_UNKNOWN_TYPE": "Onbekend organisatietype.",
"ORG_COUNTERPART_NOT_LAB": "De gekoppelde organisatie is geen lab.",
"ORG_COUNTERPART_NOT_CLINIC": "De gekoppelde organisatie is geen kliniek.",

View File

@@ -25,7 +25,6 @@ type AcceptOrganizationInviteForm = {
password: string;
confirmPassword: string;
organizationName: string;
organizationEmail: string;
organizationType: 'CLINIC' | 'LAB';
};
@@ -51,7 +50,6 @@ function AcceptOrganizationInviteContent() {
.regex(/[0-9]/, tValidation('passwordNumber')),
confirmPassword: z.string(),
organizationName: z.string().min(2, tValidation('organizationNameMinLength')),
organizationEmail: z.string().email(tValidation('organizationEmailInvalid')),
organizationType: z.enum(['CLINIC', 'LAB'], {
message: tValidation('organizationTypeRequired'),
}),
@@ -72,7 +70,6 @@ function AcceptOrganizationInviteContent() {
ownerEmail: string;
organizationName: string;
organizationType: 'CLINIC' | 'LAB';
organizationEmail?: string;
inviterOrganizationName: string;
expiresAt: string;
status: 'PENDING' | 'ACCEPTED';
@@ -114,7 +111,6 @@ function AcceptOrganizationInviteContent() {
password: '',
confirmPassword: '',
organizationName: res.data.organizationName || '',
organizationEmail: res.data.organizationEmail || '',
organizationType: res.data.organizationType,
});
if (res.data.status === 'ACCEPTED') {
@@ -148,7 +144,6 @@ function AcceptOrganizationInviteContent() {
ownerName: data.ownerName.trim(),
password: data.password,
organizationName: data.organizationName.trim(),
organizationEmail: data.organizationEmail.trim(),
organizationType: data.organizationType,
});
accepted = true;

View File

@@ -24,7 +24,6 @@ type RegisterForm = {
password: string;
confirmPassword: string;
organizationName: string;
organizationEmail: string;
organizationType: 'CLINIC' | 'LAB';
};
@@ -64,7 +63,6 @@ export default function RegisterPage() {
.regex(/[0-9]/, tValidation('passwordNumber')),
confirmPassword: z.string(),
organizationName: z.string().min(2, tValidation('organizationNameMinLength')),
organizationEmail: z.string().email(tValidation('organizationEmailInvalid')),
organizationType: z.enum(['CLINIC', 'LAB'], {
message: tValidation('organizationTypeRequired'),
}),
@@ -94,7 +92,7 @@ export default function RegisterPage() {
const fieldsToValidate =
step === 1
? (['name', 'email', 'mobile', 'password', 'confirmPassword'] as const)
: (['organizationName', 'organizationEmail', 'organizationType'] as const);
: (['organizationName', 'organizationType'] as const);
const isValid = await trigger([...fieldsToValidate]);
if (isValid) {
@@ -111,7 +109,6 @@ export default function RegisterPage() {
data.name,
data.mobile,
data.organizationName,
data.organizationEmail,
data.organizationType,
);
} catch (err: unknown) {

View File

@@ -54,11 +54,12 @@ interface AppointmentBookingModalProps {
function patientFromRecord(
patient: AppointmentRecord['patient'],
): Pick<Patient, 'id' | 'firstName' | 'lastName' | 'mobile'> {
): Pick<Patient, 'id' | 'firstName' | 'lastName' | 'identification' | 'mobile'> {
return {
id: patient.id,
firstName: patient.firstName,
lastName: patient.lastName,
identification: patient.identification,
mobile: patient.mobile,
};
}
@@ -93,7 +94,7 @@ export function AppointmentBookingModal({
const [endTime, setEndTime] = useState('09:30');
const [purpose, setPurpose] = useState<AppointmentPurpose>(defaultPurpose);
const [selectedPatient, setSelectedPatient] = useState<
Pick<Patient, 'id' | 'firstName' | 'lastName' | 'mobile'> | null
Pick<Patient, 'id' | 'firstName' | 'lastName' | 'identification' | 'mobile'> | null
>(null);
const [error, setError] = useState('');
@@ -147,6 +148,7 @@ export function AppointmentBookingModal({
id: initialPatient.id,
firstName: initialPatient.firstName,
lastName: initialPatient.lastName,
identification: initialPatient.identification,
mobile: initialPatient.mobile,
}
: null,
@@ -175,6 +177,7 @@ export function AppointmentBookingModal({
id: patient.id,
firstName: patient.firstName,
lastName: patient.lastName,
identification: patient.identification,
mobile: patient.mobile,
};
setSelectedPatient(next);

View File

@@ -1,13 +1,12 @@
'use client';
import { useTranslations } from 'next-intl';
import { Building2, Mail } from 'lucide-react';
import { Building2 } from 'lucide-react';
import type { FieldErrors, UseFormRegister, UseFormSetValue } from 'react-hook-form';
import { Input } from '@/components/ui/shared/Input';
export type OrganizationDetailsFormValues = {
organizationName: string;
organizationEmail: string;
organizationType: 'CLINIC' | 'LAB';
};
@@ -35,14 +34,6 @@ export function OrganizationDetailsFields({
error={errors.organizationName?.message}
icon={<Building2 className="h-5 w-5 icon-flat" />}
/>
<Input
label={t('organizationEmail')}
{...register('organizationEmail')}
type="email"
placeholder={t('organizationEmailPlaceholder')}
error={errors.organizationEmail?.message}
icon={<Mail className="h-5 w-5 icon-flat" />}
/>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
{t('organizationType')}

View File

@@ -320,7 +320,7 @@ export function CaseCreatePanel({
const disabled = !canEdit || starting || deleting;
return (
<div className="space-y-4">
<div className="space-y-4 min-w-0">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="text-lg font-semibold text-text-primary">{t('addCaseTitle')}</h2>
@@ -478,6 +478,7 @@ export function CaseCreatePanel({
detailClientId={activeLine.clientId}
catalog={prosthesisOptions}
disabled={disabled}
className="w-full min-w-0"
onToggleLink={(a, b) => {
if (disabled) return;
const currentGroups =

View File

@@ -158,8 +158,8 @@ export function CaseDetailPanel({
}
return (
<div className="space-y-4">
<header className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between border-b border-border pb-3">
<div className="space-y-4 min-w-0">
<header className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between border-b border-border pb-3">
<div className="min-w-0 flex-1 space-y-1">
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-lg font-semibold text-text-primary">
@@ -194,9 +194,9 @@ export function CaseDetailPanel({
</div>
</div>
<div className="flex w-full sm:w-auto shrink-0 flex-col items-end gap-2">
<div className="flex w-full lg:w-auto shrink-0 flex-col items-stretch lg:items-end gap-2">
{canEditImportant ? (
<div className="flex w-full max-w-sm items-center gap-3">
<div className="flex w-full max-w-sm flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
<Checkbox
checked={labCase.isImportant ?? false}
disabled={updatingImportant}
@@ -225,7 +225,7 @@ export function CaseDetailPanel({
) : labCase.externalCode?.trim() ? (
<p className="text-sm text-text-muted">{labCase.externalCode.trim()}</p>
) : null}
<div className="flex w-full sm:w-auto flex-wrap items-center justify-end gap-2">
<div className="flex w-full flex-wrap items-center justify-start lg:justify-end gap-2">
{showCommentsButton && onCommentsClick ? (
<Button type="button" variant="outline" size="sm" onClick={onCommentsClick}>
<MessageSquare className="h-4 w-4 me-1.5" />
@@ -246,7 +246,7 @@ export function CaseDetailPanel({
</Button>
</div>
{labCase.shareUrl || (previewAttachment && labCase.attachments.length > 0) ? (
<div className="flex flex-row items-center gap-2 shrink-0">
<div className="flex flex-wrap items-center gap-2 shrink-0">
{previewAttachment && labCase.attachments.length > 0 ? (
<button
type="button"
@@ -327,40 +327,42 @@ export function CaseDetailPanel({
<ul className="space-y-2">
{group.tasks.map((task) => (
<li key={task.id} className="rounded bg-background px-2 py-1.5 text-sm">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<div className="flex flex-col gap-1.5 sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-2 sm:gap-y-1">
<span className="min-w-0 flex-1 font-medium text-text-primary">
{task.stepOrder}. {task.stepLabel}
</span>
<span className="text-[11px] text-text-muted shrink-0">
{task.lastStatusChangedBy
? t('lastUpdatedBy', { name: task.lastStatusChangedBy.name })
: t('lastUpdatedUnknown')}
{task.lastStatusChangedAt
? ` · ${formatCaseDateTime(task.lastStatusChangedAt, locale)}`
: ''}
</span>
{canAssignTasks && onAssignTask ? (
<select
value={task.assignee?.id ?? ''}
disabled={assigningTaskId === task.id}
onChange={(e) =>
onAssignTask(task.id, e.target.value ? e.target.value : null)
}
aria-label={t('assigneeLabel')}
className={`${FORM_SELECT_CLASS} max-w-[9.5rem] rounded-md py-0.5 text-xs`}
>
<option value="">{t('assigneeUnassigned')}</option>
{assignableStaff.map((staff) => (
<option key={staff.id} value={staff.id}>
{staff.name}
</option>
))}
</select>
) : null}
<Badge variant={labTaskStatusVariant(task.status)} fixedWidth={false}>
{statusOptions.find((opt) => opt.value === task.status)?.label ??
task.status}
</Badge>
<div className="flex flex-wrap items-center gap-2">
<span className="text-[11px] text-text-muted shrink-0">
{task.lastStatusChangedBy
? t('lastUpdatedBy', { name: task.lastStatusChangedBy.name })
: t('lastUpdatedUnknown')}
{task.lastStatusChangedAt
? ` · ${formatCaseDateTime(task.lastStatusChangedAt, locale)}`
: ''}
</span>
{canAssignTasks && onAssignTask ? (
<select
value={task.assignee?.id ?? ''}
disabled={assigningTaskId === task.id}
onChange={(e) =>
onAssignTask(task.id, e.target.value ? e.target.value : null)
}
aria-label={t('assigneeLabel')}
className={`${FORM_SELECT_CLASS} max-w-[9.5rem] rounded-md py-0.5 text-xs`}
>
<option value="">{t('assigneeUnassigned')}</option>
{assignableStaff.map((staff) => (
<option key={staff.id} value={staff.id}>
{staff.name}
</option>
))}
</select>
) : null}
<Badge variant={labTaskStatusVariant(task.status)} fixedWidth={false}>
{statusOptions.find((opt) => opt.value === task.status)?.label ??
task.status}
</Badge>
</div>
</div>
</li>
))}

View File

@@ -80,15 +80,17 @@ export function CaseToothChartPanel({
if (selected.size === 0) return null;
return (
<FdiToothChart
selected={selected}
readOnly
scale={scale}
crownColors={regionColors.crown}
rootColors={regionColors.root}
connectedTeeth={resolvedConnected.size > 0 ? resolvedConnected : undefined}
compact={compact}
className={className}
/>
<div className={`min-w-0 w-full overflow-x-hidden ${className}`.trim()}>
<FdiToothChart
selected={selected}
readOnly
scale={scale}
crownColors={regionColors.crown}
rootColors={regionColors.root}
connectedTeeth={resolvedConnected.size > 0 ? resolvedConnected : undefined}
compact={compact}
className="w-full min-w-0"
/>
</div>
);
}

View File

@@ -387,15 +387,15 @@ export function CasesPage() {
const filterSelectClass = `${FORM_SELECT_CLASS} w-full min-w-0 rounded-md py-1.5 text-xs sm:py-2 sm:text-sm`;
return (
<div className="space-y-4">
<div className="space-y-4 min-w-0 overflow-x-hidden">
<div>
<h1 className="text-xl sm:text-2xl font-semibold text-text-primary">{t('title')}</h1>
<p className="text-sm text-text-muted mt-1">{t('subtitle')}</p>
</div>
<div className="grid gap-4 lg:grid-cols-[minmax(300px,380px)_1fr] lg:items-stretch">
<div className="grid gap-4 min-w-0 lg:grid-cols-[minmax(240px,340px)_minmax(0,1fr)] lg:items-stretch">
<section
className={`rounded-lg border border-border bg-surface p-3 sm:p-4 space-y-3 flex flex-col min-h-0 h-full lg:min-h-[420px] ${
className={`rounded-lg border border-border bg-surface p-3 sm:p-4 space-y-3 flex flex-col min-h-0 min-w-0 h-full overflow-x-hidden lg:min-h-[420px] ${
mobileDetailOpen && selectedCaseId ? 'hidden lg:flex' : 'flex'
}`}
>
@@ -420,8 +420,8 @@ export function CasesPage() {
placeholder={t('searchPlaceholder')}
/>
<div className="grid gap-2 sm:grid-cols-2">
<label className="space-y-1">
<div className="grid gap-2 sm:grid-cols-2 min-w-0">
<label className="space-y-1 min-w-0">
<span className="text-xs font-medium text-text-muted">{t('filterClinic')}</span>
<select
value={clinicId}
@@ -440,7 +440,7 @@ export function CasesPage() {
</select>
</label>
<label className="space-y-1">
<label className="space-y-1 min-w-0">
<span className="text-xs font-medium text-text-muted">{t('filterProsthesisType')}</span>
<select
value={prosthesisTypeCode}
@@ -459,7 +459,7 @@ export function CasesPage() {
</select>
</label>
<label className="space-y-1">
<label className="space-y-1 min-w-0">
<span className="text-xs font-medium text-text-muted">{t('filterSentFrom')}</span>
<AppDateInput
value={sentFrom}
@@ -471,7 +471,7 @@ export function CasesPage() {
/>
</label>
<label className="space-y-1">
<label className="space-y-1 min-w-0">
<span className="text-xs font-medium text-text-muted">{t('filterSentTo')}</span>
<AppDateInput
value={sentTo}
@@ -508,7 +508,7 @@ export function CasesPage() {
setSelectedCaseId(item.id);
setMobileDetailOpen(true);
}}
className={`w-full rounded-md border px-3 py-2.5 text-left transition-colors ${
className={`w-full rounded-md border px-3 py-2.5 text-start transition-colors ${
isActive
? 'border-primary bg-primary/5'
: 'border-border hover:border-primary/40'
@@ -570,7 +570,7 @@ export function CasesPage() {
</div>
{pagination.totalPages > 1 ? (
<div className="flex shrink-0 items-center justify-between gap-2 pt-2 border-t border-border">
<div className="flex shrink-0 flex-wrap items-center justify-between gap-2 pt-2 border-t border-border">
<Button
variant="outline"
size="sm"
@@ -579,7 +579,7 @@ export function CasesPage() {
>
{t('prevPage')}
</Button>
<span className="text-xs text-text-muted text-center">
<span className="min-w-0 flex-1 text-xs text-text-muted text-center">
{t('pageSummary', {
page: pagination.page,
totalPages: pagination.totalPages,
@@ -599,7 +599,7 @@ export function CasesPage() {
</section>
<section
className={`rounded-lg border border-border bg-surface p-3 sm:p-4 min-h-[320px] lg:min-h-[420px] ${
className={`rounded-lg border border-border bg-surface p-3 sm:p-4 min-h-[320px] min-w-0 overflow-x-hidden lg:min-h-[420px] ${
selectedCaseId && !mobileDetailOpen ? 'hidden lg:block' : ''
}`}
>

View File

@@ -35,7 +35,7 @@ export function LabCaseProsthesisGroupsList({
{groups.map((group) => (
<li
key={`${group.selectionGroupId ?? ''}-${group.prosthesisTypeCode}-${group.teeth.join(',')}`}
className="text-[11px] leading-snug"
className="text-[11px] leading-snug min-w-0 break-words"
>
<ProsthesisStackedTypeLabel
className="font-medium"

View File

@@ -184,7 +184,12 @@ export function OrganizationConnectionsMobileList({
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="font-medium text-text-primary truncate">{result.name}</p>
<p className="text-sm text-text-secondary truncate mt-0.5">{result.owner.email}</p>
<p className="text-sm text-text-secondary truncate mt-0.5">
{result.owner.name || '—'}
</p>
{result.owner.email ? (
<p className="text-xs text-text-muted truncate mt-0.5">{result.owner.email}</p>
) : null}
<p className="text-xs text-text-muted mt-1">{labels.statusToday}</p>
</div>
<Badge variant="default" fixedWidth={false}>

View File

@@ -5,7 +5,7 @@ import { useTranslations } from 'next-intl';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { useAuth } from '@/lib/hooks/useAuth';
import { canCreateOrganizationFromCurrentOrg } from '@/components/shared/permissions';
import { Building2, Beaker, Mail } from 'lucide-react';
import { Building2, Beaker } from 'lucide-react';
import { Input } from '@/components/ui/shared/Input';
import { Button } from '@/components/ui/shared/Button';
@@ -29,7 +29,6 @@ export function OrganizationSelectorContent() {
);
const [isCreateOpen, setIsCreateOpen] = useState(false);
const [organizationName, setOrganizationName] = useState('');
const [organizationEmail, setOrganizationEmail] = useState('');
const [organizationType, setOrganizationType] = useState<'CLINIC' | 'LAB'>('CLINIC');
const getIcon = (type: string) =>
@@ -41,13 +40,8 @@ export function OrganizationSelectorContent() {
const handleCreateOrganization = async () => {
try {
clearError();
const createdId = await createOrganization(
organizationName.trim(),
organizationEmail.trim(),
organizationType,
);
const createdId = await createOrganization(organizationName.trim(), organizationType);
setOrganizationName('');
setOrganizationEmail('');
setOrganizationType('CLINIC');
setIsCreateOpen(false);
await selectOrganization(createdId);
@@ -99,14 +93,6 @@ export function OrganizationSelectorContent() {
placeholder={tAuth('organizationNamePlaceholder')}
icon={<Building2 className="h-5 w-5 icon-flat" />}
/>
<Input
label={tAuth('organizationEmail')}
value={organizationEmail}
onChange={(event) => setOrganizationEmail(event.target.value)}
placeholder={tAuth('organizationEmailPlaceholder')}
type="email"
icon={<Mail className="h-5 w-5 icon-flat" />}
/>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
{tAuth('organizationType')}
@@ -142,7 +128,7 @@ export function OrganizationSelectorContent() {
variant="primary"
onClick={handleCreateOrganization}
isLoading={isLoading}
disabled={!organizationName.trim() || !organizationEmail.trim()}
disabled={!organizationName.trim()}
className="w-full sm:w-auto"
>
{t('createAndContinue')}

View File

@@ -407,7 +407,7 @@ export function OrganizationsPage() {
{t('tableOrganization')}
</th>
<th className="text-xs font-medium text-text-muted uppercase tracking-wider">
{t('tableOwnerEmail')}
{mode === 'search' ? t('tableOwnerName') : t('tableOwnerEmail')}
</th>
<th className="text-xs font-medium text-text-muted uppercase tracking-wider">
{t('tableDate')}
@@ -518,7 +518,12 @@ export function OrganizationsPage() {
searchResults.map((r) => (
<tr key={r.id} className="hover:bg-background-secondary/45">
<td className="text-sm font-medium text-text-primary">{r.name}</td>
<td className="text-sm text-text-secondary">{r.owner.email}</td>
<td className="text-sm text-text-secondary">
<span className="text-text-primary">{r.owner.name || '—'}</span>
{r.owner.email ? (
<span className="block text-xs text-text-muted truncate">{r.owner.email}</span>
) : null}
</td>
<td className="text-sm text-text-secondary">{t('statusToday')}</td>
<td className="text-center align-middle">
<Badge variant="default" fixedWidth={false}>{t('statusFound')}</Badge>

View File

@@ -23,7 +23,9 @@ interface CreatePatientModalProps {
variant?: 'inline' | 'dialog';
}
type FieldErrors = Partial<Record<'firstName' | 'lastName' | 'mobile' | 'email', string>>;
type FieldErrors = Partial<
Record<'firstName' | 'lastName' | 'identification' | 'mobile' | 'email', string>
>;
function CreatePatientFormFields({
formData,
@@ -56,6 +58,9 @@ function CreatePatientFormFields({
if (!formData.lastName?.trim()) {
nextErrors.lastName = t('lastNameRequired');
}
if (!formData.identification?.trim()) {
nextErrors.identification = t('identificationRequired');
}
if (!formData.mobile?.trim()) {
nextErrors.mobile = tValidation('mobileRequired');
} else if (!isValidMobile(normalizeMobile(formData.mobile) ?? '')) {
@@ -81,8 +86,9 @@ function CreatePatientFormFields({
() =>
!formData.firstName?.trim() ||
!formData.lastName?.trim() ||
!formData.identification?.trim() ||
!isValidMobile(normalizeMobile(formData.mobile || '') ?? ''),
[formData.firstName, formData.lastName, formData.mobile],
[formData.firstName, formData.lastName, formData.identification, formData.mobile],
);
const mobileDisplayError = useMemo(() => {
@@ -91,7 +97,11 @@ function CreatePatientFormFields({
}
const raw = formData.mobile?.trim() ?? '';
if (!raw) {
if (formData.firstName?.trim() && formData.lastName?.trim()) {
if (
formData.firstName?.trim() &&
formData.lastName?.trim() &&
formData.identification?.trim()
) {
return tValidation('mobileRequired');
}
return undefined;
@@ -105,6 +115,7 @@ function CreatePatientFormFields({
formData.mobile,
formData.firstName,
formData.lastName,
formData.identification,
tValidation,
]);
@@ -137,6 +148,18 @@ function CreatePatientFormFields({
required
error={fieldErrors.lastName}
/>
<Input
label={`${t('identification')} ${requiredMark}`}
value={formData.identification || ''}
onChange={(e) => {
onChange({ identification: e.target.value });
if (fieldErrors.identification) {
setFieldErrors((prev) => ({ ...prev, identification: undefined }));
}
}}
required
error={fieldErrors.identification}
/>
<Input
label={`${t('mobile')} ${requiredMark}`}
value={formData.mobile || ''}

View File

@@ -24,6 +24,9 @@ export function PatientSummaryCard({ patient }: PatientSummaryCardProps) {
<h2 className="text-lg font-semibold text-text-primary">
{patient.firstName} {patient.lastName}
</h2>
<p className="text-sm text-text-secondary">
{t('identificationLabel')} {patient.identification}
</p>
<p className="text-sm text-text-secondary">
{t('mobileLabel')} {formatMobileForDisplay(patient.mobile)}
</p>

View File

@@ -19,6 +19,7 @@ import { PatientAppointmentHistory } from '@/components/ui/patient/PatientAppoin
const EMPTY_PATIENT_FORM: CreatePatientInput = {
firstName: '',
lastName: '',
identification: '',
mobile: '',
email: '',
};

View File

@@ -3,14 +3,28 @@
import { ChevronLeft } from 'lucide-react';
import { useTranslations } from 'next-intl';
export function MobileDetailBackButton({ onClick }: { onClick: () => void }) {
/** Hide from this breakpoint up (Cases = lg, Treatment = xl). */
type HideFrom = 'lg' | 'xl';
const HIDE_FROM_CLASS: Record<HideFrom, string> = {
lg: 'lg:hidden',
xl: 'xl:hidden',
};
export function MobileDetailBackButton({
onClick,
hideFrom = 'lg',
}: {
onClick: () => void;
hideFrom?: HideFrom;
}) {
const t = useTranslations('common');
return (
<button
type="button"
onClick={onClick}
className="lg:hidden inline-flex items-center gap-1 text-sm text-primary hover:opacity-90 mb-3"
className={`${HIDE_FROM_CLASS[hideFrom]} inline-flex items-center gap-1 text-sm text-primary hover:opacity-90 mb-3`}
>
<ChevronLeft className="h-4 w-4 icon-flat" />
{t('back')}

View File

@@ -1,6 +1,14 @@
'use client';
import { useEffect, useId, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import {
useEffect,
useId,
useRef,
useState,
type CSSProperties,
type PointerEvent as ReactPointerEvent,
type ReactNode,
} from 'react';
import { useTranslations } from 'next-intl';
import { Info, Plus } from 'lucide-react';
import { Button } from '@/components/ui/shared/Button';
@@ -24,6 +32,8 @@ const TOOTH_NUMBER_GAP = 'mt-1';
const REALISTIC_NUMBER_GAP = '2mm';
/** Tight interproximal gap between tooth columns. */
const TOOTH_GAP = 'gap-x-px';
/** Max finger movement (px) still counted as a tap; beyond this, treat as scroll. */
const TOUCH_TAP_SLOP_PX = 10;
/**
* Centers a mark on the inline-end edge of a tooth column (between this tooth
* and the next in flex order). Logical `end` + 0-width flex stays correct in LTR and RTL.
@@ -31,6 +41,13 @@ const TOOTH_GAP = 'gap-x-px';
const EDGE_MARK_ANCHOR =
'absolute inset-y-0 end-0 z-10 w-0 flex items-center justify-center';
type TouchPendingTap = {
pointerId: number;
startX: number;
startY: number;
activate: () => void;
};
function quadrantMirrored(fdi: FdiToothId): boolean {
const q = fdi[0];
return q === '2' || q === '3';
@@ -67,6 +84,7 @@ function ToothNumber({
interactive,
disabled,
onActivate,
onBeginPointer,
}: {
fdi: FdiToothId;
selected: boolean;
@@ -76,6 +94,7 @@ function ToothNumber({
interactive: boolean;
disabled: boolean;
onActivate: (keys: { shiftKey: boolean; ctrlKey: boolean }) => void;
onBeginPointer: (e: ReactPointerEvent<HTMLButtonElement>) => void;
}) {
const className = `text-[10px] tabular-nums text-center leading-none ${colorClass}`;
const boxStyle: CSSProperties = { width: `${widthRem}rem`, ...style };
@@ -98,8 +117,7 @@ function ToothNumber({
}}
onPointerDown={(e) => {
if (e.button !== 0) return;
e.preventDefault();
onActivate({ shiftKey: e.shiftKey, ctrlKey: e.ctrlKey || e.metaKey });
onBeginPointer(e);
}}
onKeyDown={(e) => {
if (e.key !== 'Enter' && e.key !== ' ') return;
@@ -308,23 +326,69 @@ export function FdiToothChart({
const uid = useId().replace(/:/g, '');
const [hintOpen, setHintOpen] = useState(false);
const paintingRef = useRef(false);
const touchPendingRef = useRef<TouchPendingTap | null>(null);
const archPeak = 8;
const interactive = !readOnly && (Boolean(onToggle) || Boolean(onAssignPointer));
const linkInteractive = interactive && Boolean(onToggleLink);
const isDisabled = disabled || readOnly;
useEffect(() => {
const endPaint = () => {
paintingRef.current = false;
const slopSq = TOUCH_TAP_SLOP_PX * TOUCH_TAP_SLOP_PX;
const onMove = (e: PointerEvent) => {
const pending = touchPendingRef.current;
if (!pending || e.pointerId !== pending.pointerId) return;
const dx = e.clientX - pending.startX;
const dy = e.clientY - pending.startY;
if (dx * dx + dy * dy > slopSq) {
touchPendingRef.current = null;
}
};
window.addEventListener('pointerup', endPaint);
window.addEventListener('pointercancel', endPaint);
const onUp = (e: PointerEvent) => {
paintingRef.current = false;
const pending = touchPendingRef.current;
if (!pending || e.pointerId !== pending.pointerId) return;
touchPendingRef.current = null;
pending.activate();
};
const onCancel = (e: PointerEvent) => {
paintingRef.current = false;
const pending = touchPendingRef.current;
if (pending && e.pointerId === pending.pointerId) {
touchPendingRef.current = null;
}
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onCancel);
return () => {
window.removeEventListener('pointerup', endPaint);
window.removeEventListener('pointercancel', endPaint);
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onCancel);
};
}, []);
/** Mouse/pen: activate immediately. Touch: defer until pointerup if movement stays within slop. */
const beginToothPointer = (
e: ReactPointerEvent<HTMLButtonElement>,
opts: { startPaint: boolean; activate: () => void },
) => {
if (e.pointerType === 'touch') {
touchPendingRef.current = {
pointerId: e.pointerId,
startX: e.clientX,
startY: e.clientY,
activate: opts.activate,
};
return;
}
e.preventDefault();
e.stopPropagation();
if (opts.startPaint && !e.shiftKey) {
paintingRef.current = true;
}
opts.activate();
};
const toothSizeClass = (fdi: FdiToothId) => toothSize(fdi);
const archOffset = (index: number, count: number, upper?: boolean) => {
@@ -531,14 +595,11 @@ export function FdiToothChart({
}}
onPointerDown={(e) => {
if (e.button !== 0) return;
e.preventDefault();
e.stopPropagation();
if (onAssignPointer && !e.shiftKey) {
paintingRef.current = true;
}
activateTooth({
shiftKey: e.shiftKey,
ctrlKey: e.ctrlKey || e.metaKey,
const shiftKey = e.shiftKey;
const ctrlKey = e.ctrlKey || e.metaKey;
beginToothPointer(e, {
startPaint: Boolean(onAssignPointer),
activate: () => activateTooth({ shiftKey, ctrlKey }),
});
}}
onPointerEnter={() => {
@@ -665,6 +726,24 @@ export function FdiToothChart({
}
onToggle?.(fdi, { shiftKey: keys.shiftKey });
}}
onBeginPointer={(e) => {
const shiftKey = e.shiftKey;
const ctrlKey = e.ctrlKey || e.metaKey;
beginToothPointer(e, {
startPaint: false,
activate: () => {
if (onAssignPointer) {
onAssignPointer(fdi, {
shiftKey,
ctrlKey,
paint: ctrlKey,
});
return;
}
onToggle?.(fdi, { shiftKey });
},
});
}}
/>
))}
</div>
@@ -683,19 +762,37 @@ export function FdiToothChart({
style={numberStyle(fdi, selected.has(fdi))}
interactive={interactive}
disabled={isDisabled}
onActivate={(keys) => {
if (onAssignPointer) {
onAssignPointer(fdi, {
shiftKey: keys.shiftKey,
ctrlKey: keys.ctrlKey,
paint: keys.ctrlKey,
onActivate={(keys) => {
if (onAssignPointer) {
onAssignPointer(fdi, {
shiftKey: keys.shiftKey,
ctrlKey: keys.ctrlKey,
paint: keys.ctrlKey,
});
return;
}
onToggle?.(fdi, { shiftKey: keys.shiftKey });
}}
onBeginPointer={(e) => {
const shiftKey = e.shiftKey;
const ctrlKey = e.ctrlKey || e.metaKey;
beginToothPointer(e, {
startPaint: false,
activate: () => {
if (onAssignPointer) {
onAssignPointer(fdi, {
shiftKey,
ctrlKey,
paint: ctrlKey,
});
return;
}
onToggle?.(fdi, { shiftKey });
},
});
return;
}
onToggle?.(fdi, { shiftKey: keys.shiftKey });
}}
/>
))}
}}
/>
))}
</div>
<div className={TOOTH_NUMBER_GAP}>
<div
@@ -733,8 +830,8 @@ export function FdiToothChart({
);
return (
<div className={`${cardClass} ${className}`}>
<div className="flex items-start justify-between gap-2">
<div className={`${cardClass} min-w-0 ${className}`.trim()}>
<div className="flex min-w-0 items-start justify-between gap-2">
<div className="flex min-w-0 items-center gap-1">
<h3 className="text-sm font-semibold text-text-primary">
{compact || embedded ? t('toothChartTitleCompact') : t('toothChartTitle')}
@@ -769,7 +866,7 @@ export function FdiToothChart({
) : null}
</div>
) : null}
<p className="min-w-0 text-[11px] text-text-secondary tabular-nums text-end">
<p className="min-w-0 max-w-full text-[11px] text-text-secondary tabular-nums text-end break-words">
{t('selectedLabel')}{' '}
{selectedSummary ??
(selected.size === 0 ? t('selectedEmpty') : [...selected].sort().join(', '))}

View File

@@ -508,12 +508,12 @@ export function ProsthesisJobPopover({
);
const body = (
<div className="grid h-full min-h-0 flex-1 grid-cols-[4fr_1fr]">
<section className="flex min-h-0 min-w-0 flex-col gap-2.5 border-e border-border pe-3">
<div className="grid h-full min-h-0 flex-1 grid-cols-1 sm:grid-cols-[4fr_1fr]">
<section className="flex min-h-0 min-w-0 flex-col gap-2.5 border-b border-border pb-3 sm:border-b-0 sm:border-e sm:pb-0 sm:pe-3">
<p className="shrink-0 text-xs font-semibold leading-none text-text-primary">{title}</p>
{scope === 'arch' && onLockedArchChange ? (
<div
className="flex h-8 w-1/2 shrink-0 rounded-[var(--radius-md)] border border-border p-0.5"
className="flex h-8 w-full sm:w-1/2 shrink-0 rounded-[var(--radius-md)] border border-border p-0.5"
role="group"
aria-label={title}
>
@@ -541,13 +541,13 @@ export function ProsthesisJobPopover({
{tileRow}
</div>
</section>
<section className="flex min-h-0 min-w-0 flex-col gap-1 ps-3">
<div className="flex shrink-0 flex-col gap-1">
<section className="flex min-h-0 min-w-0 flex-col gap-1 pt-3 sm:pt-0 sm:ps-3">
<div className="flex shrink-0 flex-row gap-1 sm:flex-col">
<Button
type="button"
variant="outline"
size="sm"
className={HEADER_BTN_CLASS}
className={`${HEADER_BTN_CLASS} flex-1 sm:flex-none`}
disabled={!hasLeaf}
onClick={onClear}
>
@@ -557,7 +557,7 @@ export function ProsthesisJobPopover({
type="button"
variant="primary"
size="sm"
className={HEADER_BTN_CLASS}
className={`${HEADER_BTN_CLASS} flex-1 sm:flex-none`}
onClick={onClose}
>
{t('done')}

View File

@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from '@/i18n/navigation';
import { Button } from '@/components/ui/shared/Button';
import { MobileDetailBackButton } from '@/components/ui/shared/MobileDetailBackButton';
import { PatientSearchCombobox } from '@/components/ui/patient/PatientSearchCombobox';
import {
TreatmentLabCasesPanel,
@@ -480,6 +481,8 @@ export function TreatmentWorkspace({
const [patientSearchBusy, setPatientSearchBusy] = useState(false);
const [newTreatmentPickerOpen, setNewTreatmentPickerOpen] = useState(false);
const [creatingStandalone, setCreatingStandalone] = useState(false);
/** Below xl: show left rail instead of editor (Cases-style pane swap). */
const [mobileRailOpen, setMobileRailOpen] = useState(false);
const {
search: patientSearch,
@@ -684,6 +687,12 @@ export function TreatmentWorkspace({
!historyLoading &&
history.length === 0;
useEffect(() => {
if (showNoTreatmentFound) {
setMobileRailOpen(true);
}
}, [showNoTreatmentFound]);
const unreadUpdatesCount = unreadLabCases.length;
const otherPatientsUnreadCount = useMemo(
() => unreadLabCases.filter((item) => item.patientId !== activePatientId).length,
@@ -1690,6 +1699,7 @@ export function TreatmentWorkspace({
draftHydratingRef.current = true;
hydrateFromTreatment(created.data, { seedBlankIfEmpty: true });
draftHydratingRef.current = false;
setMobileRailOpen(false);
if (created.data.patientId && !created.data.patient?.isWalkIn) {
await refreshHistory(created.data.patientId);
}
@@ -1795,6 +1805,8 @@ export function TreatmentWorkspace({
const ok = workspaceModeRef.current === 'live' ? await flushDraftSave() : true;
if (!ok) return false;
setMobileRailOpen(false);
let treatmentToLoad = treatment;
try {
const draftResponse = treatment.appointmentId
@@ -1947,6 +1959,7 @@ export function TreatmentWorkspace({
(item: LabDispatchAttentionItem) => {
if (item.isCurrentDraft) {
exitBrowse();
setMobileRailOpen(false);
setLabWorkspaceView('dispatch');
if (item.detailClientId !== activeDetailId) {
pendingScrollToLabRef.current = true;
@@ -1968,6 +1981,7 @@ export function TreatmentWorkspace({
history.find((entry) => entry.id === item.treatmentId) ??
historyPanelItems.find((entry) => entry.id === item.treatmentId);
if (!treatment) return;
setMobileRailOpen(false);
void loadTreatmentIntoWorkspace(treatment, item.detailClientId);
},
[exitBrowse, activeDetailId, history, historyPanelItems, labCaseDrafts, loadTreatmentIntoWorkspace],
@@ -2018,6 +2032,7 @@ export function TreatmentWorkspace({
workspaceMode === 'live' &&
!isBrowsing
) {
setMobileRailOpen(false);
setLabWorkspaceView('dispatch');
if (item.detailClientId !== activeDetailId) {
pendingScrollToLabRef.current = true;
@@ -2623,7 +2638,12 @@ export function TreatmentWorkspace({
)}
<div className="treatment-layout-grid grid grid-cols-1 xl:grid-cols-[minmax(300px,380px)_minmax(0,1fr)] gap-4 items-start">
<div className="space-y-3 min-w-0 xl:max-w-[380px]">
<div
className={`space-y-3 min-w-0 xl:max-w-[380px] ${
mobileRailOpen ? 'block' : 'hidden'
} xl:block`}
>
<MobileDetailBackButton hideFrom="xl" onClick={() => setMobileRailOpen(false)} />
<div className="surface-card p-3 space-y-3">
{canEdit && !isViewingPastDay ? (
<div className="space-y-2">
@@ -2781,7 +2801,21 @@ export function TreatmentWorkspace({
) : null}
</div>
<div className="space-y-3 min-w-0 w-full">
<div
className={`space-y-3 min-w-0 w-full ${
mobileRailOpen ? 'hidden' : 'block'
} xl:block`}
>
<div className="xl:hidden">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setMobileRailOpen(true)}
>
{t('mobileOpenRail')}
</Button>
</div>
{showSearchedPatientLoading ? (
<div className="surface-card p-6">
<p className="text-sm text-text-muted">{t('loading')}</p>

View File

@@ -40,7 +40,6 @@ export const authApi = {
// Create organization for current user
createOrganization: async (data: {
organizationName: string;
organizationEmail: string;
organizationType: 'CLINIC' | 'LAB';
planName?: string;
}): Promise<any> => {

View File

@@ -9,7 +9,6 @@ import type {
export interface CounterpartSearchResultDto {
id: string;
name: string;
email: string;
phone: string | null;
owner: { email: string; name: string };
}
@@ -113,7 +112,6 @@ export const organizationApi = {
ownerEmail: string;
organizationName: string;
organizationType: 'CLINIC' | 'LAB';
organizationEmail?: string;
inviterOrganizationName: string;
expiresAt: string;
status: 'PENDING' | 'ACCEPTED';
@@ -128,7 +126,6 @@ export const organizationApi = {
acceptInvite: async (body: {
token: string;
organizationName: string;
organizationEmail: string;
organizationType: 'CLINIC' | 'LAB';
ownerName: string;
password: string;

View File

@@ -47,7 +47,6 @@ interface AuthContextType {
name: string,
mobile: string,
organizationName: string,
organizationEmail: string,
organizationType: 'CLINIC' | 'LAB'
) => Promise<void>;
login: (
@@ -59,7 +58,6 @@ interface AuthContextType {
selectOrganization: (orgId: string) => Promise<void>;
createOrganization: (
organizationName: string,
organizationEmail: string,
organizationType: 'CLINIC' | 'LAB',
planName?: string,
) => Promise<string>;
@@ -266,7 +264,6 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
name: string,
mobile: string,
organizationName: string,
organizationEmail: string,
organizationType: 'CLINIC' | 'LAB'
) => {
try {
@@ -279,7 +276,6 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
password,
name,
organizationName,
organizationEmail,
organizationType,
});
@@ -405,7 +401,6 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const createOrganization = useCallback(async (
organizationName: string,
organizationEmail: string,
organizationType: 'CLINIC' | 'LAB',
planName?: string,
) => {
@@ -415,7 +410,6 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const createResponse = await authApi.createOrganization({
organizationName,
organizationEmail,
organizationType,
planName,
});

View File

@@ -22,7 +22,7 @@ export interface AppointmentRecord {
startAt: string;
endAt: string;
purpose: string;
patient: Pick<Patient, 'id' | 'firstName' | 'lastName' | 'mobile'>;
patient: Pick<Patient, 'id' | 'firstName' | 'lastName' | 'identification' | 'mobile'>;
/** True when a treatment record is linked to this appointment. */
hasTreatment?: boolean;
}

View File

@@ -17,7 +17,6 @@ export interface TrialRegistrationData {
password: string;
name: string;
organizationName: string;
organizationEmail: string;
organizationType: 'CLINIC' | 'LAB';
}

View File

@@ -2,6 +2,7 @@ export interface Patient {
id: string;
firstName: string;
lastName: string;
identification: string;
mobile: string;
email?: string | null;
dateOfBirth?: string | null;
@@ -15,6 +16,7 @@ export interface Patient {
export interface CreatePatientInput {
firstName: string;
lastName: string;
identification: string;
mobile: string;
email?: string;
dateOfBirth?: string;