Subversion Repositories SmartDukaan

Rev

Rev 13543 | Rev 20244 | 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
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"
20242 amit.gupta 58
    return UserEmail.query.filter_by(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)
191
    query = query.filter(ReportRoleAuthority.role == role)
192
    reports = query.all()
193
    return reports
194
 
4806 varun.gupt 195
def share_entities(entityIds, email):
196
    if entityIds:
197
        entityIdsStr = ''
5483 varun.gupt 198
        email_body = get_email_body_for_product_sharing(entityIds)
199
        save_user_email_for_sending(email, '', 'Check out Saholic.com', email_body, '', 'MOBILE_SHARE')
4806 varun.gupt 200
 
201
        for entityId in entityIds:
202
            entityIdsStr += str(entityId)
203
 
204
        entities_to_be_shared = EntitiesShared()
205
        entities_to_be_shared.entityIds = entityIdsStr
206
        entities_to_be_shared.email = email
207
        entities_to_be_shared.isEmailed = False
208
        session.commit()
209
 
5483 varun.gupt 210
def get_email_body_for_product_sharing(entityIds):
211
    catalog_client = CatalogClient().get_client()
212
 
213
    emailBody = '<html><body><p>Check out following products on Saholic:</p><ul>\n'
214
    for entityId in entityIds:
215
        list_items = catalog_client.getItemsByCatalogId(entityId)
216
        url = 'http://www.saholic.com/entity/%s' % (entityId)
217
        item = list_items[0]
218
        name = item.brand + ' '
219
        name += item.modelName + ' ' if item.modelName is not None else ''
220
        name += item.modelNumber if item.modelNumber is not None else ''
221
        emailBody += '<li><a href="%s">%s</a></li>' % (url, name)
222
    emailBody += '</ul></body></html>'
223
    return emailBody
224
 
4806 varun.gupt 225
def save_quick_link(url, text):
226
    quickLink = QuickLink()
227
    quickLink.url = url
228
    quickLink.text = text
229
    session.commit()
230
 
231
def get_quick_links():
232
    return QuickLink.query.all()
233
 
4996 varun.gupt 234
def update_quicklink(id, url, text):
235
    quicklink = QuickLink.get_by(id = id)
236
    quicklink.url = url
237
    quicklink.text = text
238
    session.commit()
239
 
5110 mandeep.dh 240
def update_password_for_agent(agentEmailId, password):
241
    agent = Agent.get_by(emailId = agentEmailId)
242
    agent.password = password
243
    session.commit()
244
 
5055 varun.gupt 245
def get_emails_for_notifications_sent(start_datetime, end_datetime):
246
    query = UserEmailArchive.query.filter(UserEmailArchive.emailType == 'ProductNotification')
247
    query = query.filter(UserEmailArchive.timestamp >= start_datetime)
248
    query = query.filter(UserEmailArchive.timestamp <= end_datetime)
249
    return query.all()
6322 amar.kumar 250
def get_order_confirmation_mail(order_id):
251
    email = UserEmailArchive.get_by(emailType = 'TransactionInfo', source = order_id)
7643 manish.sha 252
    #Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
253
    if email:
254
        return email.body
255
    else:
256
        return ''
257
    #End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
6322 amar.kumar 258
 
7221 kshitij.so 259
def get_order_delivery_mail(order_id):
260
    email = UserEmailArchive.get_by(emailType = 'DeliverySuccess', source = order_id)
7643 manish.sha 261
    #Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
262
    if email:
263
        return email.body
264
    else:
13360 manish.sha 265
        tclient = TransactionClient().get_client()
266
        order = tclient.getOrder(order_id)
267
        if order.logisticsTransactionId:
268
            email = UserEmailArchive.get_by(emailType = 'DeliverySuccess', source = order.logisticsTransactionId)
269
            if email:
270
                return email.body
271
            else:
272
                return ''
7643 manish.sha 273
    #End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
7221 kshitij.so 274
 
7410 amar.kumar 275
def get_warehouseIds_for_agent(agent_emailId):
276
    agent = Agent.get_by(emailId = agent_emailId)
277
    agent_warehouse_mappings = AgentWarehouseMapping.query.filter(AgentWarehouseMapping.agentId == agent.id).all()
278
    warehouseIds = []
279
    for mapping in agent_warehouse_mappings:
280
        try:
281
            warehouseIds.append(mapping.warehouseId)
282
        except:
283
            raise HelperServiceException(108, "Exception while getting warehouseIds for Agent")
284
    return warehouseIds
285
 
