diff --git a/add_tenant_with_prefix.py b/add_tenant_with_prefix.py index 7a0bcc8..71c39ef 100644 --- a/add_tenant_with_prefix.py +++ b/add_tenant_with_prefix.py @@ -1,6 +1,6 @@ import re -from tenancy.models import Tenant, TenantGroup, Contact, ContactRole +from tenancy.models import Tenant, TenantGroup, Contact, ContactRole, ContactAssignment from ipam.models import Prefix, VRF, Role from extras.scripts import Script, StringVar, IPNetworkVar, ChoiceVar, ObjectVar from django.core.exceptions import ValidationError @@ -193,16 +193,10 @@ class CreateTenant(Script): f"Создан префикс {prefix.prefix} для оператора: {tenant.name}" ) if data.get("contacts_fio"): - try: - role = data.get("contacts_role", ContactRole.objects.first()) - except Exception as e: - self.log_failure(f"Ошибка при получении роли контакта: {e}") contact = Contact( name=data["contacts_fio"], phone=data["contacts_phone"], email=data["contacts_email"], - role=role, - tenant=tenant, ) try: contact.full_clean() @@ -210,6 +204,22 @@ class CreateTenant(Script): self.log_success(f"Создан контакт: {contact.name}") except Exception as e: self.log_failure(f"Ошибка при создании контакта: {e}") + try: + role = data.get("contacts_role", ContactRole.objects.first()) + assignment = ContactAssignment( + contact=contact, + role=role, + tenant=tenant, + ) + assignment.full_clean() + assignment.save() + self.log_success( + f"Связан контакт {contact.name} с оператором: {tenant.name}" + ) + except Exception as e: + self.log_failure( + f"Ошибка при связывании контакта с оператором: {e}" + ) else: self.log_info( @@ -230,10 +240,14 @@ class CreateTenant(Script): name=data["contacts_fio"], phone=data["contacts_phone"], email=data["contacts_email"], + ) + contact.full_clean() + assignment = ContactAssignment( + contact=contact, role=data.get("contacts_role", ContactRole.objects.first()), tenant=tenant, ) - contact.full_clean() + assignment.full_clean() self.log_success("Все данные валидны") except ValidationError as e: self.log_failure(f"Ошибка валидации: {e}")