Subversion Repositories SmartDukaan

Rev

Rev 13360 | Rev 20242 | 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"
3005 chandransh 58
    return UserEmail.query.all()
1422 varun.gupt 59
 
60
def mark_email_as_sent(email_id):
3005 chandransh 61
    query = 'INSERT INTO ' + str(UserEmailArchive.table) + ' (select * from ' + str(UserEmail.table) + ' where id = ' + str(email_id) + ')'
62
    session.execute(query, mapper=UserEmailArchive)
1422 varun.gupt 63
    email = UserEmail.get_by(id = email_id)
3005 chandransh 64
    if email:
65
        email.delete()
1422 varun.gupt 66
    session.commit()
67
 
353 ashish 68
def sendMail(mail):
69
    if not mail:
70
        raise HelperServiceException(101, "mail not present")
581 rajveer 71
    #msg = MIMEMultipart()
72
    #mail = Mail()
928 rajveer 73
    if mail.sender:
74
        mail.data = "This mail is sent by " + mail.sender + "\n" + mail.data
75
 
581 rajveer 76
    msg = MIMEText(mail.data)
900 rajveer 77
    msg['To'] = ', '.join( mail.to )
928 rajveer 78
    if mail.sender:
79
        msg['From'] = mail.sender
80
    else:    
81
        msg['From'] = "help@saholic.com"
900 rajveer 82
    msg['Subject'] = mail.subject
581 rajveer 83
    #msg.attach(mail.data)
353 ashish 84
 
85
    #handle attachments in mail
86
    if mail.attachments:
87
        for attach in mail.attachments:
88
 
89
            part = MIMEBase('application', 'octet-stream')
90
            part.set_payload(open(attach, 'rb').read())
91
            encoders.encode_base64(part)
92
            part.add_header('Content-Disposition',
93
                    'attachment; filename="%s"' % os.path.basename(attach))
94
            msg.attach(part)
900 rajveer 95
 
353 ashish 96
    for to in mail.to:
873 rajveer 97
        mail.sender = "help@shop2020.in"
98
        mail.password = "5h0p2o2o"
353 ashish 99
        mailServer = smtplib.SMTP("smtp.gmail.com", 587)
100
        mailServer.ehlo()
101
        mailServer.starttls()
102
        mailServer.ehlo()
103
        mailServer.login(mail.sender, mail.password)
104
        mailServer.sendmail(mail.password, to, msg.as_string())
105
        # Should be mailServer.quit(), but that crashes...
106
        mailServer.close() 
107
 
108
def sendText(text):
109
    pass
110
 
111
def addMessage(message):
112
    msg = Message.get_by(message_id=message.id)
113
    if msg:
114
        raise HelperServiceException(101, "Message is already present. Please try updation api instead")
115
    msg = Message();
116
    msg.message_id = message.id
117
    msg.message = message.message
118
    session.commit()
119
 
120
def getMessage(message_id):
121
    msg = Message.get_by(id=message_id)
122
    message = Msg()
123
    message.id = msg.message_id
124
    message.message = msg.message
125
    return message
126
 
127
def updateMessage(id, message):
128
    msg = Message.get_by(message_id=id)
129
    if msg:
130
        msg.message = message
131
        session.commit()
132
    else:
133
        raise HelperServiceException(101, "message could not be found with id %d" %(id))
134
 
135
def getSubstitutedMessage(id, params):
136
    #get the message first
137
    msg = Message.get_by(message_id=id)
138
    if not msg:
139
        raise HelperServiceException(101, "message could not be found with id %d" %(id))
140
    if params:
141
        s = Template(msg.message)
142
        s = s.safe_substitute(params)
143
        return s
144
    else:
145
        return msg.message
494 rajveer 146
 
147
def add_user(username, password, warehouseId):
148
    user = DashboardUser()
149
    user.username = username
150
    user.password = password
151
    user.warehouseId = warehouseId
152
    user.addedOn = datetime.datetime.now()
153
    user.status = 0