12691 manish.sha 286
def save_user_sms_for_sending(userId, mobileNo, text, type):
287
    userSms = UserSms()
288
    userSms.user_id = userId
289
    userSms.createdTimestamp = datetime.datetime.now()
290
    userSms.mobileNumber = mobileNo
291
    userSms.attempts = 0
292
    userSms.smsText = text
12877 manish.sha 293
    userSms.type = SmsType._VALUES_TO_NAMES[type]
294
    userSms.status = SmsStatus._VALUES_TO_NAMES[0]
295
    userSms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[0]
12691 manish.sha 296
    session.commit()
297
    return userSms.id
298
 
299
def get_sms_to_be_sent():
20242 amit.gupta 300
    print "get_sms_to_be_sent"
12882 manish.sha 301
    return UserSms.query.filter(UserSms.deliveryStatus== SmsDeliveryStatus._VALUES_TO_NAMES[SmsDeliveryStatus.NOT_SENT]).all()
12691 manish.sha 302
 
303
def mark_sms_as_sent(smsId, status, responseId, responseText):
12902 manish.sha 304
    sms = UserSms.get_by(id=smsId)
12691 manish.sha 305
    if sms:
306
        sms.attempts = sms.attempts+1
12877 manish.sha 307
        sms.status = SmsStatus._VALUES_TO_NAMES[status]
12691 manish.sha 308
        sms.responseId = responseId
309
        sms.responseText = responseText
310
        session.commit()
311
    query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(smsId) + ')'
312
    session.execute(query, mapper=UserSmsArchive)
313
    if sms:
314
        sms.delete()
315
    session.commit()
316
 
317
def mark_sms_as_retry(smsId, status, responseId, responseText):
12902 manish.sha 318
    sms = UserSms.get_by(id=smsId)
12691 manish.sha 319
    if sms:
320
        if sms.attempts<3:
321
            sms.attempts = sms.attempts+1
12877 manish.sha 322
            sms.status = SmsStatus._VALUES_TO_NAMES[status]
12691 manish.sha 323
            sms.responseId = responseId
324
            sms.responseText = responseText
325
            session.commit()
326
            return True
327
        else:
328
            return False
329
    else:
330
        return False
331
 
332
def add_user_sms_info(userSms_Info):
333
    userSmsInfo = UserSmsInfo()
334
    userSmsInfo.userId = userSms_Info.userId
335
    userSmsInfo.mobileNo = userSms_Info.mobileNo
336
    userSmsInfo.createdTimestamp = to_py_date(userSms_Info.createdTimestamp)
337
    userSmsInfo.updateTimestamp = to_py_date(userSms_Info.updateTimestamp)
338
    userSmsInfo.dailyCount = 0
339
    userSmsInfo.weeklyCount = 0
340
    userSmsInfo.dndStatus = False
341
    userSmsInfo.smsSubscribed = True
342
    session.commit()
343
 
344
def update_user_sms_info(userSms_Info):
345
    userSmsInfo = UserSmsInfo.query.filter(UserSmsInfo.userId == userSms_Info.userId).first()
346
    if userSmsInfo:
347
        userSmsInfo.mobileNo = userSms_Info.mobileNo
348
        userSmsInfo.dndStatus = userSms_Info.dndStatus
349
        userSmsInfo.smsSubscribed = userSms_Info.smsSubscribed
350
        userSmsInfo.dailyCount = userSms_Info.dailyCount
12946 manish.sha 351
        userSmsInfo.weeklyCount = userSms_Info.weeklyCount
12691 manish.sha 352
        userSmsInfo.updateTimestamp = datetime.datetime.now()
353
        session.commit()
354
        return True
355
    else:
356
        return False
357
 
358
def get_user_sms_info(userId):
359
    return UserSmsInfo.query.filter(UserSmsInfo.userId == userId).first()
360
 
361
def get_all_users_sms_info(dndStatus, smsSubscribed):
362
    print 'get all users sms infos'
363
    return UserSmsInfo.query.filter(UserSmsInfo.dndStatus == dndStatus).filter(UserSmsInfo.smsSubscribed == smsSubscribed).all()
364
 
365
def list_sms_to_get_delivery_info():
366
    print 'get all message waiting for delivery status'
12882 manish.sha 367
    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 368
 
369
def mark_messages_as_sent_to_operator(userSmsList):
370
    for userSms in userSmsList:
12902 manish.sha 371
        sms = UserSms.get_by(id=userSms.id)
12691 manish.sha 372
        if sms:
12877 manish.sha 373
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
12691 manish.sha 374
            sms.attempts = userSms.attempts
