Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
15400 amit.gupta 1
'''
2
Created on May 25, 2015
3
 
4
@author: amit
5
'''
6
 
7
from datetime import datetime, timedelta, date
15480 amit.gupta 8
from email import encoders
9
from email.mime.base import MIMEBase
10
from email.mime.multipart import MIMEMultipart
11
from email.mime.text import MIMEText
15400 amit.gupta 12
import MySQLdb
13
import copy
15480 amit.gupta 14
import smtplib
15400 amit.gupta 15
import xlwt
16
 
15480 amit.gupta 17
SENDER = "adwords@shop2020.in"
18
PASSWORD = "adwords_shop2020"
19
SUBJECT = "CRM Outbound Report for " + str(date.today() - timedelta(days=1))
20
SMTP_SERVER = "smtp.gmail.com"
21
SMTP_PORT = 587  
15400 amit.gupta 22
 
23
date_format = xlwt.XFStyle()
24
date_format.num_format_str = 'dd/mm/yyyy'
25
 
26
datetime_format = xlwt.XFStyle()
27
datetime_format.num_format_str = 'dd/mm/yyyy HH:MM AM/PM'
28
 
29
default_format = xlwt.XFStyle()
30
 
31
boldStyle = xlwt.XFStyle()
32
f = xlwt.Font()
33
f.bold = True
34
boldStyle.font = f
35
 
36
date_format.font = f
37
ALLIED = 4
38
NOT_RETAILER =7
39
RETAILER_NOT_INTERESTED=3
40
NOT_CONTACTABLE = 6
41
CALL_LATER=5
42
ALREADY_USER = 8
43
TOTAL = 9
44
TOTAL_AGENTS = 10
45
TOTAL_LOGIN_TIME = 11
46
TOTAL_CALL_DURATION = 12
47
CONVERTED=1
48
AWAITING_CONVERSION =2
49
LINK_SENT =2
50
 
51
 
52
 
53
 
54
 
55
disposition_map={
56
                    'call_later':CALL_LATER,
57
                    'ringing_no_answer':NOT_CONTACTABLE,
58
                    'not_reachable':NOT_CONTACTABLE,
59
                    'switch_off':NOT_CONTACTABLE,
60
                    'invalid_no':NOT_CONTACTABLE,
61
                    'wrong_no':NOT_CONTACTABLE,
62
                    'hang_up':NOT_CONTACTABLE,
63
                    'retailer_not_interested':RETAILER_NOT_INTERESTED,
64
                    'alreadyuser':ALREADY_USER,
65
                    'verified_link_sent':LINK_SENT,
66
                    'converted':CONVERTED,
67
                    'accessory_retailer':ALLIED,
68
                    'service_center_retailer':ALLIED,
69
                    'not_retailer':NOT_RETAILER,
70
                    'recharge_retailer':ALLIED,
71
                    None:TOTAL,
72
                    'agent_count':TOTAL_AGENTS,
73
                    'login_time' : TOTAL_LOGIN_TIME,
74
                    'call_duration': TOTAL_CALL_DURATION
75
                }
76
STATUS_MAP = {
77
              CONVERTED:0,
78
              AWAITING_CONVERSION:0,
79
              RETAILER_NOT_INTERESTED:0,
80
              NOT_CONTACTABLE:0,
81
              ALLIED:0,
82
              CALL_LATER:0,
83
              NOT_CONTACTABLE:0,
84
              NOT_RETAILER:0,
85
              ALREADY_USER:0,
86
              TOTAL:0,
87
              TOTAL_AGENTS:0,
88
              TOTAL_LOGIN_TIME:0,
89
              TOTAL_CALL_DURATION:0
90
              }
91
PREVIOUS_DATE = datetime.now() -timedelta(days=1)
92
DATE_MAP = {PREVIOUS_DATE.date():1, (PREVIOUS_DATE - timedelta(days=1)).date():2, (PREVIOUS_DATE - timedelta(days=2)).date():3, (PREVIOUS_DATE - timedelta(days=3)).date():4, 'MTD':5, 'Total Till Date':6}
93
 
94
def getLast4daysQuery(type='fresh'):
95
    fourDaysBefore = PREVIOUS_DATE - timedelta(days=3)
96
    fourDaysBefore = fourDaysBefore.date()
97
    curDate = (PREVIOUS_DATE + timedelta(days=1)).date()
