Subversion Repositories SmartDukaan

Rev

Rev 15401 | 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
15463 amit.gupta 8
from dtr.reports.affiliatereco import sendmail
15400 amit.gupta 9
import MySQLdb
10
import copy
11
import xlwt
12
 
13
 
14
date_format = xlwt.XFStyle()
15
date_format.num_format_str = 'dd/mm/yyyy'
16
 
17
datetime_format = xlwt.XFStyle()
18
datetime_format.num_format_str = 'dd/mm/yyyy HH:MM AM/PM'
19
 
20
default_format = xlwt.XFStyle()
21
 
22
boldStyle = xlwt.XFStyle()
23
f = xlwt.Font()
24
f.bold = True
25
boldStyle.font = f
26
 
27
date_format.font = f
28
ALLIED = 4
29
NOT_RETAILER =7
30
RETAILER_NOT_INTERESTED=3
31
NOT_CONTACTABLE = 6
32
CALL_LATER=5
33
ALREADY_USER = 8
34
TOTAL = 9
35
TOTAL_AGENTS = 10
36
TOTAL_LOGIN_TIME = 11
37
TOTAL_CALL_DURATION = 12
38
CONVERTED=1
39
AWAITING_CONVERSION =2
40
LINK_SENT =2
41
 
42
 
43
 
44
 
45
 
46
disposition_map={
47
                    'call_later':CALL_LATER,
48
                    'ringing_no_answer':NOT_CONTACTABLE,
49
                    'not_reachable':NOT_CONTACTABLE,
50
                    'switch_off':NOT_CONTACTABLE,
51
                    'invalid_no':NOT_CONTACTABLE,
52
                    'wrong_no':NOT_CONTACTABLE,
53
                    'hang_up':NOT_CONTACTABLE,
54
                    'retailer_not_interested':RETAILER_NOT_INTERESTED,
55
                    'alreadyuser':ALREADY_USER,
56
                    'verified_link_sent':LINK_SENT,
57
                    'converted':CONVERTED,
58
                    'accessory_retailer':ALLIED,
59
                    'service_center_retailer':ALLIED,
60
                    'not_retailer':NOT_RETAILER,
61
                    'recharge_retailer':ALLIED,
62
                    None:TOTAL,
63
                    'agent_count':TOTAL_AGENTS,
64
                    'login_time' : TOTAL_LOGIN_TIME,
65
                    'call_duration': TOTAL_CALL_DURATION
66
                }
67
STATUS_MAP = {
68
              CONVERTED:0,
69
              AWAITING_CONVERSION:0,
70
              RETAILER_NOT_INTERESTED:0,
71
              NOT_CONTACTABLE:0,
72
              ALLIED:0,
73
              CALL_LATER:0,
74
              NOT_CONTACTABLE:0,
75
              NOT_RETAILER:0,
76
              ALREADY_USER:0,
77
              TOTAL:0,
78
              TOTAL_AGENTS:0,
79
              TOTAL_LOGIN_TIME:0,
80
              TOTAL_CALL_DURATION:0
81
              }
82
PREVIOUS_DATE = datetime.now() -timedelta(days=1)
83
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}
84
 
85
def getLast4daysQuery(type='fresh'):
86
    fourDaysBefore = PREVIOUS_DATE - timedelta(days=3)
87
    fourDaysBefore = fourDaysBefore.date()
88
    curDate = (PREVIOUS_DATE + timedelta(days=1)).date()
89
    return '''select date(created), call_disposition, count(1) from (
90
    (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)
91
    union 
92
    (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 93
    )a group by date(created), call_disposition with rollup'''%(fourDaysBefore,curDate,type,type,fourDaysBefore,curDate )
15400 amit.gupta 94
        #union select date(created) dc, agent_i
95
 
96
def getMDTQuery(type='fresh'):
97
    return '''select a.dc, a.call_disposition, count(1) from
98
            (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
99
    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
100
    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
101
    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)
102
    a group by a.dc, a.call_disposition with rollup
103
    '''%(PREVIOUS_DATE.month, type, type, type, PREVIOUS_DATE.month, type)
104
 
105
def getConvertedMTDQuery():
106
    pass
107
 
108
 
109
def getTillDateQuery():
110
    pass
111
 
