From b664b0b17b73f1d28dbec24ee7c8a59bd9b6fdd1 Mon Sep 17 00:00:00 2001 From: Son NK Date: Tue, 17 Mar 2020 20:16:20 +0100 Subject: [PATCH] Fix duplicate results --- app/api/views/alias.py | 11 +++++-- app/dashboard/views/index.py | 57 +++++++++++++++++++++++++++++++----- 2 files changed, 58 insertions(+), 10 deletions(-) diff --git a/app/api/views/alias.py b/app/api/views/alias.py index 4f69d878..46ae5e04 100644 --- a/app/api/views/alias.py +++ b/app/api/views/alias.py @@ -9,11 +9,14 @@ from app.api.base import api_bp, verify_api_key from app.config import EMAIL_DOMAIN from app.config import PAGE_LIMIT from app.dashboard.views.alias_log import get_alias_log -from app.dashboard.views.index import get_alias_infos, AliasInfo +from app.dashboard.views.index import ( + AliasInfo, + get_alias_infos_with_pagination, +) from app.extensions import db from app.log import LOG -from app.models import EmailLog from app.models import Alias, Contact +from app.models import EmailLog from app.utils import random_string @@ -48,7 +51,9 @@ def get_aliases(): if data: query = data.get("query") - alias_infos: [AliasInfo] = get_alias_infos(user, page_id=page_id, query=query) + alias_infos: [AliasInfo] = get_alias_infos_with_pagination( + user, page_id=page_id, query=query + ) return ( jsonify( diff --git a/app/dashboard/views/index.py b/app/dashboard/views/index.py index dece96e3..a7c46c44 100644 --- a/app/dashboard/views/index.py +++ b/app/dashboard/views/index.py @@ -184,9 +184,56 @@ def index(): ) -def get_alias_infos( - user, query=None, highlight_alias_id=None, page_id=None -) -> [AliasInfo]: +def get_alias_info(alias: Alias) -> AliasInfo: + q = ( + db.session.query(Contact, EmailLog) + .filter(Contact.alias_id == alias.id) + .filter(EmailLog.contact_id == Contact.id) + ) + + alias_info = AliasInfo( + id=alias.id, + alias=alias, + mailbox=alias.mailbox, + note=alias.note, + nb_blocked=0, + nb_forward=0, + nb_reply=0, + ) + + for _, el in q: + if el.is_reply: + alias_info.nb_reply += 1 + elif el.blocked: + alias_info.nb_blocked += 1 + else: + alias_info.nb_forward += 1 + + return alias_info + + +def get_alias_infos_with_pagination(user, page_id=0, query=None) -> [AliasInfo]: + ret = [] + q = ( + db.session.query(Alias) + .options(joinedload(Alias.mailbox)) + .filter(Alias.user_id == user.id) + ) + + if query: + q = q.filter( + or_(Alias.email.ilike(f"%{query}%"), Alias.note.ilike(f"%{query}%")) + ) + + q = q.limit(PAGE_LIMIT).offset(page_id * PAGE_LIMIT) + + for alias in q: + ret.append(get_alias_info(alias)) + + return ret + + +def get_alias_infos(user, query=None, highlight_alias_id=None) -> [AliasInfo]: if query: query = query.strip().lower() @@ -206,10 +253,6 @@ def get_alias_infos( or_(Alias.email.ilike(f"%{query}%"), Alias.note.ilike(f"%{query}%")) ) - # pagination activated - if page_id is not None: - q = q.limit(PAGE_LIMIT).offset(page_id * PAGE_LIMIT) - for ge, fe, fel, mb in q: if ge.email not in aliases: aliases[ge.email] = AliasInfo(