Subversion Repositories SmartDukaan

Rev

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