Subversion Repositories SmartDukaan

Rev

Rev 16814 | Rev 16817 | 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
13804 amit.gupta 18
class StoreOrder():
19
    def on_post(self, req, resp):
20
 
21
        try:
22
            string1 = req.stream.read()
23
            req_json = json.loads(string1, encoding='utf-8')
24
        except ValueError:
25
            raise falcon.HTTPError(falcon.HTTP_400,
26
                'Malformed JSON',
27
                'Could not decode the request body. The '
28
                'JSON was incorrect.')
29
 
30
        store = main.getStore(int(req_json['sourceId']))
31
        result = store.parseOrderRawHtml(int(req_json['orderId']), req_json['subTagId'], int(req_json['userId']), req_json['rawHtml'], req_json['orderSuccessUrl'])
32
        resp.body = json.dumps(result, encoding='utf-8')
33
 
34
    def on_get(self, req, resp, userId):
35
        page = req.get_param_as_int("page")
36
        window = req.get_param_as_int("window")
14003 amit.gupta 37
        string1 = req.get_param("searchMap")
15821 amit.gupta 38
        orderType = req.get_param("type")
14004 amit.gupta 39
        searchMap={}
15821 amit.gupta 40
        if orderType is not None and orderType != "":
15822 amit.gupta 41
            if orderType in ['needamazonorderdetail','needamazonordertrack']:
16167 amit.gupta 42
                searchMap={"$or":[{"subOrders.closed":False,"subOrders.trackingUrl":{"$exists":False},"subOrders.trackAfter":{"$lt":utils.getCurrTimeStamp()}}, {"status":"html_required"}], "storeId":1}
15821 amit.gupta 43
        elif string1 is not None and string1 != "":
14006 amit.gupta 44
            try:
14007 amit.gupta 45
                searchMap = json.loads(string1, encoding='utf-8')
14006 amit.gupta 46
            except:
47
                raise falcon.HTTPError(falcon.HTTP_400,
48
                    'Malformed JSON',
49
                    'Could not decode the request body. The '
50
                    'JSON was incorrect.')
14003 amit.gupta 51
        result = Mongo.getMerchantOrdersByUser(int(userId), page, window, searchMap)
13868 amit.gupta 52
        resp.body = json.dumps(result, encoding='utf-8')
53
 
14352 amit.gupta 54
class Orders():
55
    def on_get(self, req, resp):
56
        page = req.get_param_as_int("page")
57
        window = req.get_param_as_int("window")
58
        string1 = req.get_param("searchMap")
59
        searchMap={}
60
        if string1 is None or string1 == "":
61
            pass
62
        else:
63
            try:
64
                searchMap = json.loads(string1, encoding='utf-8')
65
            except:
66
                raise falcon.HTTPError(falcon.HTTP_400,
67
                    'Malformed JSON',
68
                    'Could not decode the request body. The '
69
                    'JSON was incorrect.')
70
        result = Mongo.getMerchantOrdersByUser(None, page, window, searchMap)
71
        resp.body = json.dumps(result, encoding='utf-8')
72
 
13868 amit.gupta 73
class Track():
13939 amit.gupta 74
    def on_post(self, req, resp, userId):
13868 amit.gupta 75
        try:
14013 amit.gupta 76
            string1 = req.stream.read()
14014 amit.gupta 77
            req_obj = urlparse.parse_qs(string1)
14013 amit.gupta 78
        except ValueError:
79
            raise falcon.HTTPError(falcon.HTTP_400,
80
                'Malformed JSON',
81
                'Could not decode the request body. The '
82
                'JSON was incorrect.')
83
        try:
13927 amit.gupta 84
            store = main.getStore(req.get_param_as_int("storeId"))
16393 amit.gupta 85
            print "req_obj",req_obj
16371 amit.gupta 86
            result = store.trackOrdersForUser(int(userId),req_obj['url'][0],req_obj['html'][0])
87
            resp.body = json.dumps({'result':result}, encoding='utf-8')
15791 manish.sha 88
            '''
89
            elif req.get_param_as_int("storeId") == 7:
90
                if 'myprofile' in req_obj['url'][0]:
91
                    result = store.parseMyProfileForEmailId(int(userId),req_obj['url'][0],req_obj['html'][0])
92
                else:
93
                    result = store.parseMyOrdersForEmailId(int(userId),req_obj['url'][0],req_obj['html'][0])
94
                resp.body = json.dumps({'result':result}, encoding='utf-8')
95
            '''
