Subversion Repositories SmartDukaan

Rev

Rev 18691 | Blame | Compare with Previous | Last modification | View Log | RSS feed

'''
Created on Feb 12, 2015

@author: amit
'''
from datetime import datetime
from dtr import main
from dtr.main import tprint
from dtr.storage import Mongo, Mysql
from dtr.utils import utils
from dtr.utils.utils import find_between
import cgi
import falcon
import json
import os.path
import re
import traceback
import urlparse
import xlrd

order_fliters = {
                 "monitor":{
                    "trackingurlmissing":  {
                                                "displaylabel":"Tracking Url Missing",
                                                "query":{"subOrders.closed":False,"subOrders.trackingUrl":{"$exists":False}, "subOrders.trackMissing":True}
                                            }, 
                     "orderuntrackable":    {
                                                "displaylabel":"Untrackable Orders",   
                                                "query":{"trackError":True, "storeId":1, "subOrders.closed":False}
                                            },
                     "prematurelyclosed" :  {
                                                "displaylabel": "Prematurely Closed Orders",
                                                "query":{"closed":True, "subOrders.closed":False}
                                            },
                     
                     "parsefailed":         {   
                                                "displaylabel": "Failed to Parse Orders",
                                                "query":{"subOrders":{"$exists": False}, "status":"parse_failed"}
                                            },
                     "creditororders":     {
                                                "displaylabel": "Orders Created using Credit Option",
                                                "query":{"storeId": 4,"payment_option":{"$exists":True}}
                                            }
                     },
                 
                 "user":{}
                 
                 }
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:
                traceback.print_exc()
                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 OrderFilters():
    def on_get(self, req, resp):
        filter_type = req.get_param("type")
        result = order_fliters.get(filter_type)
        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")
        orderFilter = req.get_param("filter")
        filterType = req.get_param("filtertype")
        searchMap={}
        if filter and filterType:
            try:
                searchMap = order_fliters[filterType][orderFilter]['query']
            except:
                pass
        elif 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(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"))
            result = store.trackOrdersForUser(int(userId),req_obj['url'][0],req_obj['html'][0])
            print result
            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" enctype="multipart/form-data">
              <input type="file" name="rejects" accept=".xlsx, .xls">
              <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):
        res = None
        try:
            boundary = request.content_type.split(";")[1].strip().split("=")[1]
            pdict= {'boundary':boundary}
            filepath = "/tmp/rejectfile"
            with open(filepath, 'wb') as image_file:
                while True:
                    chunk = request.stream.read(4096)
                    if not chunk:
                        break
                    image_file.write(chunk)
            with open(filepath, 'r') as image_file:
                res = cgi.parse_multipart(image_file, pdict)['rejects'][0]
            if res:
                with open(filepath, 'wb') as image_file:
                    image_file.write(res)
                rejectCount = process_rejects(filepath)
                resp.content_type = 'text/html'
                resp.body = """
                    <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):
    rejectCount = 0
    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:4]
            rejectCount += Mongo.rejectCashback(int(orderId), subOrderId)
        except:
            traceback.print_exc()
    return rejectCount

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 AmazonSummary():
    def on_get(self, req, resp,userId):
        try:
            result = getSummary(userId, req)
            if result:
                resp.body = result
            else:
                resp.body = ''
            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 getSummary(userId, req):
    directory = "/AmazonTrack/User" + userId
    date1 = datetime(2015,1,1)
    finalFile = None
    str1 = None
    try:
        for file in os.listdir(directory):
            if file.startswith("orderSummary"):
                date2 = datetime.strptime("2015-" + file.split("orderSummary")[1].split(":")[0], "%Y-%d-%m")
                if date2 > date1:
                    date1 = date2
                    finalFile=file
        result = open(directory + "/" + finalFile).read()
        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]

        return result
    except:
        print "Missing directory"
    return str1
        
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