Subversion Repositories SmartDukaan

Rev

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

Rev 17237 Rev 17387
Line 10... Line 10...
10
from dtr.api.Service import Orders
10
from dtr.api.Service import Orders
11
from dtr.dao import AffiliateInfo, Order, SubOrder
11
from dtr.dao import AffiliateInfo, Order, SubOrder
12
from dtr.main import getBrowserObject, ScrapeException, getStore, ParseException, \
12
from dtr.main import getBrowserObject, ScrapeException, getStore, ParseException, \
13
    Store as MStore, ungzipResponse, tprint
13
    Store as MStore, ungzipResponse, tprint
14
from dtr.storage import Mongo
14
from dtr.storage import Mongo
15
from dtr.storage.DataService import Order_Parse_Info, All_user_addresses
15
from dtr.storage.DataService import Order_Parse_Info, All_user_addresses, \
-
 
16
    OrdersRaw
16
from dtr.storage.Mongo import getImgSrc, getDealRank
17
from dtr.storage.Mongo import getImgSrc, getDealRank
17
from dtr.utils import utils
18
from dtr.utils import utils
18
from dtr.utils.utils import fetchResponseUsingProxy
19
from dtr.utils.utils import fetchResponseUsingProxy, readSSh
19
from elixir import *
20
from elixir import *
20
from pprint import pprint
21
from pprint import pprint
21
from pymongo import MongoClient
22
from pymongo import MongoClient
-
 
23
from pyquery import PyQuery
22
from urlparse import urlparse, parse_qs
24
from urlparse import urlparse, parse_qs
23
from xlrd import open_workbook
25
from xlrd import open_workbook
24
import csv
26
import csv
25
import json
27
import json
26
import os.path
28
import os.path
Line 50... Line 52...
50
    '''
52
    '''
51
    OrderStatusMap = {
53
    OrderStatusMap = {
52
                      MStore.ORDER_PLACED : ['in progress', 'pending for verification', 'not available', 'in process', 'processing', 'processed', 'under verification'],
54
                      MStore.ORDER_PLACED : ['in progress', 'pending for verification', 'not available', 'in process', 'processing', 'processed', 'under verification'],
53
                      MStore.ORDER_DELIVERED : ['delivered'],
55
                      MStore.ORDER_DELIVERED : ['delivered'],
54
                      MStore.ORDER_SHIPPED : ['in transit', 'dispatched'],
56
                      MStore.ORDER_SHIPPED : ['in transit', 'dispatched'],
55
                      MStore.ORDER_CANCELLED : ['closed for vendor reallocation', 'cancelled', 'product returned by courier', 'returned', 'n/a', 'courier returned', 'a new order placed with a different seller', 'closed']
57
                      MStore.ORDER_CANCELLED : ['closed for vendor reallocation', 'cancelled', 'product returned by courier', 'returned', 'n/a', 'courier returned', 'a new order placed with a different seller', 'closed', 'cancellation in progress']
56
                      }
58
                      }
57
    
59
    
58
    CONF_CB_AMOUNT = MStore.CONF_CB_DISCOUNTED_PRICE
60
    CONF_CB_AMOUNT = MStore.CONF_CB_DISCOUNTED_PRICE
59
    def __init__(self,store_id):
61
    def __init__(self,store_id):
60
        super(Store, self).__init__(store_id)
62
        super(Store, self).__init__(store_id)
Line 373... Line 375...
373
            subOrder.trackingUrl = trackingDet.span.a['href']
375
            subOrder.trackingUrl = trackingDet.span.a['href']
374
            subOrder.trackingNumber = trackingDet.span.a.text.strip()
376
            subOrder.trackingNumber = trackingDet.span.a.text.strip()
375
 
377
 
376
        subOrders.append(subOrder)
378
        subOrders.append(subOrder)
377
        return subOrder
379
        return subOrder
-
 
380
    
-
 
381
    def getOrderJSON(self, rawHtml, supcMap):
-
 
382
        #print rawHtml
-
 
383
#        replace_with = {
-
 
384
#        '<': '&gt;',
-
 
385
#        '>': '&lt;',
-
 
386
#        '&': '&amp;',
-
 