13927 amit.gupta 96
        except:
16392 amit.gupta 97
            traceback.print_exc()
13927 amit.gupta 98
            resp.body = json.dumps({'result':'PARSE_ERROR'}, encoding='utf-8')
14087 amit.gupta 99
 
13868 amit.gupta 100
 
13939 amit.gupta 101
    def on_get(self, req, resp, userId):
13868 amit.gupta 102
        try:
103
            storeId = req.get_param_as_int("storeId")
13939 amit.gupta 104
            result = main.getStore(storeId).getTrackingUrls(int(userId))
13887 amit.gupta 105
            resp.body = json.dumps({'result':result}, encoding='utf-8')
13868 amit.gupta 106
        except ValueError:
107
            raise falcon.HTTPError(falcon.HTTP_400,
108
                'Malformed JSON',
109
                'Could not decode the request body. The '
110
                'JSON was incorrect.')
111
 
13927 amit.gupta 112
class Refunds():
13990 amit.gupta 113
    def on_get(self, req, resp, userId):
13927 amit.gupta 114
        try:
115
            page = req.get_param_as_int("page")
116
            window = req.get_param_as_int("window")
13990 amit.gupta 117
            result = Mongo.getRefunds(int(userId),page,window)
13927 amit.gupta 118
            resp.body = json.dumps(result, encoding='utf-8')
119
        except ValueError:
120
            raise falcon.HTTPError(falcon.HTTP_400,
121
                'Malformed JSON',
122
                'Could not decode the request body. The '
123
                'JSON was incorrect.')
124
 
14427 amit.gupta 125
class Transactions():
126
    def on_get(self, req, resp):
127
        try:
128
            page = req.get_param_as_int("page")
129
            window = req.get_param_as_int("window")
14725 amit.gupta 130
            user = req.get_param("user")
131
            status = req.get_param("status")
15731 amit.gupta 132
            source = req.get_param("source")
14725 amit.gupta 133
            if user == "" :
134
                user = None
135
            if status == "" :
136
                status = None
15731 amit.gupta 137
            result = Mysql.getOrders(page, window,status,user,source)
14427 amit.gupta 138
            resp.body = result
139
            resp.content_type = 'text/html'
140
        except ValueError:
141
            raise falcon.HTTPError(falcon.HTTP_400,
142
                'Malformed JSON',
143
                'Could not decode the request body. The '
144
                'JSON was incorrect.')
16789 amit.gupta 145
 
146
class Rejects():
147
    def on_get(self, req, resp):
148
        try:
149
            result="""<html><head><title>Upload Rejects</title></head><body>
150
            <h1>Upload rejects</h1>
16799 amit.gupta 151
            <form action="rejects" method="POST" enctype="multipart/form-data">
152
              <input type="file" name="rejects" accept=".xlsx, .xls">
16789 amit.gupta 153
              <input type="submit">
154
            </form>
155
 
156
            </body></html>"""
157
            resp.body = result
158
            resp.content_type = 'text/html'
159
        except ValueError:
160
            raise falcon.HTTPError(falcon.HTTP_400,
161
                'Malformed JSON',
162
                'Could not decode the request body. The '
163
                'JSON was incorrect.')
164
 
165
 
166
    def on_post(self, request, resp):
167
        try:
16814 amit.gupta 168
            boundary = request.content_type.split(";")[1].strip().split("=")[1]
169
            chunks = []
16802 amit.gupta 170
            filepath = "/tmp/rejectfile"
16806 amit.gupta 171
            with open(filepath, 'wb') as image_file:
172
                while True:
173
                    chunk = request.stream.read(4096)
174
                    if not chunk:
175
                        break
16814 amit.gupta 176
                    chunks.append(chunk) 
177
 
178
                chunk = "".join(chunks)
16815 amit.gupta 179
                print "Chunk1"
180
                print chunk
16814 amit.gupta 181
                chunk = utils.find_between(chunk, boundary, boundary)
16815 amit.gupta 182
                print "Chunk2 after boundary removed"
