Subversion Repositories SmartDukaan

Rev

Rev 18691 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
13804 amit.gupta 1
'''
2
Created on Feb 12, 2015
3
 
4
@author: amit
5
'''
17659 amit.gupta 6
from datetime import datetime
13804 amit.gupta 7
from dtr import main
16789 amit.gupta 8
from dtr.main import tprint
14427 amit.gupta 9
from dtr.storage import Mongo, Mysql
16167 amit.gupta 10
from dtr.utils import utils
17659 amit.gupta 11
from dtr.utils.utils import find_between
12
import cgi
13804 amit.gupta 13
import falcon
14
import json
16789 amit.gupta 15
import os.path
16167 amit.gupta 16
import re
16789 amit.gupta 17
import traceback
14014 amit.gupta 18
import urlparse
16789 amit.gupta 19
import xlrd
17276 amit.gupta 20
 
21
order_fliters = {
22
                 "monitor":{
23
                    "trackingurlmissing":  {
24
                                                "displaylabel":"Tracking Url Missing",
25
                                                "query":{"subOrders.closed":False,"subOrders.trackingUrl":{"$exists":False}, "subOrders.trackMissing":True}
26
                                            }, 
27
                     "orderuntrackable":    {
28
                                                "displaylabel":"Untrackable Orders",   
29
                                                "query":{"trackError":True, "storeId":1, "subOrders.closed":False}
30
                                            },
31
                     "prematurelyclosed" :  {
32
                                                "displaylabel": "Prematurely Closed Orders",
33
                                                "query":{"closed":True, "subOrders.closed":False}
34
                                            },
35
 
36
                     "parsefailed":         {   
37
                                                "displaylabel": "Failed to Parse Orders",
17289 amit.gupta 38
                                                "query":{"subOrders":{"$exists": False}, "status":"parse_failed"}
18690 manish.sha 39
                                            },
40
                     "creditororders":     {
18691 manish.sha 41
                                                "displaylabel": "Orders Created using Credit Option",
42
                                                "query":{"storeId": 4,"payment_option":{"$exists":True}}
17276 amit.gupta 43
                                            }
44
                     },
45
 
46
                 "user":{}
47
 
48
                 }
13804 amit.gupta 49
class StoreOrder():
50
    def on_post(self, req, resp):
51
 
52
        try:
53
            string1 = req.stream.read()
54
            req_json = json.loads(string1, encoding='utf-8')
55
        except ValueError:
56
            raise falcon.HTTPError(falcon.HTTP_400,
57
                'Malformed JSON',
58
                'Could not decode the request body. The '
59
                'JSON was incorrect.')
60
 
61
        store = main.getStore(int(req_json['sourceId']))
62
        result = store.parseOrderRawHtml(int(req_json['orderId']), req_json['subTagId'], int(req_json['userId']), req_json['rawHtml'], req_json['orderSuccessUrl'])
63
        resp.body = json.dumps(result, encoding='utf-8')
64
 
65
    def on_get(self, req, resp, userId):
66
        page = req.get_param_as_int("page")
67
        window = req.get_param_as_int("window")
14003 amit.gupta 68
        string1 = req.get_param("searchMap")
15821 amit.gupta 69
        orderType = req.get_param("type")
14004 amit.gupta 70
        searchMap={}
15821 amit.gupta 71
        if orderType is not None and orderType != "":
15822 amit.gupta 72
            if orderType in ['needamazonorderdetail','needamazonordertrack']:
16167 amit.gupta 73
                searchMap={"$or":[{"subOrders.closed":False,"subOrders.trackingUrl":{"$exists":False},"subOrders.trackAfter":{"$lt":utils.getCurrTimeStamp()}}, {"status":"html_required"}], "storeId":1}
15821 amit.gupta 74
        elif string1 is not None and string1 != "":
14006 amit.gupta 75
            try:
14007 amit.gupta 76
                searchMap = json.loads(string1, encoding='utf-8')
14006 amit.gupta 77
            except:
17723 amit.gupta 78
                traceback.print_exc()
14006 amit.gupta 79
                raise falcon.HTTPError(falcon.HTTP_400,
80
                    'Malformed JSON',
81
                    'Could not decode the request body. The '
82
                    'JSON was incorrect.')
