Subversion Repositories SmartDukaan

Rev

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