112
 
113
def setWorksheetTemplate(freshSheet, followupSheet):
114
    freshSheet.write(1, 0, 'Converted', boldStyle)
115
    freshSheet.write(2, 0, 'Link sent yet to be converted', boldStyle)
116
    freshSheet.write(3, 0, 'Retailer not interested', boldStyle)
117
    freshSheet.write(4, 0, 'Allied category retailer', boldStyle)
118
    freshSheet.write(5, 0, 'Call Later', boldStyle)
119
    freshSheet.write(6, 0, 'Not contactable', boldStyle)
120
    freshSheet.write(7, 0, 'Not a retailer', boldStyle)
121
    freshSheet.write(8, 0, 'AlreadyUser', boldStyle)
122
    freshSheet.write(9, 0, 'Total Attempts (Total of above)', boldStyle)
123
    freshSheet.write(10, 0, 'Total Agents Logged in', boldStyle)
124
    freshSheet.write(11, 0, 'Total Login time (Hours)', boldStyle)
125
    freshSheet.write(12, 0, 'Total Call Duration (Hours)', boldStyle)
126
 
127
    followupSheet.write(1, 0, 'Conversion After Followup', boldStyle)
128
    followupSheet.write(2, 0, 'Link sent again', boldStyle)
129
    followupSheet.write(3, 0, 'Retailer not interested', boldStyle)
130
    followupSheet.write(4, 0, 'Allied category retailer', boldStyle)
131
    followupSheet.write(5, 0, 'Call Later', boldStyle)
132
    followupSheet.write(6, 0, 'Not contactable', boldStyle)
133
    followupSheet.write(7, 0, 'Not a retailer', boldStyle)
134
    followupSheet.write(8, 0, 'AlreadyUser', boldStyle)
135
    followupSheet.write(9, 0, 'Total Attempts (Total of above)', boldStyle)
136
    followupSheet.write(10, 0, 'Total Agents Logged in', boldStyle)
137
    followupSheet.write(11, 0, 'Total Login time (Hours)', boldStyle)
138
    followupSheet.write(12, 0, 'Total Call Duration (Hours)', boldStyle)
139
 
140
 
141
 
142
def getDbConnection():
143
    return MySQLdb.connect('localhost', 'root', 'shop2020', 'dtr')
144
 
145
 
146
    conn = getDbConnection()
147
 
148
def populateFreshSheet(freshSheet):
149
    query = getLast4daysQuery()
150
    print query
151
    conn = getDbConnection()
152
    cursor = conn.cursor()
153
    cursor.execute(query)
154
    result = cursor.fetchall()
155
    datewiseMap = {}
156
    for x in [0,1,2,3,'MTD', 'Total Till Date' ]:
157
        if type(x) is int:
158
            datetime1 = PREVIOUS_DATE - timedelta(days=x)
159
            datewiseMap[datetime1.date()] = copy.deepcopy(STATUS_MAP)
160
        else:
161
            datewiseMap[x] = copy.deepcopy(STATUS_MAP)
162
    print datewiseMap
163
    for row in result:
164
        if row[0] is None:
165
            continue
166
        print row[0]
167
        statuswisemap = datewiseMap.get(row[0])
168
        disposition_tag = disposition_map.get(row[1])
169
        if statuswisemap.get(disposition_tag) is None:
170
            statuswisemap[disposition_tag] = 0
171
        print row[2]
172
        statuswisemap[disposition_tag] += row[2]
173
 
174
    query = getMDTQuery()
175
    cursor.execute(query)
176
    result = cursor.fetchall()
177
    for row in result:
178
        if row[0] is None:
179
            continue
180
        print row[0]
181
        statuswisemap = datewiseMap.get(row[0])
182
        disposition_tag = disposition_map.get(row[1])
183
        if statuswisemap.get(disposition_tag) is None:
184
            statuswisemap[disposition_tag] = 0
185
        print row[2]
186
        statuswisemap[disposition_tag] += row[2]
187
 
188
 
189
 
190
    q= '''
191
    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 
192
    '''
193
    conn = getDbConnection()
194
    cursor = conn.cursor()
195
    cursor.execute(q)
196
    result = cursor.fetchall()
197
    for row in result:
198
        if row[0] is None:
