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 encodersfrom email.mime.base import MIMEBasefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom shop2020.helpers.impl import DataServicefrom shop2020.helpers.impl.DataService import Message, UserEmail, EntitiesShared, \Report, ReportRoleAuthority, CatalogDashboardUser, UserEmailArchive, QuickLink, \AgentWarehouseMappingfrom shop2020.helpers.impl.model.Agent import Agentfrom shop2020.helpers.impl.model.DashboardUser import DashboardUserfrom shop2020.thriftpy.utils.ttypes import HelperServiceException, Mail, \Message as Msgfrom shop2020.utils.Utils import log_entry, to_py_datefrom sqlalchemy.orm import queryfrom string import Templateimport datetimeimport osimport smtplibfrom shop2020.clients.CatalogClient import CatalogClientdef 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 0user_email = UserEmail()user_email.emailTo = ';'.join(email_to)user_email.emailFrom = email_fromuser_email.subject = subjectuser_email.body = bodyuser_email.source = sourceuser_email.emailType = email_typeuser_email.status = Falseuser_email.timestamp = datetime.datetime.now()if cc:user_email.cc = ';'.join(cc)if bcc:user_email.bcc = ';'.join(bcc)session.commit()return user_email.iddef 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.datamsg = MIMEText(mail.data)msg['To'] = ', '.join( mail.to )if mail.sender:msg['From'] = mail.senderelse:msg['From'] = "help@saholic.com"msg['Subject'] = mail.subject#msg.attach(mail.data)#handle attachments in mailif 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):passdef 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.idmsg.message = message.messagesession.commit()def getMessage(message_id):msg = Message.get_by(id=message_id)message = Msg()message.id = msg.message_idmessage.message = msg.messagereturn messagedef updateMessage(id, message):msg = Message.get_by(message_id=id)if msg:msg.message = messagesession.commit()else:raise HelperServiceException(101, "message could not be found with id %d" %(id))def getSubstitutedMessage(id, params):#get the message firstmsg = 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 selse:return msg.messagedef add_user(username, password, warehouseId):user = DashboardUser()user.username = usernameuser.password = passworduser.warehouseId = warehouseIduser.addedOn = datetime.datetime.now()user.status = 0try:session.commit()return Trueexcept:raise HelperServiceException(101, "Some error while adding user")return Falsedef delete_user(username):user = DashboardUser.get_by(username=username)if user is None:return Falseuser.delete()session.commit()return Truedef 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 Falseif user.password == oldPassword:user.password = newPasswordsession.commit()return Truereturn Falsedef get_reports(role):query = session.query(Report).join(ReportRoleAuthority)query = query.filter(ReportRoleAuthority.role == role)reports = query.all()return reportsdef 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 = entityIdsStrentities_to_be_shared.email = emailentities_to_be_shared.isEmailed = Falsesession.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 emailBodydef save_quick_link(url, text):quickLink = QuickLink()quickLink.url = urlquickLink.text = textsession.commit()def get_quick_links():return QuickLink.query.all()def update_quicklink(id, url, text):quicklink = QuickLink.get_by(id = id)quicklink.url = urlquicklink.text = textsession.commit()def update_password_for_agent(agentEmailId, password):agent = Agent.get_by(emailId = agentEmailId)agent.password = passwordsession.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-2013if email:return email.bodyelse:return ''#End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013def 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-2013if email:return email.bodyelse:return ''#End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013def 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 warehouseIdsdef close_session():if session.is_active:print "session is active. closing it."session.close()def is_alive():try:return Trueexcept:return False