Subversion Repositories SmartDukaan

Rev

Rev 17087 | Rev 17282 | 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):
85
        try:
86
            filter_type = req.get_param_as_int("type")
87
            result = order_fliters.get(filter_type)
88
            resp.body = json.dumps(result, encoding='utf-8')
89
        except:
90
            raise falcon.HTTPError(falcon.HTTP_400,
91
                'Malformed JSON',
92
                'Could not decode the request body. The '
93
                'JSON was incorrect.')
94
 
95
 
14352 amit.gupta 96
class Orders():
97
    def on_get(self, req, resp):
98
        page = req.get_param_as_int("page")
99
        window = req.get_param_as_int("window")
100
        string1 = req.get_param("searchMap")
101
        searchMap={}
102
        if string1 is None or string1 == "":
103
            pass
104
        else:
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"))
17087 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.')
300
 
301
class PendingCashBacks():
302
    def on_get(self, req, resp,userId):
303
        try:
304
            result = Mongo.getPendingCashbacks(int(userId))
305
            resp.body = json.dumps(result, encoding='utf-8')
306
        except ValueError:
307
            raise falcon.HTTPError(falcon.HTTP_400,
308
                'Malformed JSON',
309
                'Could not decode the request body. The '
16789 amit.gupta 310
                'JSON was incorrect.')
311
 
312
def tprint(*msg):
313
    print datetime.now(), "-", msg