Subversion Repositories SmartDukaan

Rev

Rev 13214 | Rev 13360 | 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
12696 amit.gupta 11
from shop2020.clients.CatalogClient import CatalogClient
5110 mandeep.dh 12
from shop2020.helpers.impl import DataService
4806 varun.gupt 13
from shop2020.helpers.impl.DataService import Message, UserEmail, EntitiesShared, \
7410 amar.kumar 14
    Report, ReportRoleAuthority, CatalogDashboardUser, UserEmailArchive, QuickLink, \
13214 kshitij.so 15
    AgentWarehouseMapping, UserSms, UserSmsInfo, UserSmsArchive, DealerAuth, Campaigns
5110 mandeep.dh 16
from shop2020.helpers.impl.model.Agent import Agent
17
from shop2020.helpers.impl.model.DashboardUser import DashboardUser
18
from shop2020.thriftpy.utils.ttypes import HelperServiceException, Mail, \
12691 manish.sha 19
    Message as Msg, SmsStatus, SmsType, SmsDeliveryStatus
12696 amit.gupta 20
from shop2020.utils.Utils import log_entry, to_py_date, to_java_date
5110 mandeep.dh 21
from sqlalchemy.orm import query
12691 manish.sha 22
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
23
from sqlalchemy.sql import func
24
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
25
    between
353 ashish 26
from string import Template
494 rajveer 27
import datetime
5110 mandeep.dh 28
import os
29
import smtplib
353 ashish 30
 
3187 rajveer 31
def initialize(dbname='helper', db_hostname="localhost"):
494 rajveer 32
    log_entry("initialize@DataAccessor", "Initializing data service")
3187 rajveer 33
    DataService.initialize(dbname, db_hostname)
494 rajveer 34
 
8020 rajveer 35
def save_user_email_for_sending(email_to, email_from, subject, body, source, email_type, cc, bcc, sourceId):
36
    ## Do not send mail to users except source Website.
37
    if sourceId != 1:
38
        return 0
1395 varun.gupt 39
    user_email = UserEmail()
5864 rajveer 40
    user_email.emailTo = ';'.join(email_to)
1395 varun.gupt 41
    user_email.emailFrom = email_from
42
    user_email.subject = subject
43
    user_email.body = body
44
    user_email.source = source
45
    user_email.emailType = email_type
46
    user_email.status = False
47
    user_email.timestamp = datetime.datetime.now()
5864 rajveer 48
    if cc:
49
        user_email.cc = ';'.join(cc)
50
    if bcc:
51
        user_email.bcc = ';'.join(bcc)
1395 varun.gupt 52
    session.commit()
3206 mandeep.dh 53
    return user_email.id
1422 varun.gupt 54
 
3086 rajveer 55
def get_emails_to_be_sent():
1422 varun.gupt 56
    print "get_emails_to_be_sent"
3005 chandransh 57
    return UserEmail.query.all()
1422 varun.gupt 58
 
59
def mark_email_as_sent(email_id):
3005 chandransh 60
    query = 'INSERT INTO ' + str(UserEmailArchive.table) + ' (select * from ' + str(UserEmail.table) + ' where id = ' + str(email_id) + ')'
61
    session.execute(query, mapper=UserEmailArchive)
1422 varun.gupt 62
    email = UserEmail.get_by(id = email_id)
3005 chandransh 63
    if email:
64
        email.delete()
1422 varun.gupt 65
    session.commit()
66
 
353 ashish 67
def sendMail(mail):
68
    if not mail:
69
        raise HelperServiceException(101, "mail not present")
581 rajveer 70
    #msg = MIMEMultipart()
71
    #mail = Mail()
928 rajveer 72
    if mail.sender:
73
        mail.data = "This mail is sent by " + mail.sender + "\n" + mail.data
74
 
581 rajveer 75
    msg = MIMEText(mail.data)
900 rajveer 76
    msg['To'] = ', '.join( mail.to )
928 rajveer 77
    if mail.sender:
78
        msg['From'] = mail.sender
79
    else:    
80
        msg['From'] = "help@saholic.com"
900 rajveer 81
    msg['Subject'] = mail.subject
581 rajveer 82
    #msg.attach(mail.data)
353 ashish 83
 
84
    #handle attachments in mail
