Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
353 ashish 1
'''
2
Created on 14-Jul-2010
3
 
4
@author: ashish
5
'''
5110 mandeep.dh 6
from elixir import *
7
from email import encoders
8
from email.mime.base import MIMEBase
353 ashish 9
from email.mime.multipart import MIMEMultipart
5110 mandeep.dh 10
from email.mime.text import MIMEText
11
from shop2020.helpers.impl import DataService
4806 varun.gupt 12
from shop2020.helpers.impl.DataService import Message, UserEmail, EntitiesShared, \
7410 amar.kumar 13
    Report, ReportRoleAuthority, CatalogDashboardUser, UserEmailArchive, QuickLink, \
14
    AgentWarehouseMapping
5110 mandeep.dh 15
from shop2020.helpers.impl.model.Agent import Agent
16
from shop2020.helpers.impl.model.DashboardUser import DashboardUser
17
from shop2020.thriftpy.utils.ttypes import HelperServiceException, Mail, \
18
    Message as Msg
19
from shop2020.utils.Utils import log_entry, to_py_date
20
from sqlalchemy.orm import query
353 ashish 21
from string import Template
494 rajveer 22
import datetime
5110 mandeep.dh 23
import os
24
import smtplib
5483 varun.gupt 25
from shop2020.clients.CatalogClient import CatalogClient
353 ashish 26
 
3187 rajveer 27
def initialize(dbname='helper', db_hostname="localhost"):
494 rajveer 28
    log_entry("initialize@DataAccessor", "Initializing data service")
3187 rajveer 29
    DataService.initialize(dbname, db_hostname)
494 rajveer 30
 
8020 rajveer 31
def save_user_email_for_sending(email_to, email_from, subject, body, source, email_type, cc, bcc, sourceId):
32
    ## Do not send mail to users except source Website.
33
    if sourceId != 1:
34
        return 0
1395 varun.gupt 35
    user_email = UserEmail()
5864 rajveer 36
    user_email.emailTo = ';'.join(email_to)
1395 varun.gupt 37
    user_email.emailFrom = email_from
38
    user_email.subject = subject
39
    user_email.body = body
40
    user_email.source = source
41
    user_email.emailType = email_type
42
    user_email.status = False
43
    user_email.timestamp = datetime.datetime.now()
5864 rajveer 44
    if cc:
45
        user_email.cc = ';'.join(cc)
46
    if bcc:
47
        user_email.bcc = ';'.join(bcc)
1395 varun.gupt 48
    session.commit()
3206 mandeep.dh 49
    return user_email.id
1422 varun.gupt 50
 
3086 rajveer 51
def get_emails_to_be_sent():
1422 varun.gupt 52
    print "get_emails_to_be_sent"
3005 chandransh 53
    return UserEmail.query.all()
1422 varun.gupt 54
 
55
def mark_email_as_sent(email_id):
3005 chandransh 56
    query = 'INSERT INTO ' + str(UserEmailArchive.table) + ' (select * from ' + str(UserEmail.table) + ' where id = ' + str(email_id) + ')'
57
    session.execute(query, mapper=UserEmailArchive)
1422 varun.gupt 58
    email = UserEmail.get_by(id = email_id)
3005 chandransh 59
    if email:
60
        email.delete()
1422 varun.gupt 61
    session.commit()
62
 
353 ashish 63
def sendMail(mail):
64
    if not mail:
65
        raise HelperServiceException(101, "mail not present")
581 rajveer 66
    #msg = MIMEMultipart()
67
    #mail = Mail()
928 rajveer 68
    if mail.sender:
69
        mail.data = "This mail is sent by " + mail.sender + "\n" + mail.data
70
 
581 rajveer 71
    msg = MIMEText(mail.data)
900 rajveer 72
    msg['To'] = ', '.join( mail.to )
928 rajveer 73
    if mail.sender:
74
        msg['From'] = mail.sender
75
    else:    
76
        msg['From'] = "help@saholic.com"
900 rajveer 77
    msg['Subject'] = mail.subject