387
#        '"': '&quot;', # should be escaped in attributes
-
 
388
#        "'": '&apos;'    # should be escaped in attributes
-
 
389
#        }
-
 
390
        pq = PyQuery(rawHtml)
-
 
391
        jsonValue = pq("#orderJSON").attr("value")
-
 
392
        jsonValue.replace("&quot;", '"')
-
 
393
        jsonValue.replace("&amp;", '&')
-
 
394
        jsonValue.replace("&gt;", '>')
-
 
395
        jsonValue.replace("&lt;", '<')
-
 
396
        jsonValue.replace("&apos;", "'")
-
 
397
        allSupcElements = pq('div.mdt-layout')('div.mdt-card')('div.order-item')
-
 
398
        for supcElement in allSupcElements:
-
 
399
            try:
-
 
400
                supcElement = pq(supcElement)
-
 
401
                title = supcElement('div.order-heading').text().strip()
-
 
402
                productUrl = supcElement.attr("data-href")
-
 
403
                imgUrl = supcElement.find('img').attr('src')
-
 
404
                supc = imgUrl.split('-')[-3]
-
 
405
                supcMap[supc] = {'title':title, 'imgUrl':imgUrl, 'productUrl':productUrl}
-
 
406
            except:
-
 
407
                pass
-
 
408
        return json.loads(jsonValue)
378
 
409
 
379
    def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
410
    def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
380
                    #print merchantOrder
411
                    #print merchantOrder
381
        resp = {}
412
        resp = {}
-
 
413
        url = ORDER_TRACK_URL + re.findall('.*(\?.*?)$', orderSuccessUrl,re.IGNORECASE)[0]
-
 
414
        supcMap = {}
382
        try:
415
        try:
383
            br = getBrowserObject()
-
 
384
            url = ORDER_TRACK_URL + re.findall('.*(\?.*?)$', orderSuccessUrl,re.IGNORECASE)[0]
-
 
385
            page = br.open(url)
-
 
386
            page = ungzipResponse(page)
-
 
387
            try:
416
            try:
388
                merchantOrder = self._parseB(orderId, subTagId, userId, page, orderSuccessUrl)
417
                orderJSON = self.getOrderJSON(rawHtml, supcMap)
389
            except:
418
            except:
390
                traceback.print_exc()
419
                traceback.print_exc()
-
 
420
                try:
-
 
421
                    page = fetchResponseUsingProxy(orderSuccessUrl)
-
 
422
                    orderJSON = self.getOrderJSON(page,supcMap)
-
 
423
                except:
-
 
424
                    traceback.print_exc()
-
 
425
                    orderJSON = None
-
 
426
            if orderJSON is None:
-
 
427
                page =fetchResponseUsingProxy(url)
-
 
428
                page = ungzipResponse(page)
-
 
429
                try:
-
 
430
                    merchantOrder = self._parseB(orderId, subTagId, userId, page, orderSuccessUrl)
-
 
431
                except:
-
 
432
                    traceback.print_exc()
391
                merchantOrder = self._parse(orderId, subTagId, userId, page, orderSuccessUrl)
433
                    merchantOrder = self._parse(orderId, subTagId, userId, page, orderSuccessUrl)
-
 
434
            else:
-
 
435
                merchantOrder = self._parseC(orderId, subTagId, userId, supcMap, orderJSON, orderSuccessUrl)
392
            
436
            
393
            merchantOrder.orderTrackingUrl = url
437
            merchantOrder.orderTrackingUrl = url
394
               
438
               
395
            if self._saveToOrder(todict(merchantOrder)):
439
            if self._saveToOrder(todict(merchantOrder)):
396
                resp['result'] = 'ORDER_CREATED'
440
                resp['result'] = 'ORDER_CREATED'
397
            else:
441
            else:
398
                resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
442
                resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
399
                
443
            print "=================", resp, orderId, "=============="
400
            return resp
444
            return resp
401
        except:
445
        except:
402
            print "Error occurred"
446
            print "Error occurred"
403
            traceback.print_exc()
447
            traceback.print_exc()
404
            resp['result'] = 'ORDER_NOT_CREATED'