154
    try:
155
        session.commit()
156
        return True
157
    except:
158
        raise HelperServiceException(101, "Some error while adding user")
159
        return False
160
 
161
def delete_user(username):
162
    user = DashboardUser.get_by(username=username)
163
    if user is None:
164
        return False
165
    user.delete()
766 rajveer 166
    session.commit()
494 rajveer 167
    return True
168
 
2445 chandransh 169
def authenticate_dashboard_user(username, password):
170
    user = DashboardUser.get_by(username=username, password=password)
494 rajveer 171
    if user is None:
2445 chandransh 172
        raise HelperServiceException(101, "No dashboard user found")
494 rajveer 173
 
2445 chandransh 174
    user.loggedOn = datetime.datetime.now()
175
    session.commit()
176
    return user.to_thrift_object()
177
 
494 rajveer 178
def update_password(username, oldPassword, newPassword):
179
    user = DashboardUser.get_by(username=username)
180
    if user is None:
181
        return False
182
    if user.password == oldPassword:
183
        user.password = newPassword
766 rajveer 184
        session.commit()
494 rajveer 185
        return True
766 rajveer 186
    return False
187
 
1891 ankur.sing 188
def get_reports(role):
189
    query = session.query(Report).join(ReportRoleAuthority)
190
    query = query.filter(ReportRoleAuthority.role == role)
191
    reports = query.all()
192
    return reports
193
 
4806 varun.gupt 194
def share_entities(entityIds, email):
195
    if entityIds:
196
        entityIdsStr = ''
5483 varun.gupt 197
        email_body = get_email_body_for_product_sharing(entityIds)
198
        save_user_email_for_sending(email, '', 'Check out Saholic.com', email_body, '', 'MOBILE_SHARE')
4806 varun.gupt 199
 
200
        for entityId in entityIds:
201
            entityIdsStr += str(entityId)
202
 
203
        entities_to_be_shared = EntitiesShared()
204
        entities_to_be_shared.entityIds = entityIdsStr
205
        entities_to_be_shared.email = email
206
        entities_to_be_shared.isEmailed = False
207
        session.commit()
208
 
5483 varun.gupt 209
def get_email_body_for_product_sharing(entityIds):
210
    catalog_client = CatalogClient().get_client()
211
 
212
    emailBody = '<html><body><p>Check out following products on Saholic:</p><ul>\n'
213
    for entityId in entityIds:
214
        list_items = catalog_client.getItemsByCatalogId(entityId)
215
        url = 'http://www.saholic.com/entity/%s' % (entityId)
216
        item = list_items[0]
217
        name = item.brand + ' '
218
        name += item.modelName + ' ' if item.modelName is not None else ''
219
        name += item.modelNumber if item.modelNumber is not None else ''
220
        emailBody += '<li><a href="%s">%s</a></li>' % (url, name)
221
    emailBody += '</ul></body></html>'
222
    return emailBody
223
 
4806 varun.gupt 224
def save_quick_link(url, text):
225
    quickLink = QuickLink()
226
    quickLink.url = url
227
    quickLink.text = text
228
    session.commit()
229
 
230
def get_quick_links():
231
    return QuickLink.query.all()
232
 
4996 varun.gupt 233
def update_quicklink(id, url, text):
234
    quicklink = QuickLink.get_by(id = id)
235
    quicklink.url = url
236
    quicklink.text = text
237
    session.commit()
238
 
5110 mandeep.dh 239
def update_password_for_agent(agentEmailId, password):
240
    agent = Agent.get_by(emailId = agentEmailId)
241
    agent.password = password
242
    session.commit()
243
 
5055 varun.gupt 244
def get_emails_for_notifications_sent(start_datetime, end_datetime):
245
    query = UserEmailArchive.query.filter(UserEmailArchive.emailType == 'ProductNotification')
246
    query = query.filter(UserEmailArchive.timestamp >= start_datetime)
247
    query = query.filter(UserEmailArchive.timestamp <= end_datetime)