98
    return '''select date(created), call_disposition, count(1) from (
99
    (select id, created, call_disposition from (select * from callhistory where created between '%s' and '%s' and call_type ='%s' order by created desc) as a group by retailer_id)
100
    union 
101
    (select id, created, 'converted' from (select h.*  from retailers r join callhistory h on h.retailer_id=r.id where r.status in ('onboarded', 'onboarding') and h.call_disposition='verified_link_sent' and h.call_type='%s' and h.created between '%s' and '%s' order by h.created desc) as b1 group by retailer_id) 
15401 amit.gupta 102
    )a group by date(created), call_disposition with rollup'''%(fourDaysBefore,curDate,type,type,fourDaysBefore,curDate )
15400 amit.gupta 103
        #union select date(created) dc, agent_i
104
 
105
def getMDTQuery(type='fresh'):
106
    return '''select a.dc, a.call_disposition, count(1) from
107
            (select 'MTD' as dc, call_disposition from (select * from callhistory where month(created)=%s and call_type ='%s' order by created desc) as a group by retailer_id
108
    union all     select 'Total Till Date' dc, call_disposition from (select * from callhistory where call_type ='%s' order by created desc) as a group by retailer_id
109
    union all    select 'MTD' dc, 'converted'  call_disposition  from(select h.* from retailers r join callhistory h on h.retailer_id=r.id where r.status in ('onboarded', 'onboarding') and h.call_disposition='verified_link_sent' and h.call_type='%s' and month(h.created) = %s order by h.created desc) as b1 group by retailer_id
110
    union all    select 'Total Till Date' dc, 'converted'  call_disposition  from(select h.* from retailers r join callhistory h on h.retailer_id=r.id where r.status in ('onboarded', 'onboarding') and h.call_disposition='verified_link_sent' and h.call_type='%s' order by h.created desc) as b1 group by retailer_id)
111
    a group by a.dc, a.call_disposition with rollup
112
    '''%(PREVIOUS_DATE.month, type, type, type, PREVIOUS_DATE.month, type)
113
 
114
def getConvertedMTDQuery():
115
    pass
116
 
117
 
118
def getTillDateQuery():
119
    pass
120
 
121
 
122
def setWorksheetTemplate(freshSheet, followupSheet):
123
    freshSheet.write(1, 0, 'Converted', boldStyle)
124
    freshSheet.write(2, 0, 'Link sent yet to be converted', boldStyle)
125
    freshSheet.write(3, 0, 'Retailer not interested', boldStyle)
126
    freshSheet.write(4, 0, 'Allied category retailer', boldStyle)
127
    freshSheet.write(5, 0, 'Call Later', boldStyle)
128
    freshSheet.write(6, 0, 'Not contactable', boldStyle)
129
    freshSheet.write(7, 0, 'Not a retailer', boldStyle)
130
    freshSheet.write(8, 0, 'AlreadyUser', boldStyle)
131
    freshSheet.write(9, 0, 'Total Attempts (Total of above)', boldStyle)
132
    freshSheet.write(10, 0, 'Total Agents Logged in', boldStyle)
133
    freshSheet.write(11, 0, 'Total Login time (Hours)', boldStyle)
134
    freshSheet.write(12, 0, 'Total Call Duration (Hours)', boldStyle)
135
 
136
    followupSheet.write(1, 0, 'Conversion After Followup', boldStyle)
137
    followupSheet.write(2, 0, 'Link sent again', boldStyle)
138
    followupSheet.write(3, 0, 'Retailer not interested', boldStyle)
139
    followupSheet.write(4, 0, 'Allied category retailer', boldStyle)
140
    followupSheet.write(5, 0, 'Call Later', boldStyle)
141
    followupSheet.write(6, 0, 'Not contactable', boldStyle)
142
    followupSheet.write(7, 0, 'Not a retailer', boldStyle)
143
    followupSheet.write(8, 0, 'AlreadyUser', boldStyle)
144
    followupSheet.write(9, 0, 'Total Attempts (Total of above)', boldStyle)
145
    followupSheet.write(10, 0, 'Total Agents Logged in', boldStyle)
146
    followupSheet.write(11, 0, 'Total Login time (Hours)', boldStyle)
147
    followupSheet.write(12, 0, 'Total Call Duration (Hours)', boldStyle)
148
 
149
 
150
 
151
def getDbConnection():
152
    return MySQLdb.connect('localhost', 'root', 'shop2020', 'dtr')
153
 