375
            sms.responseId = userSms.responseId
376
            sms.responseText = userSms.responseText
377
            session.commit()
378
    return True
379
 
380
def mark_messages_as_submitted_to_smsc(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
386
            session.commit()
13543 manish.sha 387
        query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(sms.id) + ')'
388
        session.execute(query, mapper=UserSmsArchive)
389
        if sms:
390
            sms.delete()
391
        session.commit()
12691 manish.sha 392
    return True
393
 
394
def mark_messages_as_sent(userSmsList):
20242 amit.gupta 395
    UserSms.query.filter(UserSms.status==SmsStatus._VALUES_TO_NAMES[SmsStatus.DELIVERED]).delete()
12691 manish.sha 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
12902 manish.sha 401
            sms.status = SmsStatus._VALUES_TO_NAMES[userSms.status]
20242 amit.gupta 402
            query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(sms.id) + ')'
403
            session.execute(query, mapper=UserSmsArchive)
404
            sms.status = SmsStatus._VALUES_TO_NAMES[SmsStatus.DELIVERED]
405
    session.commit()
12691 manish.sha 406
    return True
407
 
408
def mark_messages_as_retry(userSmsList):
409
    for userSms in userSmsList:
12902 manish.sha 410
        sms = UserSms.get_by(id=userSms.id)
12691 manish.sha 411
        if sms:
12877 manish.sha 412
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
12691 manish.sha 413
            sms.responseText = userSms.responseText
12877 manish.sha 414
            sms.status = SmsStatus._VALUES_TO_NAMES[userSms.status]
12691 manish.sha 415
            session.commit()
12902 manish.sha 416
        query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(sms.id) + ')'
12691 manish.sha 417
        session.execute(query, mapper=UserSmsArchive)
418
        if userSms.attempts < 3:
419
            new_sms_id= save_user_sms_for_sending(userSms.user_id, userSms.mobileNumber, userSms.smsText, userSms.type)
12902 manish.sha 420
            new_sms = UserSms.get_by(id=new_sms_id)
12877 manish.sha 421
            new_sms.status = SmsStatus._VALUES_TO_NAMES[0]
12691 manish.sha 422
            new_sms.attempts = userSms.attempts
12877 manish.sha 423
            new_sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[0] 
12691 manish.sha 424
            session.commit()
425
        if sms:
426
            sms.delete()
427
        session.commit()
428
    return True
12696 amit.gupta 429
 
430
def authorise_dealer(tDealerAuth):
431
    tDealerAuth.isActive = False
432
    if tDealerAuth.username:
433
        dealerAuth = DealerAuth.get_by(username=tDealerAuth.username)
434
        if dealerAuth:
435
            if tDealerAuth.password == dealerAuth.password and dealerAuth.isActive == True:
436
                tDealerAuth.role = dealerAuth.role
437
                if tDealerAuth.lastLocation and dealerAuth.lattitude and dealerAuth.longitude:
438
                    dealerAuth.lattitude, dealerAuth.longitude, tDealerAuth.lastLocation.lattitude,tDealerAuth.lastLocation.longitude = tDealerAuth.lastLocation.lattitude,tDealerAuth.lastLocation.longitude, dealerAuth.lattitude, dealerAuth.longitude
439
                if dealerAuth.lastLoggedIn is not None:
440
                    tDealerAuth.lastLoggedIn = to_java_date(dealerAuth.lastLoggedIn)
441
                else:
442
                    tDealerAuth.lastLoggedIn = None
443
                dealerAuth.lastLoggedIn = datetime.datetime.now()
444
                tDealerAuth.isActive = True
445
                session.commit()
446
 
447
    tDealerAuth.password = None
448
    return tDealerAuth
12691 manish.sha 449
 
13214 kshitij.so 450
def addCampaignNotification(userEmail,campaignType):
451
    try:
452
        exist = Campaigns.get_by(userEmail=userEmail,campaignType=campaignType)
453
        if exist is not None:
454
            return "You are already registered."
455
        else:
456
            c = Campaigns()
457
            c.userEmail = userEmail
458
            c.campaignType = campaignType
459
            session.commit()
13225 kshitij.so 460
            return "Email registered successfully."
13214 kshitij.so 461
    except Exception as e:
462
        print e
463
        return "OOPS!!!Please try again."
12877 manish.sha 464
 
13214 kshitij.so 465
 
766 rajveer 466
def close_session():
467
    if session.is_active:
468
        print "session is active. closing it."
3376 rajveer 469
        session.close()
470
 
471
def is_alive():
472
    try:
473
        return True
474
    except:
475
        return False