from datetime import datetime

from ascoderu_webapp import db
from ascoderu_webapp.models import Email
from ascoderu_webapp.models import User


def user_exists(name_or_email):
    user = User.query.filter(User.name.ilike(name_or_email) |
                             User.email.ilike(name_or_email)).first()
    return user is not None


def outbox_emails_for(user):
    return Email.query.filter(Email.date.is_(None) &
                              (Email.sender.is_(user.email) |
                               Email.sender.is_(user.name))).all()


def sent_emails_for(user):
    return Email.query.filter(Email.date.isnot(None) &
                              (Email.sender.is_(user.email) |
                               Email.sender.is_(user.name))).all()


def inbox_emails_for(user):
    return [mail for mail in Email.query.all()
            if any(to == user.email or to == user.name for to in mail.to)]


def new_email_for(user, to, subject, body):
    is_to_local_user = user_exists(to)
    email_date = datetime.now() if is_to_local_user else None

    db.session.add(Email(
        date=email_date,
        to=[to],
        sender=user.email or user.name,
        subject=subject,
        body=body))
    db.session.commit()

    return is_to_local_user

@@ -146,614 +146,892 @@
 def 
-user_exists(name_or_email):%0A    user = User.query.filter(User.name.ilike(name_or_email) %7C%0A                             User.email.ilike(name_or_email)).first()%0A    return user is not None%0A%0A%0Adef outbox_emails_for(user):%0A    return Email.query.filter(Email.date.is_(None) &%0A                              (Email.sender.is_(user.email) %7C%0A                               Email.sender.is_(user.name))).all()%0A%0A%0Adef sent_emails_for(user):%0A    return Email.query.filter(Email.date.isnot(None) &%0A                              (Email.sender.is_(user.email) %7C%0A                               Email.sender.is_(user.name))
+_query_emails_by(user):%0A    def query_user_email():%0A        return Email.sender.ilike(user.email)%0A%0A    def query_user_name():%0A        return Email.sender.ilike(user.name)%0A%0A    if user.email and user.name:%0A        return query_user_email() %7C query_user_name()%0A    elif user.email:%0A        return query_user_email()%0A    elif user.name:%0A        return query_user_name()%0A    raise ValueError('one of user.email or user.name must be set')%0A%0A%0Adef user_exists(name_or_email):%0A    user = User.query.filter(User.name.ilike(name_or_email) %7C%0A                             User.email.ilike(name_or_email)).first()%0A    return user is not None%0A%0A%0Adef outbox_emails_for(user):%0A    query = Email.date.is_(None) & _query_emails_by(user)%0A    return Email.query.filter(query).all()%0A%0A%0Adef sent_emails_for(user):%0A    query = Email.date.isnot(None) & _query_emails_by(user)%0A    return Email.query.filter(query
 ).al

Make sent and outbox queries case insensitive