Subversion Repositories SmartDukaan

Rev

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