85
    if mail.attachments:
86
        for attach in mail.attachments:
87
 
88
            part = MIMEBase('application', 'octet-stream')
89
            part.set_payload(open(attach, 'rb').read())
90
            encoders.encode_base64(part)
91
            part.add_header('Content-Disposition',
92
                    'attachment; filename="%s"' % os.path.basename(attach))
93
            msg.attach(part)
900 rajveer 94
 
353 ashish 95
    for to in mail.to:
873 rajveer 96
        mail.sender = "help@shop2020.in"
97
        mail.password = "5h0p2o2o"
353 ashish 98
        mailServer = smtplib.SMTP("smtp.gmail.com", 587)
99
        mailServer.ehlo()
100
        mailServer.starttls()
101
        mailServer.ehlo()
102
        mailServer.login(mail.sender, mail.password)
103
        mailServer.sendmail(mail.password, to, msg.as_string())
104
        # Should be mailServer.quit(), but that crashes...
105
        mailServer.close() 
106
 
107
def sendText(text):
108
    pass
109
 
110
def addMessage(message):
111
    msg = Message.get_by(message_id=message.id)
112
    if msg:
113
        raise HelperServiceException(101, "Message is already present. Please try updation api instead")
114
    msg = Message();
115
    msg.message_id = message.id
116
    msg.message = message.message
117
    session.commit()
118
 
119
def getMessage(message_id):
120
    msg = Message.get_by(id=message_id)
121
    message = Msg()
122
    message.id = msg.message_id
123
    message.message = msg.message
124
    return message
125
 
126
def updateMessage(id, message):
127
    msg = Message.get_by(message_id=id)
128
    if msg:
129
        msg.message = message
130
        session.commit()
131
    else:
132
        raise HelperServiceException(101, "message could not be found with id %d" %(id))
133
 
134
def getSubstitutedMessage(id, params):
135
    #get the message first
136
    msg = Message.get_by(message_id=id)
137
    if not msg:
138
        raise HelperServiceException(101, "message could not be found with id %d" %(id))
139
    if params:
140
        s = Template(msg.message)
141
        s = s.safe_substitute(params)
142
        return s
143
    else:
144
        return msg.message
494 rajveer 145
 
146
def add_user(username, password, warehouseId):
147
    user = DashboardUser()
148
    user.username = username
149
    user.password = password
150
    user.warehouseId = warehouseId
151
    user.addedOn = datetime.datetime.now()
152
    user.status = 0
153
    try:
154
        session.commit()
155
        return True
156
    except:
157
        raise HelperServiceException(101, "Some error while adding user")
158
        return False
159
 
160
def delete_user(username):
161
    user = DashboardUser.get_by(username=username)
162
    if user is None:
163
        return False
164
    user.delete()
766 rajveer 165
    session.commit()
494 rajveer 166
    return True
167
 
2445 chandransh 168
def authenticate_dashboard_user(username, password):
169
    user = DashboardUser.get_by(username=username, password=password)
494 rajveer 170
    if user is None:
2445 chandransh 171
        raise HelperServiceException(101, "No dashboard user found")
494 rajveer 172
 
2445 chandransh 173
    user.loggedOn = datetime.datetime.now()
174
    session.commit()
175
    return user.to_thrift_object()
176
 
494 rajveer 177
def update_password(username, oldPassword, newPassword):
178
    user = DashboardUser.get_by(username=username)
179
    if user is None:
180
        return False
181
    if user.password == oldPassword:
182
        user.password = newPassword
766 rajveer 183
        session.commit()
494 rajveer 184
        return True
766 rajveer 185
    return False
186
 
1891 ankur.sing 187
def get_reports(role):
188
    query = session.query(Report).join(ReportRoleAuthority)
189
    query = query.filter(ReportRoleAuthority.role == role)
190
    reports = query.all()
191
    return reports
192
 
4806 varun.gupt 193
def share_entities(entityIds, email):
194
    if entityIds:
195
        entityIdsStr = ''
5483 varun.gupt 196
        email_body = get_email_body_for_product_sharing(entityIds)
197
        save_user_email_for_sending(email, '', 'Check out Saholic.com', email_body, '', 'MOBILE_SHARE')
4806 varun.gupt 198
 
199
        for entityId in entityIds:
