Subversion Repositories SmartDukaan

Rev

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