Subversion Repositories SmartDukaan

Rev

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