183
                print chunk
16814 amit.gupta 184
                chunk = chunk.split("\n\n")[1]    
185
                image_file.write(chunk)
16815 amit.gupta 186
                print "Final chunk"
16814 amit.gupta 187
                print chunk
16805 amit.gupta 188
 
16815 amit.gupta 189
            #rejectCount = process_rejects(filepath) #this function is not yet implemented
190
            rejectCount = 1
16802 amit.gupta 191
            resp.body = """
16789 amit.gupta 192
                <html><head><title>Upload Rejects</title></head><body>
193
            <h1>Reject Successful</h1>
194
            <h2> %d orders rejected</h2>
195
 
196
            </body></html>
197
                """%(rejectCount) 
198
        except ValueError:
199
            raise falcon.HTTPError(falcon.HTTP_400,
200
                'Malformed JSON',
201
                'Could not decode the request body. The '
202
                'JSON was incorrect.')
15081 amit.gupta 203
 
16789 amit.gupta 204
 
205
def process_rejects(filepath):
206
    workbook = xlrd.open_workbook(filepath)
207
    sheet = workbook.sheet_by_index(0)
208
    num_rows = sheet.nrows
209
    for rownum in range(1, num_rows):
210
        try:
211
            orderId, userId, merchantOrderId, subOrderId  = sheet.row_values(rownum)[0:3]
212
            Mongo.rejectCashback(orderId, subOrderId)
213
        except:
214
            tprint("Could not reject " + str("orderId " + orderId + ", userId " + userId + ", merchantOrderId " + merchantOrderId + ", subOrderId "+ subOrderId))
215
            traceback.print_exc()
216
 
217
 
15081 amit.gupta 218
class SnapShot():
219
    def on_get(self, req, resp):
220
        try:
221
            resp.content_type = 'text/html'
222
            user = req.get_param_as_int("user")
223
            file = req.get_param("file") 
224
            if  file is not None:
225
                #fetch the page and return html
226
                with open ("/AmazonTrack/User%d/%s"%(user, file), "r") as myfile:
227
                    resp.body=myfile.read() 
228
            else:
229
                #return user specific urls
230
                resp.body=getUserUrls(user)
231
        except ValueError:
232
            raise falcon.HTTPError(falcon.HTTP_400,
233
                'Malformed JSON',
234
                'Could not decode the request body. The '
235
                'JSON was incorrect.')
236
 
237
def getUserUrls(user):
238
    pass
14427 amit.gupta 239
 
240
class RawHtml():
241
    def on_get(self, req, resp, orderId):
242
        try:
243
            result = Mysql.getOrderHtml(orderId)
15544 amit.gupta 244
            if req.get_param("show") is None:
245
                result = re.subn(r'(src|href|style)=\s?(\'|").*?\2(?s)', '', re.subn(r'<(script|style).*?</\1>(?s)', '', result)[0])[0]
14427 amit.gupta 246
            resp.body = result
247
            resp.content_type = 'text/html'
248
        except ValueError:
249
            raise falcon.HTTPError(falcon.HTTP_400,
250
                'Malformed JSON',
251
                'Could not decode the request body. The '
252
                'JSON was incorrect.')
253
 
13927 amit.gupta 254
class PendingRefunds():
255
    def on_get(self, req, resp,userId):
256
        try:
257
            result = Mongo.getPendingRefunds(int(userId))
258
            resp.body = json.dumps(result, encoding='utf-8')
259
        except ValueError:
260
            raise falcon.HTTPError(falcon.HTTP_400,
261
                'Malformed JSON',
262
                'Could not decode the request body. The '
14671 amit.gupta 263
                'JSON was incorrect.')
264
 
265
class PendingCashBacks():
266
    def on_get(self, req, resp,userId):
267
        try:
268
            result = Mongo.getPendingCashbacks(int(userId))
269
            resp.body = json.dumps(result, encoding='utf-8')
270
        except ValueError:
271
            raise falcon.HTTPError(falcon.HTTP_400,
272
                'Malformed JSON',
273
                'Could not decode the request body. The '
16789 amit.gupta 274
                'JSON was incorrect.')
275
 
276
def tprint(*msg):
277
    print datetime.now(), "-", msg