refactor: rename Recipient to Person, remove username, add userId FK

This commit is contained in:
2026-06-16 10:04:24 +02:00
parent befe1f3f82
commit d67f31cf54
27 changed files with 751 additions and 628 deletions
+127
View File
@@ -0,0 +1,127 @@
import { Prisma } from "@/generated/prisma/client"
import prisma from "@/lib/prisma"
import type {
CreatePersonFormType,
UpdatePersonFormType,
} from "@/schemas/person.schema"
import { PersonService } from "@/services/person.service"
type FieldErrors = Record<string, string[]>
type PersonUseCaseResult =
| {
success: true
}
| {
success: false
errors: FieldErrors
}
function personError(errors: FieldErrors): PersonUseCaseResult {
return {
success: false,
errors,
}
}
function uniqueErrorFor(error: unknown): FieldErrors | null {
if (
!(error instanceof Prisma.PrismaClientKnownRequestError) ||
error.code !== "P2002"
) {
return null
}
const target = Array.isArray(error.meta?.target) ? error.meta.target : []
if (target.includes("email")) {
return { email: ["Email already exists"] }
}
return { email: ["Email already exists"] }
}
export async function createPersonUseCase(
input: CreatePersonFormType,
): Promise<PersonUseCaseResult> {
const { firstName, lastName, department, email, phone, userId } = input
try {
return await prisma.$transaction(async (tx) => {
if (email) {
const existingPersonEmail = await PersonService.findByEmail(email, tx)
if (existingPersonEmail) {
return personError({ email: ["Email already exists"] })
}
}
await PersonService.create(
{
firstName,
lastName,
department,
email: email || null,
phone: phone || null,
...(userId ? { user: { connect: { id: userId } } } : {}),
},
tx,
)
return {
success: true,
}
})
} catch (error) {
const errors = uniqueErrorFor(error)
if (errors) {
return personError(errors)
}
throw error
}
}
export async function updatePersonUseCase(
input: UpdatePersonFormType,
): Promise<PersonUseCaseResult> {
const { id, firstName, lastName, department, email, phone, userId } = input
try {
return await prisma.$transaction(async (tx) => {
if (email) {
const existingPersonEmail = await PersonService.findByEmail(email, tx)
if (existingPersonEmail && existingPersonEmail.id !== id) {
return personError({ email: ["Email already exists"] })
}
}
await PersonService.update(
id,
{
firstName,
lastName,
department,
email: email || null,
phone: phone || null,
...(userId ? { user: { connect: { id: userId } } } : { userId: null }),
},
tx,
)
return {
success: true,
}
})
} catch (error) {
const errors = uniqueErrorFor(error)
if (errors) {
return personError(errors)
}
throw error
}
}