Subversion Repositories SmartDukaan

Rev

Rev 17282 | Rev 17284 | 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",
39
                                                "query":{"$subOrders":{"$exists": False}, "status":"parse_failed"}
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={}
98
        if string1 is None or string1 == "":
99
            pass
17282 amit.gupta 100
        elif filter and filterType:
101
            try:
17283 amit.gupta 102
                searchMap = order_fliters[filterType][orderFilter]
17282 amit.gupta 103
            except:
104
                pass
14352 amit.gupta 105
        else:
106
            try:
107
                searchMap = json.loads(string1, encoding='utf-8')
108
            except:
109
                raise falcon.HTTPError(falcon.HTTP_400,
110
                    'Malformed JSON',
111
                    'Could not decode the request body. The '
112
                    'JSON was incorrect.')
113
        result = Mongo.getMerchantOrdersByUser(None, page, window, searchMap)
114
        resp.body = json.dumps(result, encoding='utf-8')
115
 
13868 amit.gupta 116
class Track():
13939 amit.gupta 117
    def on_post(self, req, resp, userId):
13868 amit.gupta 118
        try:
14013 amit.gupta 119
            string1 = req.stream.read()
14014 amit.gupta 120
            req_obj = urlparse.parse_qs(string1)
14013 amit.gupta 121
        except ValueError:
122
            raise falcon.HTTPError(falcon.HTTP_400,
123
                'Malformed JSON',
124
                'Could not decode the request body. The '
125
                'JSON was incorrect.')
126
        try:
13927 amit.gupta 127
            store = main.getStore(req.get_param_as_int("storeId"))
17087 amit.gupta 128
            #print "req_obj",req_obj
16371 amit.gupta 129
            result = store.trackOrdersForUser(int(userId),req_obj['url'][0],req_obj['html'][0])
130
            resp.body = json.dumps({'result':result}, encoding='utf-8')
15791 manish.sha 131
            '''
132
            elif req.get_param_as_int("storeId") == 7:
133
                if 'myprofile' in req_obj['url'][0]:
134
                    result = store.parseMyProfileForEmailId(int(userId),req_obj['url'][0],req_obj['html'][0])
135
                else:
136
                    result = store.parseMyOrdersForEmailId(int(userId),req_obj['url'][0],req_obj['html'][0])
137
                resp.body = json.dumps({'result':result}, encoding='utf-8')
138
            '''
13927 amit.gupta 139
        except:
16392 amit.gupta 140
            traceback.print_exc()
13927 amit.gupta 141
            resp.body = json.dumps({'result':'PARSE_ERROR'}, encoding='utf-8')
14087 amit.gupta 142
 
13868 amit.gupta 143
 
13939 amit.gupta 144
    def on_get(self, req, resp, userId):
13868 amit.gupta 145
        try:
146
            storeId = req.get_param_as_int("storeId")
13939 amit.gupta 147
            result = main.getStore(storeId).getTrackingUrls(int(userId))
13887 amit.gupta 148
            resp.body = json.dumps({'result':result}, encoding='utf-8')
13868 amit.gupta 149
        except ValueError:
150
            raise falcon.HTTPError(falcon.HTTP_400,
151
                'Malformed JSON',
152
                'Could not decode the request body. The '
153
                'JSON was incorrect.')
154
 
13927 amit.gupta 155
class Refunds():
13990 amit.gupta 156
    def on_get(self, req, resp, userId):
13927 amit.gupta 157
        try:
158
            page = req.get_param_as_int("page")
159
            window = req.get_param_as_int("window")
13990 amit.gupta 160
            result = Mongo.getRefunds(int(userId),page,window)
13927 amit.gupta 161
            resp.body = json.dumps(result, encoding='utf-8')
162
        except ValueError:
163
            raise falcon.HTTPError(falcon.HTTP_400,
164
                'Malformed JSON',
165
                'Could not decode the request body. The '
166
                'JSON was incorrect.')
167
 
14427 amit.gupta 168
class Transactions():
169
    def on_get(self, req, resp):
170
        try:
171
            page = req.get_param_as_int("page")
172
            window = req.get_param_as_int("window")
14725 amit.gupta 173
            user = req.get_param("user")
174
            status = req.get_param("status")
15731 amit.gupta 175
            source = req.get_param("source")
14725 amit.gupta 176
            if user == "" :
177
                user = None
178
            if status == "" :
179
                status = None
15731 amit.gupta 180
            result = Mysql.getOrders(page, window,status,user,source)
14427 amit.gupta 181
            resp.body = result
182
            resp.content_type = 'text/html'
183
        except ValueError:
184
            raise falcon.HTTPError(falcon.HTTP_400,
185
                'Malformed JSON',
186
                'Could not decode the request body. The '
187
                'JSON was incorrect.')
16789 amit.gupta 188
 
189
class Rejects():
190
    def on_get(self, req, resp):
191
        try:
192
            result="""<html><head><title>Upload Rejects</title></head><body>
193
            <h1>Upload rejects</h1>
16799 amit.gupta 194
            <form action="rejects" method="POST" enctype="multipart/form-data">
195
              <input type="file" name="rejects" accept=".xlsx, .xls">
16789 amit.gupta 196
              <input type="submit">
197
            </form>
198
 
199
            </body></html>"""
