From da544f18b73a3eba44fdb6c6138582f7f6067a99 Mon Sep 17 00:00:00 2001 From: rameen Date: Thu, 17 Sep 2026 20:46:32 +0330 Subject: [PATCH] Remove organization email; unique orgs by owner and name --- backend/nest-cli.json | 1 + .../migration.sql | 17 ++ .../migration.sql | 14 ++ backend/prisma/schema.prisma | 5 +- backend/src/common/errors/error-codes.ts | 3 + .../common/utils/organization-name.util.ts | 66 +++++++ backend/src/modules/auth/auth.service.ts | 75 +++---- .../auth/dto/create-organization.dto.ts | 9 +- backend/src/modules/auth/dto/register.dto.ts | 15 +- .../dto/accept-organization-invite.dto.ts | 15 +- .../organization/organization.service.ts | 184 ++++++++++-------- frontend/messages/en.json | 8 +- frontend/messages/fa.json | 8 +- frontend/messages/nl.json | 8 +- .../accept-organization-invite/page.tsx | 5 - .../app/[locale]/(public)/register/page.tsx | 5 +- .../ui/auth/OrganizationDetailsFields.tsx | 11 +- .../OrganizationConnectionsMobileList.tsx | 7 +- .../OrganizationSelectorContent.tsx | 20 +- .../ui/organizations/OrganizationsPage.tsx | 9 +- frontend/src/lib/api/auth.ts | 1 - frontend/src/lib/api/organization.ts | 3 - frontend/src/lib/hooks/useAuth.tsx | 6 - frontend/src/types/auth.ts | 1 - 24 files changed, 298 insertions(+), 198 deletions(-) create mode 100644 backend/prisma/migrations/20260917120000_drop_organization_email_unique_owner_name/migration.sql create mode 100644 backend/prisma/migrations/20260917183000_org_name_unique_case_insensitive/migration.sql create mode 100644 backend/src/common/utils/organization-name.util.ts diff --git a/backend/nest-cli.json b/backend/nest-cli.json index f9aa683..ceb68c2 100644 --- a/backend/nest-cli.json +++ b/backend/nest-cli.json @@ -2,6 +2,7 @@ "$schema": "https://json.schemastore.org/nest-cli", "collection": "@nestjs/schematics", "sourceRoot": "src", + "entryFile": "src/main", "compilerOptions": { "deleteOutDir": true } diff --git a/backend/prisma/migrations/20260917120000_drop_organization_email_unique_owner_name/migration.sql b/backend/prisma/migrations/20260917120000_drop_organization_email_unique_owner_name/migration.sql new file mode 100644 index 0000000..32adf72 --- /dev/null +++ b/backend/prisma/migrations/20260917120000_drop_organization_email_unique_owner_name/migration.sql @@ -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"); diff --git a/backend/prisma/migrations/20260917183000_org_name_unique_case_insensitive/migration.sql b/backend/prisma/migrations/20260917183000_org_name_unique_case_insensitive/migration.sql new file mode 100644 index 0000000..9723934 --- /dev/null +++ b/backend/prisma/migrations/20260917183000_org_name_unique_case_insensitive/migration.sql @@ -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"))); diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 28a43a4..967317c 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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") } @@ -729,7 +730,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 { diff --git a/backend/src/common/errors/error-codes.ts b/backend/src/common/errors/error-codes.ts index 42f4fe5..27aca4e 100644 --- a/backend/src/common/errors/error-codes.ts +++ b/backend/src/common/errors/error-codes.ts @@ -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', diff --git a/backend/src/common/utils/organization-name.util.ts b/backend/src/common/utils/organization-name.util.ts new file mode 100644 index 0000000..1ae4760 --- /dev/null +++ b/backend/src/common/utils/organization-name.util.ts @@ -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 { + 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; +} diff --git a/backend/src/modules/auth/auth.service.ts b/backend/src/modules/auth/auth.service.ts index 9a29aa4..bdc836e 100644 --- a/backend/src/modules/auth/auth.service.ts +++ b/backend/src/modules/auth/auth.service.ts @@ -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) { diff --git a/backend/src/modules/auth/dto/create-organization.dto.ts b/backend/src/modules/auth/dto/create-organization.dto.ts index 642bace..742eceb 100644 --- a/backend/src/modules/auth/dto/create-organization.dto.ts +++ b/backend/src/modules/auth/dto/create-organization.dto.ts @@ -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() diff --git a/backend/src/modules/auth/dto/register.dto.ts b/backend/src/modules/auth/dto/register.dto.ts index 0eb3f8f..808f117 100644 --- a/backend/src/modules/auth/dto/register.dto.ts +++ b/backend/src/modules/auth/dto/register.dto.ts @@ -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); diff --git a/backend/src/modules/organization/dto/accept-organization-invite.dto.ts b/backend/src/modules/organization/dto/accept-organization-invite.dto.ts index 4f9c562..398e768 100644 --- a/backend/src/modules/organization/dto/accept-organization-invite.dto.ts +++ b/backend/src/modules/organization/dto/accept-organization-invite.dto.ts @@ -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; } diff --git a/backend/src/modules/organization/organization.service.ts b/backend/src/modules/organization/organization.service.ts index 1d6de8a..da6dedf 100644 --- a/backend/src/modules/organization/organization.service.ts +++ b/backend/src/modules/organization/organization.service.ts @@ -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( diff --git a/frontend/messages/en.json b/frontend/messages/en.json index 1efacfc..34fca98 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -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", @@ -954,10 +951,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", @@ -1274,6 +1272,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.", diff --git a/frontend/messages/fa.json b/frontend/messages/fa.json index 1ac94af..73963b5 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -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": "شماره موبایل الزامی است", @@ -955,10 +952,11 @@ "loadingOrganization": "در حال بارگذاری سازمان...", "subtitle": "سازمان‌ها را جستجو کنید، درخواست اتصال به حساب‌های موجود ارسال کنید، یا اگر هنوز در Nudentic نیستند، لینک دعوت ارسال کنید.", "invitationHistory": "تاریخچه دعوت‌نامه‌ها", - "searchPlaceholder": "جستجوی {counterpart} بر اساس نام، ایمیل یا تلفن...", + "searchPlaceholder": "جستجوی {counterpart} بر اساس نام، ایمیل مالک یا تلفن...", "backToList": "بازگشت به لیست", "tableOrganization": "سازمان", "tableOwnerEmail": "ایمیل مالک", + "tableOwnerName": "نام مالک", "tableDate": "تاریخ", "tableStatus": "وضعیت", "tableAction": "عملیات", @@ -1275,6 +1273,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": "سازمان متصل‌شده کلینیک نیست.", diff --git a/frontend/messages/nl.json b/frontend/messages/nl.json index 80c7fc1..3eef1d3 100644 --- a/frontend/messages/nl.json +++ b/frontend/messages/nl.json @@ -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", @@ -954,10 +951,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", @@ -1274,6 +1272,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.", diff --git a/frontend/src/app/[locale]/(public)/accept-organization-invite/page.tsx b/frontend/src/app/[locale]/(public)/accept-organization-invite/page.tsx index e07fe4f..b650633 100644 --- a/frontend/src/app/[locale]/(public)/accept-organization-invite/page.tsx +++ b/frontend/src/app/[locale]/(public)/accept-organization-invite/page.tsx @@ -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; diff --git a/frontend/src/app/[locale]/(public)/register/page.tsx b/frontend/src/app/[locale]/(public)/register/page.tsx index fc49a8d..48f9f32 100644 --- a/frontend/src/app/[locale]/(public)/register/page.tsx +++ b/frontend/src/app/[locale]/(public)/register/page.tsx @@ -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) { diff --git a/frontend/src/components/ui/auth/OrganizationDetailsFields.tsx b/frontend/src/components/ui/auth/OrganizationDetailsFields.tsx index 7634f06..6bde86c 100644 --- a/frontend/src/components/ui/auth/OrganizationDetailsFields.tsx +++ b/frontend/src/components/ui/auth/OrganizationDetailsFields.tsx @@ -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={} /> - } - />