14003 amit.gupta 83
        result = Mongo.getMerchantOrdersByUser(int(userId), page, window, searchMap)
13868 amit.gupta 84
        resp.body = json.dumps(result, encoding='utf-8')
85
 
17276 amit.gupta 86
 
87
class OrderFilters():
88
    def on_get(self, req, resp):
17282 amit.gupta 89
        filter_type = req.get_param("type")
90
        result = order_fliters.get(filter_type)
91
        resp.body = json.dumps(result, encoding='utf-8')
17276 amit.gupta 92
 
17282 amit.gupta 93
 
14352 amit.gupta 94
class Orders():
95
    def on_get(self, req, resp):
96
        page = req.get_param_as_int("page")
97
        window = req.get_param_as_int("window")
98
        string1 = req.get_param("searchMap")
17283 amit.gupta 99
        orderFilter = req.get_param("filter")
17282 amit.gupta 100
        filterType = req.get_param("filtertype")
14352 amit.gupta 101
        searchMap={}
17284 amit.gupta 102
        if filter and filterType:
17282 amit.gupta 103
            try:
17286 amit.gupta 104
                searchMap = order_fliters[filterType][orderFilter]['query']
17282 amit.gupta 105
            except:
106
                pass
17284 amit.gupta 107
        elif string1:
14352 amit.gupta 108
            try:
109
                searchMap = json.loads(string1, encoding='utf-8')
110
            except:
111
                raise falcon.HTTPError(falcon.HTTP_400,
112
                    'Malformed JSON',
113
                    'Could not decode the request body. The '
114
                    'JSON was incorrect.')
115
        result = Mongo.getMerchantOrdersByUser(None, page, window, searchMap)
116
        resp.body = json.dumps(result, encoding='utf-8')
117
 
13868 amit.gupta 118
class Track():
13939 amit.gupta 119
    def on_post(self, req, resp, userId):
13868 amit.gupta 120
        try:
14013 amit.gupta 121
            string1 = req.stream.read()
14014 amit.gupta 122
            req_obj = urlparse.parse_qs(string1)
14013 amit.gupta 123
        except ValueError:
124
            raise falcon.HTTPError(falcon.HTTP_400,
125
                'Malformed JSON',
126
                'Could not decode the request body. The '
127
                'JSON was incorrect.')
128
        try:
13927 amit.gupta 129
            store = main.getStore(req.get_param_as_int("storeId"))
16371 amit.gupta 130
            result = store.trackOrdersForUser(int(userId),req_obj['url'][0],req_obj['html'][0])
21333 amit.gupta 131
            print result
16371 amit.gupta 132
            resp.body = json.dumps({'result':result}, encoding='utf-8')
15791 manish.sha 133
            '''
134
            elif req.get_param_as_int("storeId") == 7:
135
                if 'myprofile' in req_obj['url'][0]:
136
                    result = store.parseMyProfileForEmailId(int(userId),req_obj['url'][0],req_obj['html'][0])
137
                else:
138
                    result = store.parseMyOrdersForEmailId(int(userId),req_obj['url'][0],req_obj['html'][0])
139
                resp.body = json.dumps({'result':result}, encoding='utf-8')
140
            '''
13927 amit.gupta 141
        except:
16392 amit.gupta 142
            traceback.print_exc()
13927 amit.gupta 143
            resp.body = json.dumps({'result':'PARSE_ERROR'}, encoding='utf-8')
14087 amit.gupta 144
 
13868 amit.gupta 145
 
13939 amit.gupta 146
    def on_get(self, req, resp, userId):
13868 amit.gupta 147
        try:
148
            storeId = req.get_param_as_int("storeId")
13939 amit.gupta 149
            result = main.getStore(storeId).getTrackingUrls(int(userId))
13887 amit.gupta 150
            resp.body = json.dumps({'result':result}, encoding='utf-8')
13868 amit.gupta 151
        except ValueError:
152
            raise falcon.HTTPError(falcon.HTTP_400,
153
                'Malformed JSON',
154
                'Could not decode the request body. The '
155
                'JSON was incorrect.')
156
 
13927 amit.gupta 157
class Refunds():
13990 amit.gupta 158
    def on_get(self, req, resp, userId):
13927 amit.gupta 159
        try:
160
            page = req.get_param_as_int("page")
161
            window = req.get_param_as_int("window")
