Subversion Repositories SmartDukaan

Rev

Rev 18156 | Rev 18691 | 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"}
18690 manish.sha 39
                                            },
40
                     "creditororders":     {
41
                                                "storeId": 4,
42
                                                "query":{"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])
131
            resp.body = json.dumps({'result':result}, encoding='utf-8')
15791 manish.sha 132
            '''
133
            elif req.get_param_as_int("storeId") == 7:
134
                if 'myprofile' in req_obj['url'][0]:
135
                    result = store.parseMyProfileForEmailId(int(userId),req_obj['url'][0],req_obj['html'][0])
136
                else:
137
                    result = store.parseMyOrdersForEmailId(int(userId),req_obj['url'][0],req_obj['html'][0])
138
                resp.body = json.dumps({'result':result}, encoding='utf-8')
139
            '''
13927 amit.gupta 140
        except:
16392 amit.gupta 141
            traceback.print_exc()
13927 amit.gupta 142
            resp.body = json.dumps({'result':'PARSE_ERROR'}, encoding='utf-8')
14087 amit.gupta 143
 
13868 amit.gupta 144
 
13939 amit.gupta 145
    def on_get(self, req, resp, userId):
13868 amit.gupta 146
        try:
147
            storeId = req.get_param_as_int("storeId")
13939 amit.gupta 148
            result = main.getStore(storeId).getTrackingUrls(int(userId))
13887 amit.gupta 149
            resp.body = json.dumps({'result':result}, encoding='utf-8')
13868 amit.gupta 150
        except ValueError:
151
            raise falcon.HTTPError(falcon.HTTP_400,
152
                'Malformed JSON',
153
                'Could not decode the request body. The '
154
                'JSON was incorrect.')
155
 
13927 amit.gupta 156
class Refunds():
13990 amit.gupta 157
    def on_get(self, req, resp, userId):
13927 amit.gupta 158
        try:
159
            page = req.get_param_as_int("page")
160
            window = req.get_param_as_int("window")
13990 amit.gupta 161
            result = Mongo.getRefunds(int(userId),page,window)
13927 amit.gupta 162
            resp.body = json.dumps(result, encoding='utf-8')
163
        except ValueError:
164
            raise falcon.HTTPError(falcon.HTTP_400,
165
                'Malformed JSON',
166
                'Could not decode the request body. The '
167
                'JSON was incorrect.')
168
 
14427 amit.gupta 169
class Transactions():
170
    def on_get(self, req, resp):
171
        try:
172
            page = req.get_param_as_int("page")
173
            window = req.get_param_as_int("window")
14725 amit.gupta 174
            user = req.get_param("user")
175
            status = req.get_param("status")
15731 amit.gupta 176
            source = req.get_param("source")
14725 amit.gupta 177
            if user == "" :
178
                user = None
179
            if status == "" :
180
                status = None
15731 amit.gupta 181
            result = Mysql.getOrders(page, window,status,user,source)
14427 amit.gupta 182
            resp.body = result
183
            resp.content_type = 'text/html'
184
        except ValueError:
185
            raise falcon.HTTPError(falcon.HTTP_400,
186
                'Malformed JSON',
187
                'Could not decode the request body. The '
188
                'JSON was incorrect.')
16789 amit.gupta 189
 
190
class Rejects():
191
    def on_get(self, req, resp):
192
        try:
193
            result="""<html><head><title>Upload Rejects</title></head><body>
194
            <h1>Upload rejects</h1>
16799 amit.gupta 195
            <form action="rejects" method="POST" enctype="multipart/form-data">
196
              <input type="file" name="rejects" accept=".xlsx, .xls">
16789 amit.gupta 197
              <input type="submit">
198
            </form>
199
 
200
            </body></html>"""
201
            resp.body = result
202
            resp.content_type = 'text/html'
203
        except ValueError:
204
            raise falcon.HTTPError(falcon.HTTP_400,
205
                'Malformed JSON',
206
                'Could not decode the request body. The '
207
                'JSON was incorrect.')
208
 
209
 
210
    def on_post(self, request, resp):
16829 amit.gupta 211
        res = None
16789 amit.gupta 212
        try:
16814 amit.gupta 213
            boundary = request.content_type.split(";")[1].strip().split("=")[1]
16825 amit.gupta 214
            pdict= {'boundary':boundary}
16802 amit.gupta 215
            filepath = "/tmp/rejectfile"
16806 amit.gupta 216
            with open(filepath, 'wb') as image_file:
217
                while True:
218
                    chunk = request.stream.read(4096)
16826 amit.gupta 219
                    if not chunk:
220
                        break
16825 amit.gupta 221
                    image_file.write(chunk)
16828 amit.gupta 222
            with open(filepath, 'r') as image_file:
16829 amit.gupta 223
                res = cgi.parse_multipart(image_file, pdict)['rejects'][0]
224
            if res:
225
                with open(filepath, 'wb') as image_file:
226
                    image_file.write(res)
16838 amit.gupta 227
                rejectCount = process_rejects(filepath)
16829 amit.gupta 228
                resp.content_type = 'text/html'
229
                resp.body = """
230
                    <html><head><title>Upload Rejects</title></head><body>
231
                <h1>Reject Successful</h1>
232
                <h2> %d orders rejected</h2>
233
 
234
                </body></html>
235
                    """%(rejectCount) 
16789 amit.gupta 236
        except ValueError:
237
            raise falcon.HTTPError(falcon.HTTP_400,
238
                'Malformed JSON',
239
                'Could not decode the request body. The '
240
                'JSON was incorrect.')
15081 amit.gupta 241
 
16789 amit.gupta 242
 
243
def process_rejects(filepath):
16838 amit.gupta 244
    rejectCount = 0
16789 amit.gupta 245
    workbook = xlrd.open_workbook(filepath)
246
    sheet = workbook.sheet_by_index(0)
247
    num_rows = sheet.nrows
248
    for rownum in range(1, num_rows):
249
        try:
16831 amit.gupta 250
            orderId, userId, merchantOrderId, subOrderId  = sheet.row_values(rownum)[0:4]
16838 amit.gupta 251
            rejectCount += Mongo.rejectCashback(int(orderId), subOrderId)
16789 amit.gupta 252
        except:
253
            traceback.print_exc()
16838 amit.gupta 254
    return rejectCount
16789 amit.gupta 255
 
15081 amit.gupta 256
class SnapShot():
257
    def on_get(self, req, resp):
258
        try:
259
            resp.content_type = 'text/html'
260
            user = req.get_param_as_int("user")
261
            file = req.get_param("file") 
262
            if  file is not None:
263
                #fetch the page and return html
264
                with open ("/AmazonTrack/User%d/%s"%(user, file), "r") as myfile:
265
                    resp.body=myfile.read() 
266
            else:
267
                #return user specific urls
268
                resp.body=getUserUrls(user)
269
        except ValueError:
270
            raise falcon.HTTPError(falcon.HTTP_400,
271
                'Malformed JSON',
272
                'Could not decode the request body. The '
273
                'JSON was incorrect.')
274
 
275
def getUserUrls(user):
276
    pass
14427 amit.gupta 277
 
278
class RawHtml():
279
    def on_get(self, req, resp, orderId):
280
        try:
281
            result = Mysql.getOrderHtml(orderId)
15544 amit.gupta 282
            if req.get_param("show") is None:
283
                result = re.subn(r'(src|href|style)=\s?(\'|").*?\2(?s)', '', re.subn(r'<(script|style).*?</\1>(?s)', '', result)[0])[0]
14427 amit.gupta 284
            resp.body = result
285
            resp.content_type = 'text/html'
286
        except ValueError:
287
            raise falcon.HTTPError(falcon.HTTP_400,
288
                'Malformed JSON',
289
                'Could not decode the request body. The '
290
                'JSON was incorrect.')
291
 
13927 amit.gupta 292
class PendingRefunds():
293
    def on_get(self, req, resp,userId):
294
        try:
295
            result = Mongo.getPendingRefunds(int(userId))
296
            resp.body = json.dumps(result, encoding='utf-8')
297
        except ValueError:
298
            raise falcon.HTTPError(falcon.HTTP_400,
299
                'Malformed JSON',
300
                'Could not decode the request body. The '
14671 amit.gupta 301
                'JSON was incorrect.')
17307 amit.gupta 302
 
303
class AmazonSummary():
304
    def on_get(self, req, resp,userId):
305
        try:
17455 amit.gupta 306
            result = getSummary(userId, req)
17307 amit.gupta 307
            if result:
308
                resp.body = result
309
            else:
310
                resp.body = ''
311
            resp.content_type = 'text/html'
312
        except ValueError:
313
            raise falcon.HTTPError(falcon.HTTP_400,
314
                'Malformed JSON',
315
                'Could not decode the request body. The '
316
                'JSON was incorrect.')
317
 
318
 
17455 amit.gupta 319
def getSummary(userId, req):
17308 amit.gupta 320
    directory = "/AmazonTrack/User" + userId
17307 amit.gupta 321
    date1 = datetime(2015,1,1)
322
    finalFile = None
323
    str1 = None
324
    try:
325
        for file in os.listdir(directory):
326
            if file.startswith("orderSummary"):
327
                date2 = datetime.strptime("2015-" + file.split("orderSummary")[1].split(":")[0], "%Y-%d-%m")
328
                if date2 > date1:
329
                    date1 = date2
330
                    finalFile=file
17455 amit.gupta 331
        result = open(directory + "/" + finalFile).read()
332
        if req.get_param("show") is None:
333
            result = re.subn(r'(src|href|style)=\s?(\'|").*?\2(?s)', '', re.subn(r'<(script|style).*?</\1>(?s)', '', result)[0])[0]
334
 
335
        return result
17307 amit.gupta 336
    except:
337
        print "Missing directory"
338
    return str1
14671 amit.gupta 339
 
340
class PendingCashBacks():
341
    def on_get(self, req, resp,userId):
342
        try:
343
            result = Mongo.getPendingCashbacks(int(userId))
344
            resp.body = json.dumps(result, encoding='utf-8')
345
        except ValueError:
346
            raise falcon.HTTPError(falcon.HTTP_400,
347
                'Malformed JSON',
348
                'Could not decode the request body. The '
16789 amit.gupta 349
                'JSON was incorrect.')
350
 
351
def tprint(*msg):
352
    print datetime.now(), "-", msg