Subversion Repositories SmartDukaan

Rev

Rev 13634 | Rev 13680 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 13634 Rev 13662
Line 3... Line 3...
3
 
3
 
4
@author: amit
4
@author: amit
5
'''
5
'''
6
from BeautifulSoup import BeautifulSoup
6
from BeautifulSoup import BeautifulSoup
7
from bson.binary import Binary
7
from bson.binary import Binary
-
 
8
from datetime import datetime, date
8
from dtr import main
9
from dtr import main
9
from dtr.dao import AffiliateInfo, Order, SubOrder
10
from dtr.dao import AffiliateInfo, Order, SubOrder
10
from dtr.main import getBrowserObject, ScrapeException, getStore, ParseException
11
from dtr.main import getBrowserObject, ScrapeException, getStore, ParseException, Store as MStore
-
 
12
from pprint import pprint
11
from pymongo import MongoClient
13
from pymongo import MongoClient
12
import datetime
-
 
13
import json
14
import json
14
import pymongo
15
import pymongo
15
import re
16
import re
16
import urllib
-
 
17
import traceback
17
import traceback
-
 
18
import urllib
18
 
19
 
19
from pprint import pprint
-
 
20
USERNAME='saholic1@gmail.com'
20
USERNAME='saholic1@gmail.com'
21
PASSWORD='spice@2020'
21
PASSWORD='spice@2020'
22
AFFILIATE_URL='http://affiliate.snapdeal.com'
22
AFFILIATE_URL='http://affiliate.snapdeal.com'
23
POST_URL='https://api-p03.hasoffers.com/v3/Affiliate_Report.json'
23
POST_URL='https://api-p03.hasoffers.com/v3/Affiliate_Report.json'
24
ORDER_TRACK_URL='https://m.snapdeal.com/orderSummary'
24
ORDER_TRACK_URL='https://m.snapdeal.com/orderSummary'
25
CONFIG_URL='http://affiliate.snapdeal.com/publisher/js/config.php'
25
CONFIG_URL='http://affiliate.snapdeal.com/publisher/js/config.php'
26
 
26
 
27
 
-
 
28
class Store(main.Store):
27
class Store(MStore):
29
    
28
    
30
    '''
29
    '''
31
    This is to map order statuses of our system to order statuses of snapdeal.
30
    This is to map order statuses of our system to order statuses of snapdeal.
32
    And our statuses will change accordingly.
31
    And our statuses will change accordingly.
33
    
32
    
34
    '''
33
    '''
35
    OrderStatusMap = {
34
    OrderStatusMap = {
36
                      main.Store.ORDER_PLACED : ['In Progress','N/A'],
35
                      MStore.ORDER_PLACED : ['In Progress','N/A'],
37
                      main.Store.ORDER_DELIVERED : ['Delivered'],
36
                      MStore.ORDER_DELIVERED : ['Delivered'],
38
                      main.Store.ORDER_SHIPPED : ['In Transit'],
37
                      MStore.ORDER_SHIPPED : ['In Transit'],
39
                      main.Store.ORDER_CANCELLED : ['Closed For Vendor Reallocation']
38
                      MStore.ORDER_CANCELLED : ['Closed For Vendor Reallocation', 'Cancelled']
40
                      
39
                      
41
                      }
40
                      }
-
 
41
    
-
 
42
    CONF_CB_AMOUNT = MStore.CONF_CB_DISCOUNTED_PRICE
42
    def __init__(self,store_id):
43
    def __init__(self,store_id):
43
        client = MongoClient('mongodb://localhost:27017/')
-
 
44
        self.db = client.Dtr
-
 
45
        super(Store, self).__init__(store_id)
44
        super(Store, self).__init__(store_id)
46
 
45
 
47
    def getName(self):
46
    def getName(self):
48
        return "snapdeal"
47
        return "snapdeal"
49
    
48
    
Line 58... Line 57...
58
        
57
        
59
        token =  re.findall('"session_token":"(.*?)"', ungzipResponse(response, br), re.IGNORECASE)[0]
58
        token =  re.findall('"session_token":"(.*?)"', ungzipResponse(response, br), re.IGNORECASE)[0]
60
        
59
        
61
        allOffers = self._getAllOffers(br, token)
60
        allOffers = self._getAllOffers(br, token)
62
        
61
        
-
 
62
        allPyOffers = []
-
 
63
        maxSaleDate = self._getLastSaleDate()
-
 
64
        newMaxSaleDate = maxSaleDate
-
 
65
        for offer in allOffers:
63
        allPyOffers = [self.covertToObj(offer).__dict__ for offer in allOffers]
66
            allPyOffers.append(self.covertToObj(offer).__dict__)
-
 
67
            saleDate = datetime.strptime(offer.saleDate,"%Y-%m-%d %H:%M:%S")
-
 
68
            if maxSaleDate < saleDate:
-
 
69
                self._updateOrdersPayBackStatus(offer.subTagId,offer.saleDate)
-
 
70
                if newMaxSaleDate < saleDate:
-
 
71
                    newMaxSaleDate = saleDate
-
 
72
                    
-
 
73
        self._setLastSaleDate(newMaxSaleDate)
-
 
74
        print allPyOffers
64
        self._saveToAffiliate(allPyOffers)
75
        self._saveToAffiliate(allPyOffers)
65
    
76
    
-
 
77
    def _setLastSaleDate(self, saleDate):
-
 
78
        self.db.lastDaySale.update({'storeId':self.store_id}, {'$set':{'saleDate':saleDate}})
66
    
79
    
-
 
80
    def _updateOrdersPayBackStatus(self, subTagId, saleDate):
-
 
81
        self.db.merchantOrder.update({"subTagId":subTagId, "placedOn":saleDate, "subOrders.cashbackStatus":MStore.CB_INIT},
-
 
82
                                              { '$set': { "subOrders.$.cashbackStatus" : MStore.CB_PENDING } })
-
 
83
                         
-
 
84
        
-
 
85
        
-
 
86
    def _getLastSaleDate(self,):
-
 
87
        lastDaySaleObj = self.db.lastDaySale.find_one({"storeId":self.store_id})
-
 
88
        if lastDaySaleObj is None:
-
 
89
            return datetime.min
-
 
90
        
-
 
91
        
67
    def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
92
    def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
68
        try:
93
        try:
69
            br = getBrowserObject()
94
            br = getBrowserObject()
70
            url = ORDER_TRACK_URL + re.findall('.*(\?.*?)$', orderSuccessUrl,re.IGNORECASE)[0]
95
            url = ORDER_TRACK_URL + re.findall('.*(\?.*?)$', orderSuccessUrl,re.IGNORECASE)[0]
71
            response = br.open(url)
96
            response = br.open(url)
Line 124... Line 149...
124
                    elif "Subtotal" in subTrString:
149
                    elif "Subtotal" in subTrString:
125
                        if int(qty) > 0:
150
                        if int(qty) > 0:
126
                            amountPaid =   str(int(re.findall(r'\d+', subTrString)[0])/int(qty))
151
                            amountPaid =   str(int(re.findall(r'\d+', subTrString)[0])/int(qty))
127
                        else:
152
                        else:
128
                            amountPaid =   "0"
153
                            amountPaid =   "0"
129
 
-
 
130
                #TODO: cashbackAmount = getCashbackAmount()
154
                if self.CONF_CB_AMOUNT == MStore.CONF_CB_SELLING_PRICE or offerDiscount is None:
131
                cashbackAmount = 0
155
                    amount = int(unitPrice)
132
                cashbackStatus = Store.CB_PENDING
-
 
133
                if cashbackAmount <= 0:
156
                else:
134
                    cashbackStatus = Store.CB_NA
157
                    amount = int(unitPrice) - int(offerDiscount)
135
                        
158
                        
136
                divs = subOrderElement.findAll("div", {"class": "blk lrPad subordrs"})
159
                divs = subOrderElement.findAll("div", {"class": "blk lrPad subordrs"})
137
                if len(divs)<=0:
160
                if len(divs)<=0:
138
                    raise ParseException("subOrder", "Could not Parse suborders for Snapdeal")
161
                    raise ParseException("subOrder", "Could not Parse suborders for Snapdeal")
139
                
162
                
Line 145... Line 168...
145
                    subOrder.amountPaid = amountPaid
168
                    subOrder.amountPaid = amountPaid
146
                    subOrder.deliveryCharges = deliveryCharges
169
                    subOrder.deliveryCharges = deliveryCharges
147
                    subOrder.offerDiscount = offerDiscount
170
                    subOrder.offerDiscount = offerDiscount
148
                    subOrder.unitPrice = unitPrice
171
                    subOrder.unitPrice = unitPrice
149
                    subOrder.productCode = re.findall(r'\d+$', productUrl)[0]
172
                    subOrder.productCode = re.findall(r'\d+$', productUrl)[0]
-
 
173
                    cashbackAmount = self.getCashbackAmount(subOrder.productCode, amount)
-
 
174
                    cashbackStatus = Store.CB_INIT
-
 
175
                    if cashbackAmount <= 0:
-
 
176
                        cashbackStatus = Store.CB_NA
150
                    subOrder.cashBackStatus = cashbackStatus
177
                    subOrder.cashBackStatus = cashbackStatus
151
                    subOrder.cashBackAmount = cashbackAmount
178
                    subOrder.cashBackAmount = cashbackAmount
152
                    
179
                    
153
                    
180
                    
154
                    trackAnchor = div.find("a")   
181
                    trackAnchor = div.find("a")   
Line 184... Line 211...
184
            traceback.print_exc()
211
            traceback.print_exc()
