Fix LDAP user creation: handle existing Employee with same email

- Check if Employee with same email exists before creating new one
- Update existing Employee and link it to LDAP instead of creating duplicate
- Prevents UNIQUE constraint failed error on email field
- Sets is_ldap_managed=True and updates user data from LDAP
This commit is contained in:
lizerk 2026-03-20 00:16:29 +03:00
parent 175796ff78
commit ca1deac82b

View File

@ -116,14 +116,28 @@ class UserService(BaseService):
# 2) DB + sync-state
try:
with transaction.atomic():
emp = Employee.objects.create(
first_name=dto.first_name,
last_name=dto.last_name,
email=dto.email,
phone_number=dto.phone_e164,
is_active=dto.is_active,
is_ldap_managed=True,
)
# Проверяем, существует ли уже пользователь с таким email
emp = Employee.objects.filter(email=dto.email).first()
if emp:
# Обновляем существующего пользователя
emp.first_name = dto.first_name
emp.last_name = dto.last_name
emp.phone_number = dto.phone_e164
emp.is_active = dto.is_active
emp.is_ldap_managed = True
emp._skip_ldap_sync = True
emp.save()
else:
# Создаем нового пользователя
emp = Employee.objects.create(
first_name=dto.first_name,
last_name=dto.last_name,
email=dto.email,
phone_number=dto.phone_e164,
is_active=dto.is_active,
is_ldap_managed=True,
)
if hasattr(emp, "set_unusable_password"):
emp.set_unusable_password()
emp._skip_ldap_sync = True