154
 
155
    conn = getDbConnection()
156
 
157
def populateFreshSheet(freshSheet):
158
    query = getLast4daysQuery()
159
    print query
160
    conn = getDbConnection()
161
    cursor = conn.cursor()
162
    cursor.execute(query)
163
    result = cursor.fetchall()
164
    datewiseMap = {}
165
    for x in [0,1,2,3,'MTD', 'Total Till Date' ]:
166
        if type(x) is int:
167
            datetime1 = PREVIOUS_DATE - timedelta(days=x)
168
            datewiseMap[datetime1.date()] = copy.deepcopy(STATUS_MAP)
169
        else:
170
            datewiseMap[x] = copy.deepcopy(STATUS_MAP)
171
    print datewiseMap
172
    for row in result:
173
        if row[0] is None:
174
            continue
175
        print row[0]
176
        statuswisemap = datewiseMap.get(row[0])
177
        disposition_tag = disposition_map.get(row[1])
178
        if statuswisemap.get(disposition_tag) is None:
179
            statuswisemap[disposition_tag] = 0
180
        print row[2]
181
        statuswisemap[disposition_tag] += row[2]
182
 
183
    query = getMDTQuery()
184
    cursor.execute(query)
185
    result = cursor.fetchall()
186
    for row in result:
187
        if row[0] is None:
188
            continue
189
        print row[0]
190
        statuswisemap = datewiseMap.get(row[0])
191
        disposition_tag = disposition_map.get(row[1])
192
        if statuswisemap.get(disposition_tag) is None:
193
            statuswisemap[disposition_tag] = 0
194
        print row[2]
195
        statuswisemap[disposition_tag] += row[2]
196
 
197
 
198
 
199
    q= '''
200
    select * from (select date(created) d, count(distinct agent_id), sum(TIMESTAMPDIFF(SECOND, loginTime,logoutTime)) from  agentlogintimings   where role = 'fresh' group by date(created) with rollup)d1  order by -d limit 6 
201
    '''
202
    conn = getDbConnection()
203
    cursor = conn.cursor()
204
    cursor.execute(q)
205
    result = cursor.fetchall()
206
    for row in result:
207
        if row[0] is None:
208
            statuswisemap = datewiseMap.get('Total Till Date')
209
        else:
210
            statuswisemap = datewiseMap.get(row[0])
211
 
212
        print "------------", row[0], statuswisemap
213
        if statuswisemap is None:
214
            continue
215
        statuswisemap[disposition_map.get('agent_count')] = row[1]
216
        statuswisemap[disposition_map.get('login_time')] = round(row[2]/3600,2)
217
 
218
    q= '''
219
    select 'MTD', count(distinct agent_id),  sum(TIMESTAMPDIFF(SECOND, loginTime,logoutTime)) from agentlogintimings where role = 'fresh' and month(created)=month(DATE_ADD(now(), interval - 1 day))
220
    '''
221
    conn = getDbConnection()
222
    cursor = conn.cursor()
223
    cursor.execute(q)
224
    result = cursor.fetchall()
225
    for row in result:
226
        if row[0] is None:
227
            statuswisemap = datewiseMap.get('Total Till Date')
228
        else:
229
            statuswisemap = datewiseMap.get(row[0])
230
 
231
        print "------------", row[0], statuswisemap
232
        if statuswisemap is None:
233
            continue
234
        statuswisemap[disposition_map.get('agent_count')] = row[1]
235
        statuswisemap[disposition_map.get('login_time')] = round(row[2]/3600,2)
236
 
237
 
238
    q ='''
239
         select * from (select date(created)d, sum(duration_sec) from callhistory  where duration_sec >0 and call_type='fresh' group by date(created) with rollup) a order by -d limit 5
240
         '''
241
    conn = getDbConnection()
242
    cursor = conn.cursor()
243
    cursor.execute(q)
244
    result = cursor.fetchall()
245
    for row in result:
246
        if row[0] is None:
247
            statuswisemap = datewiseMap.get('Total Till Date')
248
        else:
249
            statuswisemap = datewiseMap.get(row[0])
250
 
251
        print "------------", row[0], statuswisemap
252
        if statuswisemap is None:
253
            continue
254
        statuswisemap[disposition_map.get('call_duration')] = round(row[1]/3600,2)
255
 
256
    q ='''
257
         select 'MTD', sum(duration_sec) from callhistory  where duration_sec >0 and call_type='fresh' and month(date_add(now(), interval -1 day)) = month(created) group by month(created) 
258
         '''