185
        
212
        
186
        return False
213
        return False
187
        #soup = BeautifulSoup(rawHtml,convertEntities=BeautifulSoup.HTML_ENTITIES)
214
        #soup = BeautifulSoup(rawHtml,convertEntities=BeautifulSoup.HTML_ENTITIES)
188
        #soup.find(name, attrs, recursive, text)
215
        #soup.find(name, attrs, recursive, text)
189
    
-
 
190
                      
-
 
191
 
216
 
192
    def _getStatusFromDetailedStatus(self, detailedStatus):
217
    def _getStatusFromDetailedStatus(self, detailedStatus):
193
        for key, value in Store.OrderStatusMap.iteritems():
218
        for key, value in Store.OrderStatusMap.iteritems():
194
            if detailedStatus in value:
219
            if detailedStatus in value:
195
                return key
220
                return key
-
 
221
            print "Detailed Status need to be mapped"
196
        raise ParseException("_getStatusFromDetailedStatus", "Found new order status" + detailedStatus)
222
        raise ParseException("_getStatusFromDetailedStatus", "Found new order status" + detailedStatus)
197
    
223
    
198
    def settlePayBack(self):
-
 
199
        pass
-
 
200
    
224
    
201
    def scrapeStoreOrders(self,):
225
    def scrapeStoreOrders(self,):
202
        orders = self._getActiveOrders()
226
        orders = self._getActiveOrders()
203
        br = getBrowserObject()
227
        br = getBrowserObject()
204
        for order in orders:
228
        for order in orders:
Line 299... Line 323...
299
            rmap = json.loads(ungzipResponse(response, br))
323
            rmap = json.loads(ungzipResponse(response, br))
300
            if rmap is not None:
324
            if rmap is not None:
301
                rmap = rmap['response']
325
                rmap = rmap['response']
302
                if rmap is not None and len(rmap['errors'])==0:
326
                if rmap is not None and len(rmap['errors'])==0:
303
                    allOffers += rmap['data']['data']
327
                    allOffers += rmap['data']['data']
304
                    print allOffers
-
 
305
            nextPage += 1
328
            nextPage += 1
306
            if rmap['data']['pageCount']<nextPage:
329
            if rmap['data']['pageCount']<nextPage:
307
                break
330
                break
308
        
331
        
309
        return allOffers
332
        return allOffers
Line 312... Line 335...
312
        offerData = offer['Stat']
335
        offerData = offer['Stat']
313
        offer1 = AffiliateInfo(offerData['affiliate_info1'], self.store_id, offerData['conversion_status'], offerData['ad_id'], 
336
        offer1 = AffiliateInfo(offerData['affiliate_info1'], self.store_id, offerData['conversion_status'], offerData['ad_id'], 
314
                              offerData['datetime'], offerData['payout'], offer['Offer']['name'], offerData['ip'], offerData['conversion_sale_amount'])
337
                              offerData['datetime'], offerData['payout'], offer['Offer']['name'], offerData['ip'], offerData['conversion_sale_amount'])
315
        return offer1
338
        return offer1
316
def getPostData(token, page = 1, limit= 20, startDate=None, endDate=None):
339
def getPostData(token, page = 1, limit= 20, startDate=None, endDate=None):
317
    endDate=datetime.date.today() + datetime.timedelta(days=1)
340
    endDate=date.today() + datetime.timedelta(days=1)
318
    startDate=endDate - datetime.timedelta(days=31)
341
    startDate=endDate - datetime.timedelta(days=31)
319
 
342
 
320
    parameters = (
343
    parameters = (
321
        ("page",str(page)),
344
        ("page",str(page)),
322
        ("limit",str(limit)),
345
        ("limit",str(limit)),
Line 343... Line 366...
343
    return urllib.urlencode(parameters)
366
    return urllib.urlencode(parameters)
344
 
367
 
345
def main():
368
def main():
346
    
369
    
347
    store = getStore(3)
370
    store = getStore(3)
348
    store._isSubOrderActive(8, "5970688907")
371
    #store._isSubOrderActive(8, "5970688907")
349
    
372
    store.scrapeAffiliate()
350
    #store.parseOrderRawHtml(12345, "subtagId", 122323,  "html", 'https://m.snapdeal.com/purchaseMobileComplete?code=1f4166d13ea799b65aa9dea68b3e9e70&order=4509499363')
373
    #store.parseOrderRawHtml(12345, "subtagId", 122323,  "html", 'https://m.snapdeal.com/purchaseMobileComplete?code=1f4166d13ea799b65aa9dea68b3e9e70&order=4509499363')
351
 
374
 
352
def ungzipResponse(r,b):
375
def ungzipResponse(r,b):
353
    headers = r.info()
376
    headers = r.info()
354
    if headers['Content-Encoding']=='gzip':
377
    if headers['Content-Encoding']=='gzip':