Subversion Repositories SmartDukaan

Rev

Rev 7643 | Rev 12696 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

'''
Created on 14-Jul-2010

@author: ashish
'''
from elixir import *
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from shop2020.helpers.impl import DataService
from shop2020.helpers.impl.DataService import Message, UserEmail, EntitiesShared, \
    Report, ReportRoleAuthority, CatalogDashboardUser, UserEmailArchive, QuickLink, \
    AgentWarehouseMapping
from shop2020.helpers.impl.model.Agent import Agent
from shop2020.helpers.impl.model.DashboardUser import DashboardUser
from shop2020.thriftpy.utils.ttypes import HelperServiceException, Mail, \
    Message as Msg
from shop2020.utils.Utils import log_entry, to_py_date
from sqlalchemy.orm import query
from string import Template
import datetime
import os
import smtplib
from shop2020.clients.CatalogClient import CatalogClient

def initialize(dbname='helper', db_hostname="localhost"):
    log_entry("initialize@DataAccessor", "Initializing data service")
    DataService.initialize(dbname, db_hostname)
    
def save_user_email_for_sending(email_to, email_from, subject, body, source, email_type, cc, bcc, sourceId):
    ## Do not send mail to users except source Website.
    if sourceId != 1:
        return 0
    user_email = UserEmail()
    user_email.emailTo = ';'.join(email_to)
    user_email.emailFrom = email_from
    user_email.subject = subject
    user_email.body = body
    user_email.source = source
    user_email.emailType = email_type
    user_email.status = False
    user_email.timestamp = datetime.datetime.now()
    if cc:
        user_email.cc = ';'.join(cc)
    if bcc:
        user_email.bcc = ';'.join(bcc)
    session.commit()
    return user_email.id

def get_emails_to_be_sent():
    print "get_emails_to_be_sent"
    return UserEmail.query.all()

def mark_email_as_sent(email_id):
    query = 'INSERT INTO ' + str(UserEmailArchive.table) + ' (select * from ' + str(UserEmail.table) + ' where id = ' + str(email_id) + ')'
    session.execute(query, mapper=UserEmailArchive)
    email = UserEmail.get_by(id = email_id)
    if email:
        email.delete()
    session.commit()

def sendMail(mail):
    if not mail:
        raise HelperServiceException(101, "mail not present")
    #msg = MIMEMultipart()
    #mail = Mail()
    if mail.sender:
        mail.data = "This mail is sent by " + mail.sender + "\n" + mail.data
        
    msg = MIMEText(mail.data)
    msg['To'] = ', '.join( mail.to )
    if mail.sender:
        msg['From'] = mail.sender
    else:    
        msg['From'] = "help@saholic.com"
    msg['Subject'] = mail.subject
    #msg.attach(mail.data)
    
    #handle attachments in mail
    if mail.attachments:
        for attach in mail.attachments:
                   
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(attach, 'rb').read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                    'attachment; filename="%s"' % os.path.basename(attach))
            msg.attach(part)
    
    for to in mail.to:
        mail.sender = "help@shop2020.in"
        mail.password = "5h0p2o2o"
        mailServer = smtplib.SMTP("smtp.gmail.com", 587)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(mail.sender, mail.password)
        mailServer.sendmail(mail.password, to, msg.as_string())
        # Should be mailServer.quit(), but that crashes...
        mailServer.close() 
        
def sendText(text):
    pass

def addMessage(message):
    msg = Message.get_by(message_id=message.id)
    if msg:
        raise HelperServiceException(101, "Message is already present. Please try updation api instead")
    msg = Message();
    msg.message_id = message.id
    msg.message = message.message
    session.commit()
    
def getMessage(message_id):
    msg = Message.get_by(id=message_id)
    message = Msg()
    message.id = msg.message_id
    message.message = msg.message
    return message

def updateMessage(id, message):
    msg = Message.get_by(message_id=id)
    if msg:
        msg.message = message
        session.commit()
    else:
        raise HelperServiceException(101, "message could not be found with id %d" %(id))

def getSubstitutedMessage(id, params):
    #get the message first
    msg = Message.get_by(message_id=id)
    if not msg:
        raise HelperServiceException(101, "message could not be found with id %d" %(id))
    if params:
        s = Template(msg.message)
        s = s.safe_substitute(params)
        return s
    else:
        return msg.message

