Subversion Repositories SmartDukaan

Rev

Rev 20244 | 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.clients.CatalogClient import CatalogClient
from shop2020.clients.TransactionClient import TransactionClient
from shop2020.helpers.impl import DataService
from shop2020.helpers.impl.DataService import Message, UserEmail, EntitiesShared, \
    Report, ReportRoleAuthority, CatalogDashboardUser, UserEmailArchive, QuickLink, \
    AgentWarehouseMapping, UserSms, UserSmsInfo, UserSmsArchive, DealerAuth, Campaigns
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, SmsStatus, SmsType, SmsDeliveryStatus
from shop2020.utils.Utils import log_entry, to_py_date, to_java_date
from sqlalchemy.orm import query
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
    between
from string import Template
import datetime
import os
import smtplib

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.filter(UserEmail.status == 0).all()

def mark_email_as_sent(email_id):
    UserEmail.query.filter(UserEmail.status==1).delete()
    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.status=1
    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)
    if role==-1:
        query.filter()
    else:
        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:
        tclient = TransactionClient().get_client()
        order = tclient.getOrder(order_id)
        if order.logisticsTransactionId:
            email = UserEmailArchive.get_by(emailType = 'DeliverySuccess', source = order.logisticsTransactionId)
            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 save_user_sms_for_sending(userId, mobileNo, text, type):
    userSms = UserSms()
    userSms.user_id = userId
    userSms.createdTimestamp = datetime.datetime.now()
    userSms.mobileNumber = mobileNo
    userSms.attempts = 0
    userSms.smsText = text
    userSms.type = SmsType._VALUES_TO_NAMES[type]
    userSms.status = SmsStatus._VALUES_TO_NAMES[0]
    userSms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[0]
    session.commit()
    return userSms.id
    
def get_sms_to_be_sent():
    print "get_sms_to_be_sent"
    return UserSms.query.filter(UserSms.deliveryStatus== SmsDeliveryStatus._VALUES_TO_NAMES[SmsDeliveryStatus.NOT_SENT]).all()

def mark_sms_as_sent(smsId, status, responseId, responseText):
    sms = UserSms.get_by(id=smsId)
    if sms:
        sms.attempts = sms.attempts+1
        sms.status = SmsStatus._VALUES_TO_NAMES[status]
        sms.responseId = responseId
        sms.responseText = responseText
        session.commit()
    query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(smsId) + ')'
    session.execute(query, mapper=UserSmsArchive)
    if sms:
        sms.delete()
    session.commit()
    
def mark_sms_as_retry(smsId, status, responseId, responseText):
    sms = UserSms.get_by(id=smsId)
    if sms:
        if sms.attempts<3:
            sms.attempts = sms.attempts+1
            sms.status = SmsStatus._VALUES_TO_NAMES[status]
            sms.responseId = responseId
            sms.responseText = responseText
            session.commit()
            return True
        else:
            return False
    else:
        return False

def add_user_sms_info(userSms_Info):
    userSmsInfo = UserSmsInfo()
    userSmsInfo.userId = userSms_Info.userId
    userSmsInfo.mobileNo = userSms_Info.mobileNo
    userSmsInfo.createdTimestamp = to_py_date(userSms_Info.createdTimestamp)
    userSmsInfo.updateTimestamp = to_py_date(userSms_Info.updateTimestamp)
    userSmsInfo.dailyCount = 0
    userSmsInfo.weeklyCount = 0
    userSmsInfo.dndStatus = False
    userSmsInfo.smsSubscribed = True
    session.commit()
    
def update_user_sms_info(userSms_Info):
    userSmsInfo = UserSmsInfo.query.filter(UserSmsInfo.userId == userSms_Info.userId).first()
    if userSmsInfo:
        userSmsInfo.mobileNo = userSms_Info.mobileNo
        userSmsInfo.dndStatus = userSms_Info.dndStatus
        userSmsInfo.smsSubscribed = userSms_Info.smsSubscribed
        userSmsInfo.dailyCount = userSms_Info.dailyCount
        userSmsInfo.weeklyCount = userSms_Info.weeklyCount
        userSmsInfo.updateTimestamp = datetime.datetime.now()
        session.commit()
        return True
    else:
        return False
    
def get_user_sms_info(userId):
    return UserSmsInfo.query.filter(UserSmsInfo.userId == userId).first()