259
    conn = getDbConnection()
260
    cursor = conn.cursor()
261
    cursor.execute(q)
262
    result = cursor.fetchall()
263
    for row in result:
264
        if row[0] is None:
265
            statuswisemap = datewiseMap.get('Total Till Date')
266
        else:
267
            statuswisemap = datewiseMap.get(row[0])
268
 
269
        print "------------", row[0], statuswisemap
270
        if statuswisemap is None:
271
            continue
272
        statuswisemap[disposition_map.get('call_duration')] = round(row[1]/3600,2)
273
 
274
    for disdate, statusmap in datewiseMap.iteritems():
275
        freshSheet.write(0, DATE_MAP.get(disdate), disdate, date_format if type(disdate) is date else boldStyle)
276
        for index, statuscount in statusmap.iteritems():
277
            if index in [TOTAL,LINK_SENT]:
278
                statuscount -= statusmap.get(CONVERTED)
279
 
280
            print index, disdate, statuscount    
281
            freshSheet.write(index, DATE_MAP.get(disdate),statuscount)
282
 
283
def populateFollowupSheet(followupSheet):
284
    query = getLast4daysQuery('followup')
285
    print query
286
    conn = getDbConnection()
287
    cursor = conn.cursor()
288
    cursor.execute(query)
289
    result = cursor.fetchall()
290
    datewiseMap = {}
291
    for x in [0,1,2,3,'MTD', 'Total Till Date' ]:
292
        if type(x) is int:
293
            datetime1 = PREVIOUS_DATE - timedelta(days=x)
294
            datewiseMap[datetime1.date()] = copy.deepcopy(STATUS_MAP)
295
        else:
296
            datewiseMap[x] = copy.deepcopy(STATUS_MAP)
297
    print datewiseMap
298
    for row in result:
299
        if row[0] is None:
300
            continue
301
        print row[0]
302
        statuswisemap = datewiseMap.get(row[0])
303
        disposition_tag = disposition_map.get(row[1])
304
        print "disposition_tag",disposition_tag
305
        if statuswisemap.get(disposition_tag) is None:
306
            statuswisemap[disposition_tag] = 0
307
        print row[2]
308
        statuswisemap[disposition_tag] += row[2]
309
 
310
    query = getMDTQuery('followup')
311
    cursor.execute(query)
312
    result = cursor.fetchall()
313
    for row in result:
314
        if row[0] is None:
315
            continue
316
        print row[0]
317
        statuswisemap = datewiseMap.get(row[0])
318
        disposition_tag = disposition_map.get(row[1])
319
        print "disposition_tag",disposition_tag
320
        if statuswisemap.get(disposition_tag) is None:
321
            statuswisemap[disposition_tag] = 0
322
        print row[2]
323
        statuswisemap[disposition_tag] += row[2]
324
 
325
 
326
        q= '''
327
    select * from (select date(created) d, count(distinct agent_id), sum(TIMESTAMPDIFF(SECOND, loginTime,logoutTime)) from  agentlogintimings   where role = 'followup' group by date(created) with rollup)d1  order by -d limit 6 
328
    '''
329
    conn = getDbConnection()
330
    cursor = conn.cursor()
331
    cursor.execute(q)
332
    result = cursor.fetchall()
333
    for row in result:
334
        if row[0] is None:
335
            statuswisemap = datewiseMap.get('Total Till Date')
336
        else:
337
            statuswisemap = datewiseMap.get(row[0])
338
 
339
        print "------------", row[0], statuswisemap
340
        if statuswisemap is None:
341
            continue
342
        statuswisemap[disposition_map.get('agent_count')] = row[1]
343
        statuswisemap[disposition_map.get('login_time')] = round(row[2]/3600,2)
344
 
345
    q= '''
346
    select 'MTD', count(distinct agent_id),  sum(TIMESTAMPDIFF(SECOND, loginTime,logoutTime)) from agentlogintimings where role = 'followup' and month(created)=month(DATE_ADD(now(), interval - 1 day))
347
    '''
348
    conn = getDbConnection()
349
    cursor = conn.cursor()
350
    cursor.execute(q)
351
    result = cursor.fetchall()
352
    for row in result:
353
        if row[0] is None:
354
            statuswisemap = datewiseMap.get('Total Till Date')
355
        else:
356
            statuswisemap = datewiseMap.get(row[0])
357
 
358
        print "------------", row[0], statuswisemap
359
        if statuswisemap is None:
360
            continue
361
        statuswisemap[disposition_map.get('agent_count')] = row[1]
362
        statuswisemap[disposition_map.get('login_time')] = round(row[2]/3600,2)
363
 
364
 
365
    q ='''
366
         select * from (select date(created)d, sum(duration_sec) from callhistory  where duration_sec >0 and call_type='followup' group by date(created) with rollup) a order by -d limit 5
367
         '''
368
    conn = getDbConnection()
369
    cursor = conn.cursor()
370
    cursor.execute(q)
371
    result = cursor.fetchall()
372
    for row in result:
373
        if row[0] is None:
374
            statuswisemap = datewiseMap.get('Total Till Date')
375
        else:
376
            statuswisemap = datewiseMap.get(row[0])
377
 
378
        print "------------", row[0], statuswisemap
379
        if statuswisemap is None:
380
            continue
381
        statuswisemap[disposition_map.get('call_duration')] = round(row[1]/3600,2)
382
 
383
    q ='''
384
         select 'MTD', sum(duration_sec) from callhistory  where duration_sec >0 and call_type='followup' and month(date_add(now(), interval -1 day)) = month(created) group by month(created) 
385
         '''
386
    conn = getDbConnection()
387
    cursor = conn.cursor()
388
    cursor.execute(q)
389
    result = cursor.fetchall()
390
    for row in result:
391
        if row[0] is None:
392
            statuswisemap = datewiseMap.get('Total Till Date')
393
        else:
394
            statuswisemap = datewiseMap.get(row[0])
395
 
396
        print "------------", row[0], statuswisemap
397
        if statuswisemap is None:
398
            continue
399
        statuswisemap[disposition_map.get('call_duration')] = round(row[1]/3600,2)
400
 
401
    for disdate, statusmap in datewiseMap.iteritems():
402
        print disdate
403
        followupSheet.write(0, DATE_MAP.get(disdate), disdate, date_format if type(disdate) is date else boldStyle)
404
        for index, statuscount in statusmap.iteritems():
405
            if index in [TOTAL,LINK_SENT]:
406
                statuscount -= statusmap.get(CONVERTED)
407
 
408
 
409
            followupSheet.write(index, DATE_MAP.get(disdate),statuscount)
410
 
411
def generateCrmAcquisitionReport():
412
    workbook = xlwt.Workbook()
413
    freshSheet = workbook.add_sheet("Fresh Call Summary")
414
    followupSheet = workbook.add_sheet("Followup Call Summary")
415
    setWorksheetTemplate(freshSheet, followupSheet)
416
    populateFreshSheet(freshSheet)
417
    populateFollowupSheet(followupSheet)
15463 amit.gupta 418
    workbook.save("crmacquisition.xls")
15480 amit.gupta 419
    sendmail(["amit.gupta@shop2020.in", "rajneesh.arora@saholic.com", "amit.sirohi@shop2020.in"], "", "CRM Acquision Report", "crmacquisition.xls")
420
 
421
def sendmail(email, message, title, *varargs):
422
    if email == "":
423
        return
424
    mailServer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
425
    mailServer.ehlo()
426
    mailServer.starttls()
427
    mailServer.ehlo()
428
 
429
    # Create the container (outer) email message.
430
    msg = MIMEMultipart()
431
    msg['Subject'] = title
432
    msg.preamble = title
433
    html_msg = MIMEText(message, 'html')
434
    msg.attach(html_msg)
435
 
436
    #snapdeal more to be added here
437
    for fileName in varargs:
438
        snapdeal = MIMEBase('application', 'vnd.ms-excel')
439
        snapdeal.set_payload(file(fileName).read())
440
        encoders.encode_base64(snapdeal)
441
        snapdeal.add_header('Content-Disposition', 'attachment;filename=' + fileName)
442
        msg.attach(snapdeal)
443
 
444
 
445
    email.append('amit.gupta@shop2020.in')
446
    MAILTO = email 
447
    mailServer.login(SENDER, PASSWORD)
17441 manish.sha 448
    mailServer.sendmail(SENDER, MAILTO, msg.as_string())        
15480 amit.gupta 449
 
15400 amit.gupta 450
def main():
451
    generateCrmAcquisitionReport()
452
 
453
if __name__ == '__main__':
454
    main()