def add_user(username, password, warehouseId):
    user = DashboardUser()
    user.username = username
    user.password = password
    user.warehouseId = warehouseId
    user.addedOn = datetime.datetime.now()
    user.status = 0
    try:
        session.commit()
        return True
    except:
        raise HelperServiceException(101, "Some error while adding user")
        return False

def delete_user(username):
    user = DashboardUser.get_by(username=username)
    if user is None:
        return False
    user.delete()
    session.commit()
    return True

def authenticate_dashboard_user(username, password):
    user = DashboardUser.get_by(username=username, password=password)
    if user is None:
        raise HelperServiceException(101, "No dashboard user found")
    
    user.loggedOn = datetime.datetime.now()
    session.commit()
    return user.to_thrift_object()
    
def update_password(username, oldPassword, newPassword):
    user = DashboardUser.get_by(username=username)
    if user is None:
        return False
    if user.password == oldPassword:
        user.password = newPassword
        session.commit()
        return True
    return False

def get_reports(role):
    query = session.query(Report).join(ReportRoleAuthority)
    query = query.filter(ReportRoleAuthority.role == role)
    reports = query.all()
    return reports

def share_entities(entityIds, email):
    if entityIds:
        entityIdsStr = ''
        email_body = get_email_body_for_product_sharing(entityIds)
        save_user_email_for_sending(email, '', 'Check out Saholic.com', email_body, '', 'MOBILE_SHARE')
        
        for entityId in entityIds:
            entityIdsStr += str(entityId)
        
        entities_to_be_shared = EntitiesShared()
        entities_to_be_shared.entityIds = entityIdsStr
        entities_to_be_shared.email = email
        entities_to_be_shared.isEmailed = False
        session.commit()

def get_email_body_for_product_sharing(entityIds):
    catalog_client = CatalogClient().get_client()
    
    emailBody = '<html><body><p>Check out following products on Saholic:</p><ul>\n'
    for entityId in entityIds:
        list_items = catalog_client.getItemsByCatalogId(entityId)
        url = 'http://www.saholic.com/entity/%s' % (entityId)
        item = list_items[0]
        name = item.brand + ' '
        name += item.modelName + ' ' if item.modelName is not None else ''
        name += item.modelNumber if item.modelNumber is not None else ''
        emailBody += '<li><a href="%s">%s</a></li>' % (url, name)
    emailBody += '</ul></body></html>'
    return emailBody

def save_quick_link(url, text):
    quickLink = QuickLink()
    quickLink.url = url
    quickLink.text = text
    session.commit()

def get_quick_links():
    return QuickLink.query.all()

def update_quicklink(id, url, text):
    quicklink = QuickLink.get_by(id = id)
    quicklink.url = url
    quicklink.text = text
    session.commit()

def update_password_for_agent(agentEmailId, password):
    agent = Agent.get_by(emailId = agentEmailId)
    agent.password = password
    session.commit()

def get_emails_for_notifications_sent(start_datetime, end_datetime):
    query = UserEmailArchive.query.filter(UserEmailArchive.emailType == 'ProductNotification')
    query = query.filter(UserEmailArchive.timestamp >= start_datetime)
    query = query.filter(UserEmailArchive.timestamp <= end_datetime)
    return query.all()
def get_order_confirmation_mail(order_id):
    email = UserEmailArchive.get_by(emailType = 'TransactionInfo', source = order_id)
    #Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
    if email:
        return email.body
    else:
        return ''
    #End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
    
def get_order_delivery_mail(order_id):
    email = UserEmailArchive.get_by(emailType = 'DeliverySuccess', source = order_id)
    #Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
    if email:
        return email.body
    else:
        return ''
    #End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013

def get_warehouseIds_for_agent(agent_emailId):
    agent = Agent.get_by(emailId = agent_emailId)
    agent_warehouse_mappings = AgentWarehouseMapping.query.filter(AgentWarehouseMapping.agentId == agent.id).all()
    warehouseIds = []
    for mapping in agent_warehouse_mappings:
        try:
            warehouseIds.append(mapping.warehouseId)
        except:
            raise HelperServiceException(108, "Exception while getting warehouseIds for Agent")
    return warehouseIds

def close_session():
    if session.is_active:
        print "session is active. closing it."
        session.close()

def is_alive():
    try:
        return True
    except:
        return False