def get_all_users_sms_info(dndStatus, smsSubscribed):
    print 'get all users sms infos'
    return UserSmsInfo.query.filter(UserSmsInfo.dndStatus == dndStatus).filter(UserSmsInfo.smsSubscribed == smsSubscribed).all()

def list_sms_to_get_delivery_info():
    print 'get all message waiting for delivery status'
    return UserSms.query.filter(or_(UserSms.deliveryStatus== SmsDeliveryStatus._VALUES_TO_NAMES[SmsDeliveryStatus.SENT_TO_OPERATOR], UserSms.deliveryStatus== SmsDeliveryStatus._VALUES_TO_NAMES[SmsDeliveryStatus.SUBMITTED_TO_SMSC])).all()

def mark_messages_as_sent_to_operator(userSmsList):
    for userSms in userSmsList:
        sms = UserSms.get_by(id=userSms.id)
        if sms:
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
            sms.attempts = userSms.attempts
            sms.responseId = userSms.responseId
            sms.responseText = userSms.responseText
            session.commit()
    return True
        
def mark_messages_as_submitted_to_smsc(userSmsList):
    for userSms in userSmsList:
        sms = UserSms.get_by(id=userSms.id)
        if sms:
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
            sms.responseText = userSms.responseText
            session.commit()
        query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(sms.id) + ')'
        session.execute(query, mapper=UserSmsArchive)
        if sms:
            sms.delete()
        session.commit()
    return True

def mark_messages_as_sent(userSmsList):
    UserSms.query.filter(UserSms.status==SmsStatus._VALUES_TO_NAMES[SmsStatus.DELIVERED]).delete()
    for userSms in userSmsList:
        sms = UserSms.get_by(id=userSms.id)
        if sms:
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
            sms.responseText = userSms.responseText
            sms.status = SmsStatus._VALUES_TO_NAMES[userSms.status]
            query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(sms.id) + ')'
            session.execute(query, mapper=UserSmsArchive)
            sms.status = SmsStatus._VALUES_TO_NAMES[SmsStatus.DELIVERED]
    session.commit()
    return True

def mark_messages_as_retry(userSmsList):
    for userSms in userSmsList:
        sms = UserSms.get_by(id=userSms.id)
        if sms:
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
            sms.responseText = userSms.responseText
            sms.status = SmsStatus._VALUES_TO_NAMES[userSms.status]
            session.commit()
        query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(sms.id) + ')'
        session.execute(query, mapper=UserSmsArchive)
        if userSms.attempts < 3:
            new_sms_id= save_user_sms_for_sending(userSms.user_id, userSms.mobileNumber, userSms.smsText, userSms.type)
            new_sms = UserSms.get_by(id=new_sms_id)
            new_sms.status = SmsStatus._VALUES_TO_NAMES[0]
            new_sms.attempts = userSms.attempts
            new_sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[0] 
            session.commit()
        if sms:
            sms.delete()
        session.commit()
    return True

def authorise_dealer(tDealerAuth):
    tDealerAuth.isActive = False
    if tDealerAuth.username:
        dealerAuth = DealerAuth.get_by(username=tDealerAuth.username)
        if dealerAuth:
            if tDealerAuth.password == dealerAuth.password and dealerAuth.isActive == True:
                tDealerAuth.role = dealerAuth.role
                if tDealerAuth.lastLocation and dealerAuth.lattitude and dealerAuth.longitude:
                    dealerAuth.lattitude, dealerAuth.longitude, tDealerAuth.lastLocation.lattitude,tDealerAuth.lastLocation.longitude = tDealerAuth.lastLocation.lattitude,tDealerAuth.lastLocation.longitude, dealerAuth.lattitude, dealerAuth.longitude
                if dealerAuth.lastLoggedIn is not None:
                    tDealerAuth.lastLoggedIn = to_java_date(dealerAuth.lastLoggedIn)
                else:
                    tDealerAuth.lastLoggedIn = None
                dealerAuth.lastLoggedIn = datetime.datetime.now()
                tDealerAuth.isActive = True
                session.commit()
             
    tDealerAuth.password = None
    return tDealerAuth

def addCampaignNotification(userEmail,campaignType):
    try:
        exist = Campaigns.get_by(userEmail=userEmail,campaignType=campaignType)
        if exist is not None:
            return "You are already registered."
        else:
            c = Campaigns()
            c.userEmail = userEmail
            c.campaignType = campaignType
            session.commit()
            return "Email registered successfully."
    except Exception as e:
        print e
        return "OOPS!!!Please try again."


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

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