diff --git a/app/models.py b/app/models.py index 2a6fc2f3..ba353c74 100644 --- a/app/models.py +++ b/app/models.py @@ -1208,8 +1208,16 @@ class Mailbox(db.Model, ModelMixin): # Put all aliases belonging to this mailbox to global trash try: for alias in Alias.query.filter_by(mailbox_id=obj_id): - DeletedAlias.create(email=alias.email) - db.session.commit() + # special handling for alias that has several mailboxes and has mailbox_id=obj_id + if len(alias.mailboxes) > 1: + # use the first mailbox found in alias._mailboxes + first_mb = alias._mailboxes[0] + alias.mailbox_id = first_mb.id + alias._mailboxes.remove(first_mb) + else: + # only put aliases that have mailbox as a single mailbox into trash + DeletedAlias.create(email=alias.email) + db.session.commit() # this can happen when a previously deleted alias is re-created via catch-all or directory feature except IntegrityError: LOG.error("Some aliases have been added before to DeletedAlias") diff --git a/tests/test_models.py b/tests/test_models.py index 95c58de3..be796f75 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -5,7 +5,7 @@ import pytest from app.config import EMAIL_DOMAIN, MAX_NB_EMAIL_FREE_PLAN from app.email_utils import parseaddr_unicode from app.extensions import db -from app.models import generate_email, User, Alias, Contact +from app.models import generate_email, User, Alias, Contact, Mailbox, AliasMailbox def test_generate_email(flask_client): @@ -133,3 +133,30 @@ def test_new_addr(flask_client): "Nhơn Nguyễn - abcd at example.com", "rep@sl", ) + + +def test_mailbox_delete(flask_client): + user = User.create( + email="a@b.c", password="password", name="Test User", activated=True + ) + db.session.commit() + + m1 = Mailbox.create(user_id=user.id, email="m1@example.com", verified=True) + m2 = Mailbox.create(user_id=user.id, email="m2@example.com", verified=True) + m3 = Mailbox.create(user_id=user.id, email="m3@example.com", verified=True) + db.session.commit() + + # alias has 2 mailboxes + alias = Alias.create_new(user, "prefix", mailbox_id=m1.id) + db.session.commit() + + alias._mailboxes.append(m2) + alias._mailboxes.append(m3) + db.session.commit() + + assert len(alias.mailboxes) == 3 + + # delete m1, should not delete alias + Mailbox.delete(m1.id) + alias = Alias.get(alias.id) + assert len(alias.mailboxes) == 2