Subversion Repositories SmartDukaan

Rev

Rev 13662 | Rev 13678 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
13569 amit.gupta 1
'''
2
Created on Jan 15, 2015
3
 
4
@author: amit
5
'''
6
from pymongo.mongo_client import MongoClient
7
import importlib
13662 amit.gupta 8
import json
9
import math
13569 amit.gupta 10
import mechanize
13631 amit.gupta 11
import traceback
13662 amit.gupta 12
import urllib
13
import urllib2
13582 amit.gupta 14
sourceMap = {1:"amazon", 2:"flipkart", 3:"snapdeal", 4:"spice", 5:"homeshop18"}
13662 amit.gupta 15
headers = { 
16
           'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
17
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
18
            'Accept-Language' : 'en-US,en;q=0.8',                     
19
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
20
        }
21
CASHBACK_URL = 'http://api.profittill.com/cashbacks/index/%s/%s'
13677 amit.gupta 22
USER_LOOKUP_URL = 'http://api.profittill.com/user_account/saholic/%s'
23
WALLET_CREDIT_URL = 'http://www.shop2020.in:8080/mobileapi/wallet?userId=%s&isLoggedIn=true'
13569 amit.gupta 24
 
25
def getStore(source_id):
26
    #module = sourceMap[source_id]
27
    store = Store(source_id)
13631 amit.gupta 28
    try:
29
        module = importlib.import_module("dtr.sources." + sourceMap[source_id])
30
        store = getattr(module, "Store")(source_id)
31
        return store
32
    except:
33
        traceback.print_exc()
34
        return None
13569 amit.gupta 35
 
36
class ScrapeException(Exception):
37
    """Exception raised for errors in the input.
38
 
39
    Attributes:
40
        expr -- input expression in which the error occurred
41
        msg  -- explanation of the error
42
    """
43
 
44
    def __init__(self, expr, msg):
45
        self.expr = expr
46
        self.msg = msg
47
 
48
class ParseException(Exception):
49
    """Exception raised for errors in the input.
50
 
51
    Attributes:
52
        expr -- input expression in which the error occurred
53
        msg  -- explanation of the error
54
    """
55
 
56
    def __init__(self, expr, msg):
57
        self.expr = expr
58
        self.msg = msg
59
 
13677 amit.gupta 60
client = MongoClient('mongodb://localhost:27017/') 
61
 
13569 amit.gupta 62
class Store(object):
63
 
64
    ORDER_PLACED = 'Order Placed'
65
    ORDER_DELIVERED = 'Delivered'
66
    ORDER_SHIPPED = 'Shipped' #Lets see if we can make use of it
67
    ORDER_CANCELLED = 'Cancelled'
68
 
13662 amit.gupta 69
    CB_INIT = 'Waiting Confirmation'
13610 amit.gupta 70
    CB_PENDING = 'Pending'
71
    CB_CREDITED = 'Credited to wallet'
72
    CB_NA = 'Not Applicable'
73
    CB_APPROVED = 'Approved'
74
    CB_CANCELLED = 'Cancelled'
13569 amit.gupta 75
 
13662 amit.gupta 76
    CONF_CB_SELLING_PRICE = 0
77
    CONF_CB_DISCOUNTED_PRICE = 1
13610 amit.gupta 78
 
13569 amit.gupta 79
    def __init__(self, store_id):
13662 amit.gupta 80
        self.db = client.Dtr
13569 amit.gupta 81
        self.store_id = store_id
13576 amit.gupta 82
        self.store_name = sourceMap[store_id]
13569 amit.gupta 83
 
13662 amit.gupta 84
    '''
85
    To Settle payback for respective stores.
86
    Also ensures that settlement happens only for approved orders
87
    '''
13569 amit.gupta 88
 
89
    def getName(self):
90
        raise NotImplementedError
91
 
92
    def scrapeAffiliate(self, startDate=None, endDate=None):
93
        raise NotImplementedError
94
 
95
    def saveToAffiliate(self, offers):
96
        raise NotImplementedError
97
 
98
    def scrapeStoreOrders(self,):
99
        raise NotImplementedError
13610 amit.gupta 100
 
13662 amit.gupta 101
 
102
    def getCashbackAmount(self, productCode, amount):
103
        alagvar = CASHBACK_URL % (self.store_id,productCode)
