Subversion Repositories SmartDukaan

Rev

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