Subversion Repositories SmartDukaan

Rev

Rev 16791 | Rev 16794 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

'''
Created on Feb 12, 2015

@author: amit
'''
from dtr import main
from datetime import datetime
from dtr.main import tprint
from dtr.storage import Mongo, Mysql
from dtr.utils import utils
import falcon
import json
import os.path
import re
import traceback
import urlparse
import xlrd
class StoreOrder():
    def on_post(self, req, resp):
        
        try:
            string1 = req.stream.read()
            req_json = json.loads(string1, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')
            
        store = main.getStore(int(req_json['sourceId']))
        result = store.parseOrderRawHtml(int(req_json['orderId']), req_json['subTagId'], int(req_json['userId']), req_json['rawHtml'], req_json['orderSuccessUrl'])
        resp.body = json.dumps(result, encoding='utf-8')
    
    def on_get(self, req, resp, userId):
        page = req.get_param_as_int("page")
        window = req.get_param_as_int("window")
        string1 = req.get_param("searchMap")
        orderType = req.get_param("type")
        searchMap={}
        if orderType is not None and orderType != "":
            if orderType in ['needamazonorderdetail','needamazonordertrack']:
                searchMap={"$or":[{"subOrders.closed":False,"subOrders.trackingUrl":{"$exists":False},"subOrders.trackAfter":{"$lt":utils.getCurrTimeStamp()}}, {"status":"html_required"}], "storeId":1}
        elif string1 is not None and string1 != "":
            try:
                searchMap = json.loads(string1, encoding='utf-8')
            except:
                raise falcon.HTTPError(falcon.HTTP_400,
                    'Malformed JSON',
                    'Could not decode the request body. The '
                    'JSON was incorrect.')
        result = Mongo.getMerchantOrdersByUser(int(userId), page, window, searchMap)
        resp.body = json.dumps(result, encoding='utf-8')
        
class Orders():
    def on_get(self, req, resp):
        page = req.get_param_as_int("page")
        window = req.get_param_as_int("window")
        string1 = req.get_param("searchMap")
        searchMap={}
        if string1 is None or string1 == "":
            pass
        else:
            try:
                searchMap = json.loads(string1, encoding='utf-8')
            except:
                raise falcon.HTTPError(falcon.HTTP_400,
                    'Malformed JSON',
                    'Could not decode the request body. The '
                    'JSON was incorrect.')
        result = Mongo.getMerchantOrdersByUser(None, page, window, searchMap)
        resp.body = json.dumps(result, encoding='utf-8')
        
class Track():
    def on_post(self, req, resp, userId):
        try:
            string1 = req.stream.read()
            req_obj = urlparse.parse_qs(string1)
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')
        try:
            store = main.getStore(req.get_param_as_int("storeId"))
            print "req_obj",req_obj
            result = store.trackOrdersForUser(int(userId),req_obj['url'][0],req_obj['html'][0])
            resp.body = json.dumps({'result':result}, encoding='utf-8')
            '''
            elif req.get_param_as_int("storeId") == 7:
                if 'myprofile' in req_obj['url'][0]:
                    result = store.parseMyProfileForEmailId(int(userId),req_obj['url'][0],req_obj['html'][0])
                else:
                    result = store.parseMyOrdersForEmailId(int(userId),req_obj['url'][0],req_obj['html'][0])
                resp.body = json.dumps({'result':result}, encoding='utf-8')
            '''
        except:
            traceback.print_exc()
            resp.body = json.dumps({'result':'PARSE_ERROR'}, encoding='utf-8')
            
    
    def on_get(self, req, resp, userId):
        try:
            storeId = req.get_param_as_int("storeId")
            result = main.getStore(storeId).getTrackingUrls(int(userId))
            resp.body = json.dumps({'result':result}, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')
        
class Refunds():
    def on_get(self, req, resp, userId):
        try:
            page = req.get_param_as_int("page")
            window = req.get_param_as_int("window")
            result = Mongo.getRefunds(int(userId),page,window)
            resp.body = json.dumps(result, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')
        
class Transactions():
    def on_get(self, req, resp):
        try:
            page = req.get_param_as_int("page")
            window = req.get_param_as_int("window")
            user = req.get_param("user")
            status = req.get_param("status")
            source = req.get_param("source")
            if user == "" :
                user = None
            if status == "" :
                status = None
            result = Mysql.getOrders(page, window,status,user,source)
            resp.body = result
            resp.content_type = 'text/html'
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')
            
class Rejects():
    def on_get(self, req, resp):
        try:
            result="""<html><head><title>Upload Rejects</title></head><body>
            <h1>Upload rejects</h1>
            <form action="rejects" method="POST">
              <input type="file" name="rejects" accept="application/*">
              <input type="submit">
            </form>
   
            </body></html>"""
            resp.body = result
            resp.content_type = 'text/html'
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')
            
            
    def on_post(self, request, resp):
        try:
            uploadfile = request.files.get('rejects')
            ext = uploadfile.filename.split(".")[1]
            if ext not in ['.xls','.xlsx']:
                raise falcon.HTTPError(falcon.HTTP_400, 'Invalid Extension use xls/xlsx', 'Invalid Extension use xls/xlsx')
            
            filepath = '/tmp/'+uploadfile.filename
            uploadfile.save(filepath)
            rejectCount = process_rejects(filepath) #this function is not yet implemented
            
            resp = """
                <html><head><title>Upload Rejects</title></head><body>
            <h1>Reject Successful</h1>
            <h2> %d orders rejected</h2>
   
            </body></html>
                """%(rejectCount) 
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')


def process_rejects(filepath):
    workbook = xlrd.open_workbook(filepath)
    sheet = workbook.sheet_by_index(0)
    num_rows = sheet.nrows
    for rownum in range(1, num_rows):
        try:
            orderId, userId, merchantOrderId, subOrderId  = sheet.row_values(rownum)[0:3]
            Mongo.rejectCashback(orderId, subOrderId)
        except:
            tprint("Could not reject " + str("orderId " + orderId + ", userId " + userId + ", merchantOrderId " + merchantOrderId + ", subOrderId "+ subOrderId))
            traceback.print_exc()
              

class SnapShot():
    def on_get(self, req, resp):
        try:
            resp.content_type = 'text/html'
            user = req.get_param_as_int("user")
            file = req.get_param("file") 
            if  file is not None:
                #fetch the page and return html
                with open ("/AmazonTrack/User%d/%s"%(user, file), "r") as myfile:
                    resp.body=myfile.read() 
            else:
                #return user specific urls
                resp.body=getUserUrls(user)
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')
            
def getUserUrls(user):
    pass
        
class RawHtml():
    def on_get(self, req, resp, orderId):
        try:
            result = Mysql.getOrderHtml(orderId)
            if req.get_param("show") is None:
                result = re.subn(r'(src|href|style)=\s?(\'|").*?\2(?s)', '', re.subn(r'<(script|style).*?</\1>(?s)', '', result)[0])[0]
            resp.body = result
            resp.content_type = 'text/html'
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')
        
class PendingRefunds():
    def on_get(self, req, resp,userId):
        try:
            result = Mongo.getPendingRefunds(int(userId))
            resp.body = json.dumps(result, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')
        
class PendingCashBacks():
    def on_get(self, req, resp,userId):
        try:
            result = Mongo.getPendingCashbacks(int(userId))
            resp.body = json.dumps(result, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')
            
def tprint(*msg):
    print datetime.now(), "-", msg