200
            resp.body = result
201
            resp.content_type = 'text/html'
202
        except ValueError:
203
            raise falcon.HTTPError(falcon.HTTP_400,
204
                'Malformed JSON',
205
                'Could not decode the request body. The '
206
                'JSON was incorrect.')
207
 
208
 
209
    def on_post(self, request, resp):
16829 amit.gupta 210
        res = None
16789 amit.gupta 211
        try:
16814 amit.gupta 212
            boundary = request.content_type.split(";")[1].strip().split("=")[1]
16825 amit.gupta 213
            pdict= {'boundary':boundary}
16802 amit.gupta 214
            filepath = "/tmp/rejectfile"
16806 amit.gupta 215
            with open(filepath, 'wb') as image_file:
216
                while True:
217
                    chunk = request.stream.read(4096)
16826 amit.gupta 218
                    if not chunk:
219
                        break
16825 amit.gupta 220
                    image_file.write(chunk)
16828 amit.gupta 221
            with open(filepath, 'r') as image_file:
16829 amit.gupta 222
                res = cgi.parse_multipart(image_file, pdict)['rejects'][0]
223
            if res:
224
                with open(filepath, 'wb') as image_file:
225
                    image_file.write(res)
16838 amit.gupta 226
                rejectCount = process_rejects(filepath)
16829 amit.gupta 227
                resp.content_type = 'text/html'
228
                resp.body = """
229
                    <html><head><title>Upload Rejects</title></head><body>
230
                <h1>Reject Successful</h1>
231
                <h2> %d orders rejected</h2>
232
 
233
                </body></html>
234
                    """%(rejectCount) 
16789 amit.gupta 235
        except ValueError:
236
            raise falcon.HTTPError(falcon.HTTP_400,
237
                'Malformed JSON',
238
                'Could not decode the request body. The '
239
                'JSON was incorrect.')
15081 amit.gupta 240
 
16789 amit.gupta 241
 
242
def process_rejects(filepath):
16838 amit.gupta 243
    rejectCount = 0
16789 amit.gupta 244
    workbook = xlrd.open_workbook(filepath)
245
    sheet = workbook.sheet_by_index(0)
246
    num_rows = sheet.nrows
247
    for rownum in range(1, num_rows):
248
        try:
16831 amit.gupta 249
            orderId, userId, merchantOrderId, subOrderId  = sheet.row_values(rownum)[0:4]
16838 amit.gupta 250
            rejectCount += Mongo.rejectCashback(int(orderId), subOrderId)
16789 amit.gupta 251
        except:
252
            traceback.print_exc()
16838 amit.gupta 253
    return rejectCount
16789 amit.gupta 254
 
15081 amit.gupta 255
class SnapShot():
256
    def on_get(self, req, resp):
257
        try:
258
            resp.content_type = 'text/html'
259
            user = req.get_param_as_int("user")
260
            file = req.get_param("file") 
261
            if  file is not None:
262
                #fetch the page and return html
263
                with open ("/AmazonTrack/User%d/%s"%(user, file), "r") as myfile:
264
                    resp.body=myfile.read() 
265
            else:
266
                #return user specific urls
267
                resp.body=getUserUrls(user)
268
        except ValueError:
269
            raise falcon.HTTPError(falcon.HTTP_400,
270
                'Malformed JSON',
271
                'Could not decode the request body. The '
272
                'JSON was incorrect.')
273
 
274
def getUserUrls(user):
275
    pass
14427 amit.gupta 276
 
277
class RawHtml():
278
    def on_get(self, req, resp, orderId):
279
        try:
280
            result = Mysql.getOrderHtml(orderId)
15544 amit.gupta 281
            if req.get_param("show") is None:
282
                result = re.subn(r'(src|href|style)=\s?(\'|").*?\2(?s)', '', re.subn(r'<(script|style).*?</\1>(?s)', '', result)[0])[0]
14427 amit.gupta 283
            resp.body = result
284
            resp.content_type = 'text/html'
285
        except ValueError:
286
            raise falcon.HTTPError(falcon.HTTP_400,
287
                'Malformed JSON',
288
                'Could not decode the request body. The '
289
                'JSON was incorrect.')
290
 
13927 amit.gupta 291
class PendingRefunds():
292
    def on_get(self, req, resp,userId):
293
        try:
294
            result = Mongo.getPendingRefunds(int(userId))
295
            resp.body = json.dumps(result, encoding='utf-8')
296
        except ValueError:
297
            raise falcon.HTTPError(falcon.HTTP_400,
298
                'Malformed JSON',
299
                'Could not decode the request body. The '
14671 amit.gupta 300
                'JSON was incorrect.')
301
 
302
class PendingCashBacks():
303
    def on_get(self, req, resp,userId):
304
        try:
305
            result = Mongo.getPendingCashbacks(int(userId))
306
            resp.body = json.dumps(result, encoding='utf-8')
307
        except ValueError:
308
            raise falcon.HTTPError(falcon.HTTP_400,
309
                'Malformed JSON',
310
                'Could not decode the request body. The '
16789 amit.gupta 311
                'JSON was incorrect.')
312
 
313
def tprint(*msg):
314
    print datetime.now(), "-", msg