13990 amit.gupta 162
            result = Mongo.getRefunds(int(userId),page,window)
13927 amit.gupta 163
            resp.body = json.dumps(result, encoding='utf-8')
164
        except ValueError:
165
            raise falcon.HTTPError(falcon.HTTP_400,
166
                'Malformed JSON',
167
                'Could not decode the request body. The '
168
                'JSON was incorrect.')
169
 
14427 amit.gupta 170
class Transactions():
171
    def on_get(self, req, resp):
172
        try:
173
            page = req.get_param_as_int("page")
174
            window = req.get_param_as_int("window")
14725 amit.gupta 175
            user = req.get_param("user")
176
            status = req.get_param("status")
15731 amit.gupta 177
            source = req.get_param("source")
14725 amit.gupta 178
            if user == "" :
179
                user = None
180
            if status == "" :
181
                status = None
15731 amit.gupta 182
            result = Mysql.getOrders(page, window,status,user,source)
14427 amit.gupta 183
            resp.body = result
184
            resp.content_type = 'text/html'
185
        except ValueError:
186
            raise falcon.HTTPError(falcon.HTTP_400,
187
                'Malformed JSON',
188
                'Could not decode the request body. The '
189
                'JSON was incorrect.')
16789 amit.gupta 190
 
191
class Rejects():
192
    def on_get(self, req, resp):
193
        try:
194
            result="""<html><head><title>Upload Rejects</title></head><body>
195
            <h1>Upload rejects</h1>
16799 amit.gupta 196
            <form action="rejects" method="POST" enctype="multipart/form-data">
197
              <input type="file" name="rejects" accept=".xlsx, .xls">
16789 amit.gupta 198
              <input type="submit">
199
            </form>
200
 
201
            </body></html>"""
202
            resp.body = result
203
            resp.content_type = 'text/html'
204
        except ValueError:
205
            raise falcon.HTTPError(falcon.HTTP_400,
206
                'Malformed JSON',
207
                'Could not decode the request body. The '
208
                'JSON was incorrect.')
209
 
210
 
211
    def on_post(self, request, resp):
16829 amit.gupta 212
        res = None
16789 amit.gupta 213
        try:
16814 amit.gupta 214
            boundary = request.content_type.split(";")[1].strip().split("=")[1]
16825 amit.gupta 215
            pdict= {'boundary':boundary}
16802 amit.gupta 216
            filepath = "/tmp/rejectfile"
16806 amit.gupta 217
            with open(filepath, 'wb') as image_file:
218
                while True:
219
                    chunk = request.stream.read(4096)
16826 amit.gupta 220
                    if not chunk:
221
                        break
16825 amit.gupta 222
                    image_file.write(chunk)
16828 amit.gupta 223
            with open(filepath, 'r') as image_file:
16829 amit.gupta 224
                res = cgi.parse_multipart(image_file, pdict)['rejects'][0]
225
            if res:
226
                with open(filepath, 'wb') as image_file:
227
                    image_file.write(res)
16838 amit.gupta 228
                rejectCount = process_rejects(filepath)
16829 amit.gupta 229
                resp.content_type = 'text/html'
230
                resp.body = """
231
                    <html><head><title>Upload Rejects</title></head><body>
232
                <h1>Reject Successful</h1>
233
                <h2> %d orders rejected</h2>
234
 
235
                </body></html>
236
                    """%(rejectCount) 
16789 amit.gupta 237
        except ValueError:
238
            raise falcon.HTTPError(falcon.HTTP_400,
239
                'Malformed JSON',
240
                'Could not decode the request body. The '
241
                'JSON was incorrect.')
15081 amit.gupta 242
 
16789 amit.gupta 243
 
244
def process_rejects(filepath):
16838 amit.gupta 245
    rejectCount = 0
16789 amit.gupta 246
    workbook = xlrd.open_workbook(filepath)
247
    sheet = workbook.sheet_by_index(0)
248
    num_rows = sheet.nrows
249
    for rownum in range(1, num_rows):
250
        try:
16831 amit.gupta 251
            orderId, userId, merchantOrderId, subOrderId  = sheet.row_values(rownum)[0:4]
16838 amit.gupta 252
            rejectCount += Mongo.rejectCashback(int(orderId), subOrderId)