248
    return query.all()
6322 amar.kumar 249
def get_order_confirmation_mail(order_id):
250
    email = UserEmailArchive.get_by(emailType = 'TransactionInfo', source = order_id)
7643 manish.sha 251
    #Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
252
    if email:
253
        return email.body
254
    else:
255
        return ''
256
    #End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
6322 amar.kumar 257
 
7221 kshitij.so 258
def get_order_delivery_mail(order_id):
259
    email = UserEmailArchive.get_by(emailType = 'DeliverySuccess', source = order_id)
7643 manish.sha 260
    #Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
261
    if email:
262
        return email.body
263
    else:
13360 manish.sha 264
        tclient = TransactionClient().get_client()
265
        order = tclient.getOrder(order_id)
266
        if order.logisticsTransactionId:
267
            email = UserEmailArchive.get_by(emailType = 'DeliverySuccess', source = order.logisticsTransactionId)
268
            if email:
269
                return email.body
270
            else:
271
                return ''
7643 manish.sha 272
    #End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013
7221 kshitij.so 273
 
7410 amar.kumar 274
def get_warehouseIds_for_agent(agent_emailId):
275
    agent = Agent.get_by(emailId = agent_emailId)
276
    agent_warehouse_mappings = AgentWarehouseMapping.query.filter(AgentWarehouseMapping.agentId == agent.id).all()
277
    warehouseIds = []
278
    for mapping in agent_warehouse_mappings:
279
        try:
280
            warehouseIds.append(mapping.warehouseId)
281
        except:
282
            raise HelperServiceException(108, "Exception while getting warehouseIds for Agent")
283
    return warehouseIds
284
 
12691 manish.sha 285
def save_user_sms_for_sending(userId, mobileNo, text, type):
286
    userSms = UserSms()
287
    userSms.user_id = userId
288
    userSms.createdTimestamp = datetime.datetime.now()
289
    userSms.mobileNumber = mobileNo
290
    userSms.attempts = 0
291
    userSms.smsText = text
12877 manish.sha 292
    userSms.type = SmsType._VALUES_TO_NAMES[type]
293
    userSms.status = SmsStatus._VALUES_TO_NAMES[0]
294
    userSms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[0]
12691 manish.sha 295
    session.commit()
296
    return userSms.id
297
 
298
def get_sms_to_be_sent():
299
    print "get_emails_to_be_sent"
12882 manish.sha 300
    return UserSms.query.filter(UserSms.deliveryStatus== SmsDeliveryStatus._VALUES_TO_NAMES[SmsDeliveryStatus.NOT_SENT]).all()
12691 manish.sha 301
 
302
def mark_sms_as_sent(smsId, status, responseId, responseText):
12902 manish.sha 303
    sms = UserSms.get_by(id=smsId)
12691 manish.sha 304
    if sms:
305
        sms.attempts = sms.attempts+1
12877 manish.sha 306
        sms.status = SmsStatus._VALUES_TO_NAMES[status]
12691 manish.sha 307
        sms.responseId = responseId
308
        sms.responseText = responseText
309
        session.commit()
310
    query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(smsId) + ')'
311
    session.execute(query, mapper=UserSmsArchive)
312
    if sms:
313
        sms.delete()
314
    session.commit()
315
 
316
def mark_sms_as_retry(smsId, status, responseId, responseText):
12902 manish.sha 317
    sms = UserSms.get_by(id=smsId)
12691 manish.sha 318
    if sms:
319
        if sms.attempts<3:
320
            sms.attempts = sms.attempts+1
12877 manish.sha 321
            sms.status = SmsStatus._VALUES_TO_NAMES[status]
12691 manish.sha 322
            sms.responseId = responseId
323
            sms.responseText = responseText
324
            session.commit()
325
            return True
326
        else:
327
            return False
328
    else:
329
        return False
330
 
331
def add_user_sms_info(userSms_Info):
332
    userSmsInfo = UserSmsInfo()