200
            entityIdsStr += str(entityId)
201
 
202
        entities_to_be_shared = EntitiesShared()
203
        entities_to_be_shared.entityIds = entityIdsStr
204
        entities_to_be_shared.email = email
205
        entities_to_be_shared.isEmailed = False
206
        session.commit()
207
 
5483 varun.gupt 208
def get_email_body_for_product_sharing(entityIds):
209
    catalog_client = CatalogClient().get_client()
210
 
211
    emailBody = '<html><body><p>Check out following products on Saholic:</p><ul>\n'
212
    for entityId in entityIds:
213
        list_items = catalog_client.getItemsByCatalogId(entityId)
214
        url = 'http://www.saholic.com/entity/%s' % (entityId)
215
        item = list_items[0]
216
        name = item.brand + ' '
217
        name += item.modelName + ' ' if item.modelName is not None else ''
218
        name += item.modelNumber if item.modelNumber is not None else ''
219
        emailBody += '<li><a href="%s">%s</a></li>' % (url, name)
220
    emailBody += '</ul></body></html>'
221
    return emailBody
222
 
4806 varun.gupt 223
def save_quick_link(url, text):
224
    quickLink = QuickLink()
225
    quickLink.url = url
226
    quickLink.text = text
227
    session.commit()
228
 
229
def get_quick_links():
230
    return QuickLink.query.all()
231
 
4996 varun.gupt 232
def update_quicklink(id, url, text):
233
    quicklink = QuickLink.get_by(id = id)
234
    quicklink.url = url
235
    quicklink.text = text
236
    session.commit()
237
 
5110 mandeep.dh 238
def update_password_for_agent(agentEmailId, password):
239
    agent = Agent.get_by(emailId = agentEmailId)
240
    agent.password = password
241
    session.commit()
242
 
5055 varun.gupt 243
def get_emails_for_notifications_sent(start_datetime, end_datetime):
244
    query = UserEmailArchive.query.filter(UserEmailArchive.emailType == 'ProductNotification')
245
    query = query.filter(UserEmailArchive.timestamp >= start_datetime)
246
    query = query.filter(UserEmailArchive.timestamp <= end_datetime)
247
    return query.all()
6322 amar.kumar 248
def get_order_confirmation_mail(order_id):
249
    email = UserEmailArchive.get_by(emailType = 'TransactionInfo', source = order_id)
7643 manish.sha 250
    #Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
251
    if email:
252
        return email.body
253
    else:
254
        return ''
255
    #End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
6322 amar.kumar 256
 
7221 kshitij.so 257
def get_order_delivery_mail(order_id):
258
    email = UserEmailArchive.get_by(emailType = 'DeliverySuccess', source = order_id)
7643 manish.sha 259
    #Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
260
    if email:
261
        return email.body
262
    else:
263
        return ''
264
    #End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
7221 kshitij.so 265
 
7410 amar.kumar 266
def get_warehouseIds_for_agent(agent_emailId):
267
    agent = Agent.get_by(emailId = agent_emailId)
268
    agent_warehouse_mappings = AgentWarehouseMapping.query.filter(AgentWarehouseMapping.agentId == agent.id).all()
269
    warehouseIds = []
270
    for mapping in agent_warehouse_mappings:
271
        try:
272
            warehouseIds.append(mapping.warehouseId)
273
        except:
274
            raise HelperServiceException(108, "Exception while getting warehouseIds for Agent")
275
    return warehouseIds
276
 
12691 manish.sha 277
def save_user_sms_for_sending(userId, mobileNo, text, type):
278
    userSms = UserSms()
279
    userSms.user_id = userId
280
    userSms.createdTimestamp = datetime.datetime.now()
281
    userSms.mobileNumber = mobileNo
282
    userSms.attempts = 0
283
    userSms.smsText = text
12877 manish.sha 284
    userSms.type = SmsType._VALUES_TO_NAMES[type]
285
    userSms.status = SmsStatus._VALUES_TO_NAMES[0]
286
    userSms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[0]
12691 manish.sha 287
    session.commit()
288
    return userSms.id
289
 
290
def get_sms_to_be_sent():
291
    print "get_emails_to_be_sent"
