Subversion Repositories SmartDukaan

Rev

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