333
    userSmsInfo.userId = userSms_Info.userId
334
    userSmsInfo.mobileNo = userSms_Info.mobileNo
335
    userSmsInfo.createdTimestamp = to_py_date(userSms_Info.createdTimestamp)
336
    userSmsInfo.updateTimestamp = to_py_date(userSms_Info.updateTimestamp)
337
    userSmsInfo.dailyCount = 0
338
    userSmsInfo.weeklyCount = 0
339
    userSmsInfo.dndStatus = False
340
    userSmsInfo.smsSubscribed = True
341
    session.commit()
342
 
343
def update_user_sms_info(userSms_Info):
344
    userSmsInfo = UserSmsInfo.query.filter(UserSmsInfo.userId == userSms_Info.userId).first()
345
    if userSmsInfo:
346
        userSmsInfo.mobileNo = userSms_Info.mobileNo
347
        userSmsInfo.dndStatus = userSms_Info.dndStatus
348
        userSmsInfo.smsSubscribed = userSms_Info.smsSubscribed
349
        userSmsInfo.dailyCount = userSms_Info.dailyCount
12946 manish.sha 350
        userSmsInfo.weeklyCount = userSms_Info.weeklyCount
12691 manish.sha 351
        userSmsInfo.updateTimestamp = datetime.datetime.now()
352
        session.commit()
353
        return True
354
    else:
355
        return False
356
 
357
def get_user_sms_info(userId):
358
    return UserSmsInfo.query.filter(UserSmsInfo.userId == userId).first()
359
 
360
def get_all_users_sms_info(dndStatus, smsSubscribed):
361
    print 'get all users sms infos'
362
    return UserSmsInfo.query.filter(UserSmsInfo.dndStatus == dndStatus).filter(UserSmsInfo.smsSubscribed == smsSubscribed).all()
363
 
364
def list_sms_to_get_delivery_info():
365
    print 'get all message waiting for delivery status'
12882 manish.sha 366
    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 367
 
368
def mark_messages_as_sent_to_operator(userSmsList):
369
    for userSms in userSmsList:
12902 manish.sha 370
        sms = UserSms.get_by(id=userSms.id)
12691 manish.sha 371
        if sms:
12877 manish.sha 372
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
12691 manish.sha 373
            sms.attempts = userSms.attempts
374
            sms.responseId = userSms.responseId
375
            sms.responseText = userSms.responseText
376
            session.commit()
377
    return True
378
 
379
def mark_messages_as_submitted_to_smsc(userSmsList):
380
    for userSms in userSmsList:
12902 manish.sha 381
        sms = UserSms.get_by(id=userSms.id)
12691 manish.sha 382
        if sms:
12877 manish.sha 383
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
12691 manish.sha 384
            sms.responseText = userSms.responseText
385
            session.commit()
13543 manish.sha 386
        query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(sms.id) + ')'
387
        session.execute(query, mapper=UserSmsArchive)
388
        if sms:
389
            sms.delete()
390
        session.commit()
12691 manish.sha 391
    return True
392
 
393
def mark_messages_as_sent(userSmsList):
394
    for userSms in userSmsList:
12902 manish.sha 395
        sms = UserSms.get_by(id=userSms.id)
12691 manish.sha 396
        if sms:
12877 manish.sha 397
            sms.deliveryStatus = SmsDeliveryStatus._VALUES_TO_NAMES[userSms.deliveryStatus]
12691 manish.sha 398
            sms.responseText = userSms.responseText
12902 manish.sha 399
            sms.status = SmsStatus._VALUES_TO_NAMES[userSms.status]
12691 manish.sha 400
            session.commit()
12902 manish.sha 401
        query = 'INSERT INTO ' + str(UserSmsArchive.table) + ' (select * from ' + str(UserSms.table) + ' where id = ' + str(sms.id) + ')'
12691 manish.sha 402
        session.execute(query, mapper=UserSmsArchive)
403
        if sms:
404
            sms.delete()
405
        session.commit()
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