12882 manish.sha 292
    return UserSms.query.filter(UserSms.deliveryStatus== SmsDeliveryStatus._VALUES_TO_NAMES[SmsDeliveryStatus.NOT_SENT]).all()
12691 manish.sha 293
 
294
def mark_sms_as_sent(smsId, status, responseId, responseText):
12902 manish.sha 295
    sms = UserSms.get_by(id=smsId)
12691 manish.sha 296
    if sms:
297
        sms.attempts = sms.attempts+1
12877 manish.sha 298
        sms.status = SmsStatus._VALUES_TO_NAMES[status]
12691 manish.sha 299
        sms.responseId = responseId
300
        sms.responseText = responseText
301
        session.commit()
302
    query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(smsId) + ')'
303
    session.execute(query, mapper=UserSmsArchive)
304
    if sms:
305
        sms.delete()
306
    session.commit()
307
 
308
def mark_sms_as_retry(smsId, status, responseId, responseText):
12902 manish.sha 309
    sms = UserSms.get_by(id=smsId)
12691 manish.sha 310
    if sms:
311
        if sms.attempts<3:
312
            sms.attempts = sms.attempts+1
12877 manish.sha 313
            sms.status = SmsStatus._VALUES_TO_NAMES[status]
12691 manish.sha 314
            sms.responseId = responseId
315
            sms.responseText = responseText
316
            session.commit()
317
            return True
318
        else:
319
            return False
320
    else:
321
        return False
322
 
323
def add_user_sms_info(userSms_Info):
324
    userSmsInfo = UserSmsInfo()
325
    userSmsInfo.userId = userSms_Info.userId
326
    userSmsInfo.mobileNo = userSms_Info.mobileNo
327
    userSmsInfo.createdTimestamp = to_py_date(userSms_Info.createdTimestamp)
328
    userSmsInfo.updateTimestamp = to_py_date(userSms_Info.updateTimestamp)
329
    userSmsInfo.dailyCount = 0
330
    userSmsInfo.weeklyCount = 0
331
    userSmsInfo.dndStatus = False
332
    userSmsInfo.smsSubscribed = True
333
    session.commit()
334
 
335
def update_user_sms_info(userSms_Info):
336
    userSmsInfo = UserSmsInfo.query.filter(UserSmsInfo.userId == userSms_Info.userId).first()
337
    if userSmsInfo:
338
        userSmsInfo.mobileNo = userSms_Info.mobileNo
339
        userSmsInfo.dndStatus = userSms_Info.dndStatus
340
        userSmsInfo.smsSubscribed = userSms_Info.smsSubscribed
341
        userSmsInfo.dailyCount = userSms_Info.dailyCount
12946 manish.sha 342
        userSmsInfo.weeklyCount = userSms_Info.weeklyCount
12691 manish.sha 343
        userSmsInfo.updateTimestamp = datetime.datetime.now()
344
        session.commit()
345
        return True
346
    else:
347
        return False
348
 
349
def get_user_sms_info(userId):
350
    return UserSmsInfo.query.filter(UserSmsInfo.userId == userId).first()
351
 
352
def get_all_users_sms_info(dndStatus, smsSubscribed):
353
    print 'get all users sms infos'
354
    return UserSmsInfo.query.filter(UserSmsInfo.dndStatus == dndStatus).filter(UserSmsInfo.smsSubscribed == smsSubscribed).all()
355
 
356
def list_sms_to_get_delivery_info():
357
    print 'get all message waiting for delivery status'
12882 manish.sha 358
    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()
12691 manish.sha 359
 
360
def mark_messages_as_sent_to_operator(userSmsList):
361
    for userSms in userSmsList:
12902 manish.sha 362
        sms = UserSms.get_by(id=userSms.id)
12691 manish.sha 363
        if sms:
12877 manish.sha 364
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
12691 manish.sha 365
            sms.attempts = userSms.attempts
366
            sms.responseId = userSms.responseId
367
            sms.responseText = userSms.responseText
368
            session.commit()
369
    return True
370
 
371
def mark_messages_as_submitted_to_smsc(userSmsList):
372
    for userSms in userSmsList:
12902 manish.sha 373
        sms = UserSms.get_by(id=userSms.id)
12691 manish.sha 374
        if sms:
12877 manish.sha 375
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
12691 manish.sha 376
            sms.responseText = userSms.responseText