104
        filehandle = urllib2.Request(alagvar,headers=headers)
105
        x= urllib2.urlopen(filehandle)
106
        map = json.loads(x.read())
107
        if map['cashback']==0:
108
            return 0
109
        else:
110
            if map['cashback_type'] == 'percentage':
111
                return math.floor((amount * map['cashback'])/100)
112
            else:
113
                return map['cashback']
114
 
13569 amit.gupta 115
    '''
116
    Parses the order for specific store
117
 
118
    order id, total amount, created on(now() if could not parse
119
    suborder id, title, quantity, unit price, expected delivery date,
120
    status (default would be Order placed)
121
 
122
    once products are identified, each suborder can then be updated
123
    with respective cashback.
124
 
125
    Possible fields to display for Not yet delivered orders are 
126
    Product/Quantity/Amount/Store/CashbackAmount/OrderDate/ExpectedDelivery/OrderStaus/DetailedStatus/CashbackStatus
127
    No need to show cancelled orders.
13610 amit.gupta 128
    CashbackStatus - NotApplicable/Pending/Approved/Cancelled/CreditedToWallet
13569 amit.gupta 129
    OrderStatus - Placed/Cancelled/Delivered
130
    '''
13576 amit.gupta 131
    def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
13569 amit.gupta 132
 
133
        pass
134
 
13662 amit.gupta 135
def main():
13677 amit.gupta 136
    #store = getStore(3)
137
    #print store.getCashbackAmount('864683341', 100)
138
    data = urllib.urlencode({'orderId':6000, 'amount':200})
139
    request = urllib2.Request(WALLET_CREDIT_URL % (483649), headers=headers)
140
    response = urllib2.urlopen(request, data)
141
    print response.read()
13662 amit.gupta 142
 
13569 amit.gupta 143
if __name__ == '__main__':
13662 amit.gupta 144
    main()
13569 amit.gupta 145
 
146
 
13677 amit.gupta 147
def settlePayBack():
148
        orders = client.Dtr.merchantOrder.find({'subOrders.cashBackStatus':Store.CB_APPROVED}, {'userId':1, 'orderId': 1, 'subOrders.cashBackAmount':1, 'subOrders.merchantSubOrderId':1})
149
        for order in orders:
150
            print order
151
            for subOrder in order.get('subOrders'):
152
                if subOrder.get('cashBackAmount') is not None:
153
                    if __refundToWallet(order['userId'], order['orderId'], subOrder.get('cashBackAmount')):
154
                        client.Dtr.merchantOrder.update({'orderId':order['orderId'], 'subOrders.merchantSubOrderId':subOrder['merchantSubOrderId']},{'subOrders.$.cashBackStatus':Store.CB_CREDITED})
155
                        print "Settled order-", order['orderId'], "Sub Order-", subOrder['merchantSubOrderId'], "for amount", subOrder['cashBackAmount']
156
 
157
def __refundToWallet(self, userId, orderId, amount):
158
    userLookupRequest = urllib2.Request(USER_LOOKUP_URL %(userId), headers=headers)
159
    response = urllib2.urlopen(userLookupRequest).read()
160
    saholicUserId = json.loads(response)['account_id']
161
 
162
    request = urllib2.Request(WALLET_CREDIT_URL % (saholicUserId), headers=headers)
163
    data = urllib.urlencode({'orderId':orderId, 'amount':amount})
164
    response = urllib2.urlopen(request, data)
165
 
166
    return json.loads(response.read())['credited']
167
 
13569 amit.gupta 168
def getBrowserObject():
169
    import cookielib
170
    br = mechanize.Browser(factory=mechanize.RobustFactory())
171
    cj = cookielib.LWPCookieJar()
172
    br.set_cookiejar(cj)
173
    br.set_handle_equiv(True)
174
    br.set_handle_redirect(True)
175
    br.set_handle_referer(True)
176
    br.set_handle_robots(False)
177
    br.set_debug_http(False)
178
    br.set_debug_redirects(False)
179
    br.set_debug_responses(False)
180
 
181
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
182
 
183
    br.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'),
184
                     ('Accept', 'text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8'),
185
                     ('Accept-Encoding', 'gzip,deflate,sdch'),                  
186
                     ('Accept-Language', 'en-US,en;q=0.8'),                     
187
                     ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3')]
13677 amit.gupta 188
    return br
189