581 rajveer 78
    #msg.attach(mail.data)
353 ashish 79
 
80
    #handle attachments in mail
81
    if mail.attachments:
82
        for attach in mail.attachments:
83
 
84
            part = MIMEBase('application', 'octet-stream')
85
            part.set_payload(open(attach, 'rb').read())
86
            encoders.encode_base64(part)
87
            part.add_header('Content-Disposition',
88
                    'attachment; filename="%s"' % os.path.basename(attach))
89
            msg.attach(part)
900 rajveer 90
 
353 ashish 91
    for to in mail.to:
873 rajveer 92
        mail.sender = "help@shop2020.in"
93
        mail.password = "5h0p2o2o"
353 ashish 94
        mailServer = smtplib.SMTP("smtp.gmail.com", 587)
95
        mailServer.ehlo()
96
        mailServer.starttls()
97
        mailServer.ehlo()
98
        mailServer.login(mail.sender, mail.password)
99
        mailServer.sendmail(mail.password, to, msg.as_string())
100
        # Should be mailServer.quit(), but that crashes...
101
        mailServer.close() 
102
 
103
def sendText(text):
104
    pass
105
 
106
def addMessage(message):
107
    msg = Message.get_by(message_id=message.id)
108
    if msg:
109
        raise HelperServiceException(101, "Message is already present. Please try updation api instead")
110
    msg = Message();
111
    msg.message_id = message.id
112
    msg.message = message.message
113
    session.commit()
114
 
115
def getMessage(message_id):
116
    msg = Message.get_by(id=message_id)
117
    message = Msg()
118
    message.id = msg.message_id
119
    message.message = msg.message
120
    return message
121
 
122
def updateMessage(id, message):
123
    msg = Message.get_by(message_id=id)
124
    if msg:
125
        msg.message = message
126
        session.commit()
127
    else:
128
        raise HelperServiceException(101, "message could not be found with id %d" %(id))
129
 
130
def getSubstitutedMessage(id, params):
131
    #get the message first
132
    msg = Message.get_by(message_id=id)
133
    if not msg:
134
        raise HelperServiceException(101, "message could not be found with id %d" %(id))
135
    if params:
136
        s = Template(msg.message)
137
        s = s.safe_substitute(params)
138
        return s
139
    else:
140
        return msg.message
494 rajveer 141
 
142
def add_user(username, password, warehouseId):
143
    user = DashboardUser()
144
    user.username = username
145
    user.password = password
146
    user.warehouseId = warehouseId
147
    user.addedOn = datetime.datetime.now()
148
    user.status = 0
149
    try:
150
        session.commit()
151
        return True
152
    except:
153
        raise HelperServiceException(101, "Some error while adding user")
154
        return False
155
 
156
def delete_user(username):
157
    user = DashboardUser.get_by(username=username)
158
    if user is None:
159
        return False
160
    user.delete()
766 rajveer 161
    session.commit()
494 rajveer 162
    return True
163
 
2445 chandransh 164
def authenticate_dashboard_user(username, password):
165
    user = DashboardUser.get_by(username=username, password=password)
494 rajveer 166
    if user is None:
2445 chandransh 167
        raise HelperServiceException(101, "No dashboard user found")
494 rajveer 168
 
2445 chandransh 169
    user.loggedOn = datetime.datetime.now()
170
    session.commit()
171
    return user.to_thrift_object()
172
 
494 rajveer 173
def update_password(username, oldPassword, newPassword):
174
    user = DashboardUser.get_by(username=username)
175
    if user is None:
176
        return False
177
    if user.password == oldPassword:
178
        user.password = newPassword
766 rajveer 179
        session.commit()
494 rajveer 180
        return True
766 rajveer 181
    return False
182
 
1891 ankur.sing 183
def get_reports(role):
184
    query = session.query(Report).join(ReportRoleAuthority)
185
    query = query.filter(ReportRoleAuthority.role == role)
186
    reports = query.all()
187
    return reports
188
 
4806 varun.gupt 189
def share_entities(entityIds, email):
190
    if entityIds:
191
        entityIdsStr = ''
5483 varun.gupt 192
        email_body = get_email_body_for_product_sharing(entityIds)
193
        save_user_email_for_sending(email, '', 'Check out Saholic.com', email_body, '', 'MOBILE_SHARE')
4806 varun.gupt 194
 
195
        for entityId in entityIds:
196
            entityIdsStr += str(entityId)
197
 
198
        entities_to_be_shared = EntitiesShared()
199
        entities_to_be_shared.entityIds = entityIdsStr
200
        entities_to_be_shared.email = email
201
        entities_to_be_shared.isEmailed = False
202
        session.commit()
203
 
5483 varun.gupt 204
def get_email_body_for_product_sharing(entityIds):
205
    catalog_client = CatalogClient().get_client()
206
 
207
    emailBody = '<html><body><p>Check out following products on Saholic:</p><ul>\n'
208
    for entityId in entityIds:
209
        list_items = catalog_client.getItemsByCatalogId(entityId)
210
        url = 'http://www.saholic.com/entity/%s' % (entityId)
211
        item = list_items[0]
212
        name = item.brand + ' '
213
        name += item.modelName + ' ' if item.modelName is not None else ''
214
        name += item.modelNumber if item.modelNumber is not None else ''
215
        emailBody += '<li><a href="%s">%s</a></li>' % (url, name)
216
    emailBody += '</ul></body></html>'
217
    return emailBody
218
 
4806 varun.gupt 219
def save_quick_link(url, text):
220
    quickLink = QuickLink()
221
    quickLink.url = url
222
    quickLink.text = text
223
    session.commit()
224
 
225
def get_quick_links():
226
    return QuickLink.query.all()
227
 
4996 varun.gupt 228
def update_quicklink(id, url, text):
229
    quicklink = QuickLink.get_by(id = id)
230
    quicklink.url = url
231
    quicklink.text = text
232
    session.commit()
233
 
5110 mandeep.dh 234
def update_password_for_agent(agentEmailId, password):
235
    agent = Agent.get_by(emailId = agentEmailId)
236
    agent.password = password
237
    session.commit()
238
 
5055 varun.gupt 239
def get_emails_for_notifications_sent(start_datetime, end_datetime):
240
    query = UserEmailArchive.query.filter(UserEmailArchive.emailType == 'ProductNotification')
241
    query = query.filter(UserEmailArchive.timestamp >= start_datetime)
242
    query = query.filter(UserEmailArchive.timestamp <= end_datetime)
243
    return query.all()
6322 amar.kumar 244
def get_order_confirmation_mail(order_id):
245
    email = UserEmailArchive.get_by(emailType = 'TransactionInfo', source = order_id)
7643 manish.sha 246
    #Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
247
    if email:
248
        return email.body
249
    else:
250
        return ''
251
    #End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
6322 amar.kumar 252
 
7221 kshitij.so 253
def get_order_delivery_mail(order_id):
254
    email = UserEmailArchive.get_by(emailType = 'DeliverySuccess', source = order_id)
7643 manish.sha 255
    #Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
256
    if email:
257
        return email.body
258
    else:
259
        return ''
260
    #End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
7221 kshitij.so 261
 
7410 amar.kumar 262
def get_warehouseIds_for_agent(agent_emailId):
263
    agent = Agent.get_by(emailId = agent_emailId)
264
    agent_warehouse_mappings = AgentWarehouseMapping.query.filter(AgentWarehouseMapping.agentId == agent.id).all()
265
    warehouseIds = []
266
    for mapping in agent_warehouse_mappings:
267
        try:
268
            warehouseIds.append(mapping.warehouseId)
269
        except:
270
            raise HelperServiceException(108, "Exception while getting warehouseIds for Agent")
271
    return warehouseIds
272
 
766 rajveer 273
def close_session():
274
    if session.is_active:
275
        print "session is active. closing it."
3376 rajveer 276
        session.close()
277
 
278
def is_alive():
279
    try:
280
        return True
281
    except:
282
        return False