199
            statuswisemap = datewiseMap.get('Total Till Date')
200
        else:
201
            statuswisemap = datewiseMap.get(row[0])
202
 
203
        print "------------", row[0], statuswisemap
204
        if statuswisemap is None:
205
            continue
206
        statuswisemap[disposition_map.get('agent_count')] = row[1]
207
        statuswisemap[disposition_map.get('login_time')] = round(row[2]/3600,2)
208
 
209
    q= '''
210
    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))
211
    '''
212
    conn = getDbConnection()
213
    cursor = conn.cursor()
214
    cursor.execute(q)
215
    result = cursor.fetchall()
216
    for row in result:
217
        if row[0] is None:
218
            statuswisemap = datewiseMap.get('Total Till Date')
219
        else:
220
            statuswisemap = datewiseMap.get(row[0])
221
 
222
        print "------------", row[0], statuswisemap
223
        if statuswisemap is None:
224
            continue
225
        statuswisemap[disposition_map.get('agent_count')] = row[1]
226
        statuswisemap[disposition_map.get('login_time')] = round(row[2]/3600,2)
227
 
228
 
229
    q ='''
230
         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
231
         '''
232
    conn = getDbConnection()
233
    cursor = conn.cursor()
234
    cursor.execute(q)
235
    result = cursor.fetchall()
236
    for row in result:
237
        if row[0] is None:
238
            statuswisemap = datewiseMap.get('Total Till Date')
239
        else:
240
            statuswisemap = datewiseMap.get(row[0])
241
 
242
        print "------------", row[0], statuswisemap
243
        if statuswisemap is None:
244
            continue
245
        statuswisemap[disposition_map.get('call_duration')] = round(row[1]/3600,2)
246
 
247
    q ='''
248
         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) 
249
         '''
250
    conn = getDbConnection()
251
    cursor = conn.cursor()
252
    cursor.execute(q)
253
    result = cursor.fetchall()
254
    for row in result:
255
        if row[0] is None:
256
            statuswisemap = datewiseMap.get('Total Till Date')
257
        else:
258
            statuswisemap = datewiseMap.get(row[0])
259
 
260
        print "------------", row[0], statuswisemap
261
        if statuswisemap is None:
262
            continue
263
        statuswisemap[disposition_map.get('call_duration')] = round(row[1]/3600,2)
264
 
265
    for disdate, statusmap in datewiseMap.iteritems():
266
        freshSheet.write(0, DATE_MAP.get(disdate), disdate, date_format if type(disdate) is date else boldStyle)
267
        for index, statuscount in statusmap.iteritems():
268
            if index in [TOTAL,LINK_SENT]:
269
                statuscount -= statusmap.get(CONVERTED)
270
 
271
            print index, disdate, statuscount    
272
            freshSheet.write(index, DATE_MAP.get(disdate),statuscount)
273
 
274
def populateFollowupSheet(followupSheet):
275
    query = getLast4daysQuery('followup')
276
    print query
277
    conn = getDbConnection()
278
    cursor = conn.cursor()
279
    cursor.execute(query)
280
    result = cursor.fetchall()
281
    datewiseMap = {}
282
    for x in [0,1,2,3,'MTD', 'Total Till Date' ]:
283
        if type(x) is int:
284
            datetime1 = PREVIOUS_DATE - timedelta(days=x)
285
            datewiseMap[datetime1.date()] = copy.deepcopy(STATUS_MAP)
286
        else:
287
            datewiseMap[x] = copy.deepcopy(STATUS_MAP)
288
    print datewiseMap
289
    for row in result:
290
        if row[0] is None:
291
            continue
292
        print row[0]
293
        statuswisemap = datewiseMap.get(row[0])
294
        disposition_tag = disposition_map.get(row[1])
295
        print "disposition_tag",disposition_tag
296
        if statuswisemap.get(disposition_tag) is None:
297
            statuswisemap[disposition_tag] = 0
298
        print row[2]
299
        statuswisemap[disposition_tag] += row[2]
300
 
301
    query = getMDTQuery('followup')
302
    cursor.execute(query)
303
    result = cursor.fetchall()
304
    for row in result:
305
        if row[0] is None:
306
            continue
307
        print row[0]
308
        statuswisemap = datewiseMap.get(row[0])
