refactor: consolidate admin/users management under /people
This commit is contained in:
@@ -5,7 +5,10 @@ import type {
|
||||
CreatePersonFormType,
|
||||
UpdatePersonFormType,
|
||||
} from "@/schemas/person.schema"
|
||||
import type { UnifiedCreateFormType } from "@/schemas/user.schema"
|
||||
import type {
|
||||
UnifiedCreateFormType,
|
||||
UnifiedUpdateFormType,
|
||||
} from "@/schemas/user.schema"
|
||||
import { PersonService } from "@/services/person.service"
|
||||
import { getUserByEmail } from "@/services/user.service"
|
||||
|
||||
@@ -217,3 +220,83 @@ export async function createPersonUserUseCase(
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function updatePersonUserUseCase(
|
||||
input: UnifiedUpdateFormType,
|
||||
): Promise<PersonUseCaseResult> {
|
||||
const {
|
||||
id,
|
||||
firstName,
|
||||
lastName,
|
||||
department,
|
||||
email,
|
||||
phone,
|
||||
role,
|
||||
isActive,
|
||||
password,
|
||||
} = input
|
||||
|
||||
try {
|
||||
return await prisma.$transaction(async (tx) => {
|
||||
const existing = await tx.person.findUnique({
|
||||
where: { id },
|
||||
include: { user: true },
|
||||
})
|
||||
|
||||
if (!existing) {
|
||||
return personError({ id: ["Person not found"] })
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
tx,
|
||||
)
|
||||
|
||||
// If the person has a linked user, update User fields.
|
||||
if (existing.userId && existing.user) {
|
||||
const userData: Prisma.UserUpdateInput = {}
|
||||
|
||||
if (role !== undefined) {
|
||||
userData.role = role
|
||||
}
|
||||
if (isActive !== undefined) {
|
||||
userData.isActive = isActive
|
||||
}
|
||||
if (password && password.length >= 8) {
|
||||
userData.password = await getPasswordHash(password)
|
||||
}
|
||||
|
||||
if (Object.keys(userData).length > 0) {
|
||||
await tx.user.update({
|
||||
where: { id: existing.userId },
|
||||
data: userData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
})
|
||||
} catch (error) {
|
||||
const errors = uniqueErrorFor(error)
|
||||
|
||||
if (errors) {
|
||||
return personError(errors)
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user