377
            session.commit()
378
    return True
379
 
380
def mark_messages_as_sent(userSmsList):
381
    for userSms in userSmsList:
12902 manish.sha 382
        sms = UserSms.get_by(id=userSms.id)
12691 manish.sha 383
        if sms:
12877 manish.sha 384
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
12691 manish.sha 385
            sms.responseText = userSms.responseText
12902 manish.sha 386
            sms.status = SmsStatus._VALUES_TO_NAMES[userSms.status]
12691 manish.sha 387
            session.commit()
12902 manish.sha 388
        query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(sms.id) + ')'
12691 manish.sha 389
        session.execute(query, mapper=UserSmsArchive)
390
        if sms:
391
            sms.delete()
392
        session.commit()
393
    return True
394
 
395
def mark_messages_as_retry(userSmsList):
396
    for userSms in userSmsList:
12902 manish.sha 397
        sms = UserSms.get_by(id=userSms.id)
12691 manish.sha 398
        if sms:
12877 manish.sha 399
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
12691 manish.sha 400
            sms.responseText = userSms.responseText
12877 manish.sha 401
            sms.status = SmsStatus._VALUES_TO_NAMES[userSms.status]
12691 manish.sha 402
            session.commit()
12902 manish.sha 403
        query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(sms.id) + ')'
12691 manish.sha 404
        session.execute(query, mapper=UserSmsArchive)
405
        if userSms.attempts < 3:
406
            new_sms_id= save_user_sms_for_sending(userSms.user_id, userSms.mobileNumber, userSms.smsText, userSms.type)
12902 manish.sha 407
            new_sms = UserSms.get_by(id=new_sms_id)
12877 manish.sha 408
            new_sms.status = SmsStatus._VALUES_TO_NAMES[0]
12691 manish.sha 409
            new_sms.attempts = userSms.attempts
12877 manish.sha 410
            new_sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[0] 
12691 manish.sha 411
            session.commit()
412
        if sms:
413
            sms.delete()
414
        session.commit()
415
    return True
12696 amit.gupta 416
 
417
def authorise_dealer(tDealerAuth):
418
    tDealerAuth.isActive = False
419
    if tDealerAuth.username:
420
        dealerAuth = DealerAuth.get_by(username=tDealerAuth.username)
421
        if dealerAuth:
422
            if tDealerAuth.password == dealerAuth.password and dealerAuth.isActive == True:
423
                tDealerAuth.role = dealerAuth.role
424
                if tDealerAuth.lastLocation and dealerAuth.lattitude and dealerAuth.longitude:
425
                    dealerAuth.lattitude, dealerAuth.longitude, tDealerAuth.lastLocation.lattitude,tDealerAuth.lastLocation.longitude = tDealerAuth.lastLocation.lattitude,tDealerAuth.lastLocation.longitude, dealerAuth.lattitude, dealerAuth.longitude
426
                if dealerAuth.lastLoggedIn is not None:
427
                    tDealerAuth.lastLoggedIn = to_java_date(dealerAuth.lastLoggedIn)
428
                else:
429
                    tDealerAuth.lastLoggedIn = None
430
                dealerAuth.lastLoggedIn = datetime.datetime.now()
431
                tDealerAuth.isActive = True
432
                session.commit()
433
 
434
    tDealerAuth.password = None
435
    return tDealerAuth
12691 manish.sha 436
 
13214 kshitij.so 437
def addCampaignNotification(userEmail,campaignType):
438
    try:
439
        exist = Campaigns.get_by(userEmail=userEmail,campaignType=campaignType)
440
        if exist is not None:
441
            return "You are already registered."
442
        else:
443
            c = Campaigns()
444
            c.userEmail = userEmail
445
            c.campaignType = campaignType
446
            session.commit()
13225 kshitij.so 447
            return "Email registered successfully."
13214 kshitij.so 448
    except Exception as e:
449
        print e
450
        return "OOPS!!!Please try again."
12877 manish.sha 451
 
13214 kshitij.so 452
 
766 rajveer 453
def close_session():
454
    if session.is_active:
455
        print "session is active. closing it."
3376 rajveer 456
        session.close()
457
 
458
def is_alive():
459
    try:
460
        return True
461
    except:
462
        return False