Subversion Repositories SmartDukaan

Rev

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