448
            resp['result'] = 'ORDER_NOT_CREATED'
-
 
449
            print "=================", resp, orderId, "=============="
405
            return resp
450
            return resp
406
             
451
             
407
        
452
        
408
        #soup = BeautifulSoup(rawHtml,convertEntities=BeautifulSoup.HTML_ENTITIES)
453
        #soup = BeautifulSoup(rawHtml,convertEntities=BeautifulSoup.HTML_ENTITIES)
409
        #soup.find(name, attrs, recursive, text)
454
        #soup.find(name, attrs, recursive, text)
-
 
455
    def _parseC(self, orderId, subTagId, userId, supcMap, orderJSON, orderSuccessUrl):
-
 
456
        print orderJSON
-
 
457
        merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
-
 
458
        placedOn = datetime.strftime(utils.fromTimeStamp(orderJSON['created']/1000), "%a, %d %b, %Y")
-
 
459
        merchantOrder.placedOn = placedOn
-
 
460
        merchantOrder.merchantOrderId = orderJSON['code']
-
 
461
        merchantOrder.paidAmount = orderJSON['paidAmount']
-
 
462
        merchantOrder.deliveryCharges = orderJSON['shippingCharges']
-
 
463
        merchantOrder.closed= False
-
 
464
        merchantSubOrders = []
-
 
465
        for s in orderJSON['suborders']:
-
 
466
            print s
-
 
467
            if not supcMap.has_key(s['supcCode']):
-
 
468
                url = "http://www.snapdeal.com/search/autoSuggestion?q=%s&catId=0&ver=3"%s['supcCode']
-
 
469
                html = utils.fetchResponseUsingProxy(url)
-
 
470
                ul = PyQuery(html)('ul.top-products')
-
 
471
                title = ul('div.product-text').text().strip()
-
 
472
                productUrl = ul('a').attr("href").split("?")[0]
-
 
473
                imgUrl = ul('img').attr('src')
-
 
474
                supcMap[s['supcCode']] = {'title':title, 'imgUrl':imgUrl, 'productUrl':productUrl}
-
 
475
            map1 = supcMap[s['supcCode']]
-
 
476
                
-
 
477
            amountPaid = s['paidAmount']
-
 
478
            productTitle = map1['title']
-
 
479
            productUrl = map1['productUrl'] 
-
 
480
            subOrder = SubOrder(productTitle, productUrl, placedOn, amountPaid)
-
 
481
            if(s.get('deliveryDate') is not None):
-
 
482
                print "Delivered On", 
-
 
483
                subOrder.deliveredOn = datetime.strftime(utils.fromTimeStamp(s.get('deliveryDate')/1000),'%Y-%m-%d')
-
 
484
                subOrder.status = MStore.ORDER_DELIVERED
-
 
485
                subOrder.detailedStatus = MStore.ORDER_DELIVERED
-
 
486
            elif s['suborderStatus'].get('macroDescription')== 'Closed':
-
 
487
                if s['suborderStatus'].get('value')== 'Close for vendor reallocation':
-
 
488
                    subOrder.detailedStatus = 'Close for vendor reallocation'
-
 
489
                    subOrder.status = MStore.ORDER_CANCELLED
-
 
490
            
-
 
491
            try:
-
 
492
                subOrder.detailedStatus = s['suborderStatus']['macroDescription']
-
 
493
                subOrder.status = self._getStatusFromDetailedStatus(subOrder.detailedStatus)
-
 
494
            except:
-
 
495
                print "----------------", s['suborderStatus']
-
 
496
 
-
 
497
            subOrder.merchantSubOrderId = s['code']
-
 
498
            subOrder.deliveryCharges = s['shippingCharges']
-
 
499
            subOrder.productCode = s['supcCode']
-
 
500
            subOrder.imgUrl = map1['imgUrl']
-
 
501
            subOrder.unitPrice = s['offerPrice']  -s['internalCashbackValue'] - s['externalCashbackValue']
-
 
502
            subOrder.amount = subOrder.unitPrice - s['offerDiscount'] - s['sdCash']
-
 
503
            try:
-
 
504
                try:
-
 
505
                    if s['shipDateRange']['start']==s['shipDateRange']['end']:
