diff --git a/app/contact_utils.py b/app/contact_utils.py index 4d508a13..e2bb62e3 100644 --- a/app/contact_utils.py +++ b/app/contact_utils.py @@ -16,6 +16,7 @@ from app.utils import sanitize_email class ContactCreateError(Enum): InvalidEmail = "Invalid email" NotAllowed = "Your plan does not allow to create contacts" + Unknown = "Unknown error when trying to create contact" @dataclass @@ -87,6 +88,7 @@ def create_contact( return __update_contact_if_needed(contact, name, mail_from) # Create the contact reply_email = generate_reply_email(email, alias) + alias_id = alias.id try: flags = Contact.FLAG_PARTNER_CREATED if from_partner else 0 contact = Contact.create( @@ -114,11 +116,21 @@ def create_contact( LOG.d( f"Created contact {contact} for alias {alias} with email {email} invalid_email={contact.invalid_email}" ) + return ContactCreateResult(contact, created=True, error=None) except IntegrityError: Session.rollback() LOG.info( - f"Contact with email {email} for alias_id {alias.id} already existed, fetching from DB" + f"Contact with email {email} for alias_id {alias_id} already existed, fetching from DB" ) - contact = Contact.get_by(alias_id=alias.id, website_email=email) - return __update_contact_if_needed(contact, name, mail_from) - return ContactCreateResult(contact, created=True, error=None) + contact: Optional[Contact] = Contact.get_by( + alias_id=alias_id, website_email=email + ) + if contact: + return __update_contact_if_needed(contact, name, mail_from) + else: + LOG.warning( + f"Could not find contact with email {email} for alias_id {alias_id} and it should exist" + ) + return ContactCreateResult( + None, created=False, error=ContactCreateError.Unknown + )