16789 amit.gupta 253
        except:
254
            traceback.print_exc()
16838 amit.gupta 255
    return rejectCount
16789 amit.gupta 256
 
15081 amit.gupta 257
class SnapShot():
258
    def on_get(self, req, resp):
259
        try:
260
            resp.content_type = 'text/html'
261
            user = req.get_param_as_int("user")
262
            file = req.get_param("file") 
263
            if  file is not None:
264
                #fetch the page and return html
265
                with open ("/AmazonTrack/User%d/%s"%(user, file), "r") as myfile:
266
                    resp.body=myfile.read() 
267
            else:
268
                #return user specific urls
269
                resp.body=getUserUrls(user)
270
        except ValueError:
271
            raise falcon.HTTPError(falcon.HTTP_400,
272
                'Malformed JSON',
273
                'Could not decode the request body. The '
274
                'JSON was incorrect.')
275
 
276
def getUserUrls(user):
277
    pass
14427 amit.gupta 278
 
279
class RawHtml():
280
    def on_get(self, req, resp, orderId):
281
        try:
282
            result = Mysql.getOrderHtml(orderId)
15544 amit.gupta 283
            if req.get_param("show") is None:
284
                result = re.subn(r'(src|href|style)=\s?(\'|").*?\2(?s)', '', re.subn(r'<(script|style).*?</\1>(?s)', '', result)[0])[0]
14427 amit.gupta 285
            resp.body = result
286
            resp.content_type = 'text/html'
287
        except ValueError:
288
            raise falcon.HTTPError(falcon.HTTP_400,
289
                'Malformed JSON',
290
                'Could not decode the request body. The '
291
                'JSON was incorrect.')
292
 
13927 amit.gupta 293
class PendingRefunds():
294
    def on_get(self, req, resp,userId):
295
        try:
296
            result = Mongo.getPendingRefunds(int(userId))
297
            resp.body = json.dumps(result, encoding='utf-8')
298
        except ValueError:
299
            raise falcon.HTTPError(falcon.HTTP_400,
300
                'Malformed JSON',
301
                'Could not decode the request body. The '
14671 amit.gupta 302
                'JSON was incorrect.')
17307 amit.gupta 303
 
304
class AmazonSummary():
305
    def on_get(self, req, resp,userId):
306
        try:
17455 amit.gupta 307
            result = getSummary(userId, req)
17307 amit.gupta 308
            if result:
309
                resp.body = result
310
            else:
311
                resp.body = ''
312
            resp.content_type = 'text/html'
313
        except ValueError:
314
            raise falcon.HTTPError(falcon.HTTP_400,
315
                'Malformed JSON',
316
                'Could not decode the request body. The '
317
                'JSON was incorrect.')
318
 
319
 
17455 amit.gupta 320
def getSummary(userId, req):
17308 amit.gupta 321
    directory = "/AmazonTrack/User" + userId
17307 amit.gupta 322
    date1 = datetime(2015,1,1)
323
    finalFile = None
324
    str1 = None
325
    try:
326
        for file in os.listdir(directory):
327
            if file.startswith("orderSummary"):
328
                date2 = datetime.strptime("2015-" + file.split("orderSummary")[1].split(":")[0], "%Y-%d-%m")
329
                if date2 > date1:
330
                    date1 = date2
331
                    finalFile=file
17455 amit.gupta 332
        result = open(directory + "/" + finalFile).read()
333
        if req.get_param("show") is None:
334
            result = re.subn(r'(src|href|style)=\s?(\'|").*?\2(?s)', '', re.subn(r'<(script|style).*?</\1>(?s)', '', result)[0])[0]
335
 
336
        return result
17307 amit.gupta 337
    except:
338
        print "Missing directory"
339
    return str1
14671 amit.gupta 340
 
341
class PendingCashBacks():
342
    def on_get(self, req, resp,userId):
343
        try:
344
            result = Mongo.getPendingCashbacks(int(userId))
345
            resp.body = json.dumps(result, encoding='utf-8')
346
        except ValueError:
347
            raise falcon.HTTPError(falcon.HTTP_400,
348
                'Malformed JSON',
349
                'Could not decode the request body. The '
16789 amit.gupta 350
                'JSON was incorrect.')
351
 
352
def tprint(*msg):
353
    print datetime.now(), "-", msg