-
 
506
                        subOrder.estimatedShippingDate = datetime.strftime(utils.fromTimeStamp(s['shipDateRange']['start']/1000),'%Y-%m-%d') 
-
 
507
                    else:
-
 
508
                        subOrder.estimatedShippingDate = datetime.strftime(utils.fromTimeStamp(s['shipDateRange']['start']/1000),'%Y-%m-%d') + " - " + datetime.strftime(utils.fromTimeStamp(s['shipDateRange']['end']/1000),'%Y-%m-%d')
-
 
509
                except:   
-
 
510
                    if s['deliveryDateRange']['start']==s['deliveryDateRange']['end']:
-
 
511
                        subOrder.estimatedDeliveryDate = datetime.strftime(utils.fromTimeStamp(s['deliveryDateRange']['start']/1000),'%Y-%m-%d') 
-
 
512
                    else:
-
 
513
                        subOrder.estimatedDeliveryDate = datetime.strftime(utils.fromTimeStamp(s['deliveryDateRange']['start']/1000),'%Y-%m-%d') + " - " + datetime.strftime('%Y-%m-%d',utils.fromTimeStamp(s['deliveryDateRange']['end']/1000),'%Y-%m-%d')   
-
 
514
            except:
-
 
515
                pass
-
 
516
            subOrder.offerDiscount = s['offerDiscount']
-
 
517
            subOrder.unitPrice = s['offerPrice']
-
 
518
            merchantSubOrders.append(subOrder)
-
 
519
            
-
 
520
        merchantOrder.subOrders = merchantSubOrders
-
 
521
        self.populateDerivedFields(merchantOrder)
-
 
522
        return merchantOrder
410
 
523
 
411
    def _getStatusFromDetailedStatus(self, detailedStatus):
524
    def _getStatusFromDetailedStatus(self, detailedStatus):
412
        for key, value in Store.OrderStatusMap.iteritems():
525
        for key, value in Store.OrderStatusMap.iteritems():
413
            if detailedStatus.lower() in value:
526
            if detailedStatus.lower() in value:
414
                return key
527
                return key
Line 742... Line 855...
742
 
855
 
743
 
856
 
744
def main():
857
def main():
745
    #print todict([1,2,"3"])
858
    #print todict([1,2,"3"])
746
    store = getStore(3)
859
    store = getStore(3)
747
    store.scrapeStoreOrders()
860
    #store.scrapeStoreOrders()
-
 
861
    #https://m.snapdeal.com/purchaseMobileComplete?code=3fbc8a02a1c4d3c4e906f46886de0464&order=5808451506
-
 
862
    #https://m.snapdeal.com/purchaseMobileComplete?code=9f4dfa49ff08a16d04c5e4bf519506fc&order=9611672826
-
 
863
    
-
 
864
    orders = session.query(OrdersRaw).filter_by(store_id=3).filter_by(status='ORDER_NOT_CREATED').all()
-
 
865
    for o in orders:
-
 
866
        result = store.parseOrderRawHtml(o.id, o.sub_tag, o.user_id, o.rawhtml, o.order_url)['result']
-
 
867
        o.status = result
-
 
868
        session.commit() 
748
    #store.parseOrderRawHtml(332221, "3232311", 2, "32311243", "https://m.snapdeal.com/orderSummary?code=3fbc8a02a1c4d3c4e906f46886de0464&order=5808451506")
869
        #store.parseOrderRawHtml(332221, "3232311", 2, readSSh("/home/amit/snapdeal.html"), "https://m.snapdeal.com/purchaseMobileComplete?code=3fbc8a02a1c4d3c4e906f46886de0464&order=5808451506")
749
    #store.scrapeStoreOrders()
870
    #store.scrapeStoreOrders()
750
    #store._isSubOrderActive(8, "5970688907")
871
    #store._isSubOrderActive(8, "5970688907")
751
    #store.scrapeAffiliate(datetime(2015,4,1))
872
    #store.scrapeAffiliate(datetime(2015,4,1))
752
    #store.scrapeStoreOrders()
873
    #store.scrapeStoreOrders()
753
    #store.parseInfo()
874
    #store.parseInfo()