309
        disposition_tag = disposition_map.get(row[1])
310
        print "disposition_tag",disposition_tag
311
        if statuswisemap.get(disposition_tag) is None:
312
            statuswisemap[disposition_tag] = 0
313
        print row[2]
314
        statuswisemap[disposition_tag] += row[2]
315
 
316
 
317
        q= '''
318
    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 
319
    '''
320
    conn = getDbConnection()
321
    cursor = conn.cursor()
322
    cursor.execute(q)
323
    result = cursor.fetchall()
324
    for row in result:
325
        if row[0] is None:
326
            statuswisemap = datewiseMap.get('Total Till Date')
327
        else:
328
            statuswisemap = datewiseMap.get(row[0])
329
 
330
        print "------------", row[0], statuswisemap
331
        if statuswisemap is None:
332
            continue
333
        statuswisemap[disposition_map.get('agent_count')] = row[1]
334
        statuswisemap[disposition_map.get('login_time')] = round(row[2]/3600,2)
335
 
336
    q= '''
337
    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))
338
    '''
339
    conn = getDbConnection()
340
    cursor = conn.cursor()
341
    cursor.execute(q)
342
    result = cursor.fetchall()
343
    for row in result:
344
        if row[0] is None:
345
            statuswisemap = datewiseMap.get('Total Till Date')
346
        else:
347
            statuswisemap = datewiseMap.get(row[0])
348
 
349
        print "------------", row[0], statuswisemap
350
        if statuswisemap is None:
351
            continue
352
        statuswisemap[disposition_map.get('agent_count')] = row[1]
353
        statuswisemap[disposition_map.get('login_time')] = round(row[2]/3600,2)
354
 
355
 
356
    q ='''
357
         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
358
         '''
359
    conn = getDbConnection()
360
    cursor = conn.cursor()
361
    cursor.execute(q)
362
    result = cursor.fetchall()
363
    for row in result:
364
        if row[0] is None:
365
            statuswisemap = datewiseMap.get('Total Till Date')
366
        else:
367
            statuswisemap = datewiseMap.get(row[0])
368
 
369
        print "------------", row[0], statuswisemap
370
        if statuswisemap is None:
371
            continue
372
        statuswisemap[disposition_map.get('call_duration')] = round(row[1]/3600,2)
373
 
374
    q ='''
375
         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) 
376
         '''
377
    conn = getDbConnection()
378
    cursor = conn.cursor()
379
    cursor.execute(q)
380
    result = cursor.fetchall()
381
    for row in result:
382
        if row[0] is None:
383
            statuswisemap = datewiseMap.get('Total Till Date')
384
        else:
385
            statuswisemap = datewiseMap.get(row[0])
386
 
387
        print "------------", row[0], statuswisemap
388
        if statuswisemap is None:
389
            continue
390
        statuswisemap[disposition_map.get('call_duration')] = round(row[1]/3600,2)
391
 
392
    for disdate, statusmap in datewiseMap.iteritems():
393
        print disdate
394
        followupSheet.write(0, DATE_MAP.get(disdate), disdate, date_format if type(disdate) is date else boldStyle)
395
        for index, statuscount in statusmap.iteritems():
396
            if index in [TOTAL,LINK_SENT]:
397
                statuscount -= statusmap.get(CONVERTED)
398
 
399
 
400
            followupSheet.write(index, DATE_MAP.get(disdate),statuscount)
401
 
402
def generateCrmAcquisitionReport():
403
    workbook = xlwt.Workbook()
404
    freshSheet = workbook.add_sheet("Fresh Call Summary")
405
    followupSheet = workbook.add_sheet("Followup Call Summary")
406
    setWorksheetTemplate(freshSheet, followupSheet)
407
    populateFreshSheet(freshSheet)
408
    populateFollowupSheet(followupSheet)
15463 amit.gupta 409
    workbook.save("crmacquisition.xls")
410
    sendmail(["amit.gupta@shop2020.in", "rajneesh.arora@saholic.com", "amit.sirohi@shop2020.in"], "", "CRM Acquision Report", "crmacquisition.xls")        
15400 amit.gupta 411
def main():
412
    generateCrmAcquisitionReport()
413
 
414
if __name__ == '__main__':
415
    main()