Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
14811 amit.gupta 1
'''
2
Created on Apr 12, 2015
3
 
4
@author: amit
5
'''
6
from bs4 import BeautifulSoup
16391 amit.gupta 7
from datetime import datetime, timedelta
14811 amit.gupta 8
from dtr import main
16371 amit.gupta 9
from dtr.dao import Order, SubOrder
14811 amit.gupta 10
from dtr.main import getBrowserObject, getStore, ParseException, ungzipResponse, \
16371 amit.gupta 11
    Store as MStore, sourceMap, tprint, todict
16283 amit.gupta 12
from dtr.sources.amazon import readSSh
16391 amit.gupta 13
from dtr.storage.DataService import paytm_coupon_usages
16421 amit.gupta 14
from dtr.utils.utils import fetchResponseUsingProxy, find_between
16391 amit.gupta 15
from elixir import *
14811 amit.gupta 16
from pymongo.mongo_client import MongoClient
16371 amit.gupta 17
import json
16391 amit.gupta 18
import os
16371 amit.gupta 19
import traceback
14811 amit.gupta 20
 
16374 amit.gupta 21
 
14811 amit.gupta 22
class Store(MStore):
23
    OrderStatusMap = {
16382 amit.gupta 24
                      main.Store.ORDER_PLACED : ['in process', 'ready to be shipped', 'order recieved', 'order received', 'pending confirmation', 'waiting for courier pickup'],
16283 amit.gupta 25
                      main.Store.ORDER_DELIVERED : ['delivered'],
16371 amit.gupta 26
                      main.Store.ORDER_SHIPPED : ['in transit', 'shipped'],
16404 amit.gupta 27
                      main.Store.ORDER_CANCELLED : ['failed', 'payment failed', 'cancelled']
14811 amit.gupta 28
 
29
                      }
30
    def __init__(self,store_id):
31
        client = MongoClient('mongodb://localhost:27017/')
32
        self.db = client.dtr
33
        super(Store, self).__init__(store_id)
34
 
35
    def saveOrder(self, merchantOrder):
36
        MStore.saveOrder(self, merchantOrder)
16371 amit.gupta 37
 
38
    def parseTrackingUrl(self, trackingUrl):
39
        subOrder = {}
40
        page = fetchResponseUsingProxy(trackingUrl)
41
        soup = BeautifulSoup(page)
42
        subOrder['detailedStatus'] = soup.h1.text
43
        subOrder['status'] = self._getStatusFromDetailedStatus(subOrder['detailedStatus'])
14811 amit.gupta 44
 
16371 amit.gupta 45
 
14811 amit.gupta 46
    def scrapeStoreOrders(self):
16371 amit.gupta 47
        orders = self.db.merchantOrder.find({"storeId":1, "closed":False, "subOrders":{"$elemMatch":{"closed":False, "trackingUrl":{"$exists":True}}}})
48
        for merchantOrder in orders:
49
            executeBulk = False
50
            try:
51
                bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
52
                closed = True
53
                map1 = {}
54
                for subOrder in merchantOrder.get("subOrders"):
55
                    if subOrder.get("closed"):
56
                        continue
57
                    elif subOrder.get("trackingUrl") is None:
58
                        closed = False
59
                        continue
60
                    executeBulk = True
61
                    findMap = {"orderId":merchantOrder.get("orderId"), "subOrders.merchantSubOrderId":subOrder.get("merchantSubOrderId")} 
62
                    trackingUrl = subOrder.get("trackingUrl")
63
                    if not map1.has_key(trackingUrl):
64
                        map1[trackingUrl] = self.parseTrackingUrl(trackingUrl)
65
                    newOrder = map1.get(trackingUrl)
66
                    updateMap = self.getUpdateMap(newOrder, subOrder.get('cashBackStatus'))
67
                    print findMap, "\n", updateMap
68
                    bulk.find(findMap).update({'$set' : updateMap})
69
                    closed = closed and newOrder['closed']
70
                if executeBulk:
71
                    bulk.find({"orderId":merchantOrder.get("orderId")}).update({"$set":{"closed":closed, "parseError":False}})
72
                    bulk.execute()
73
            except:
74
                tprint("Could not update " + str(merchantOrder['orderId']) + " For store " + self.getName())
75
                self.db.merchantOrder.update({"orderId":merchantOrder['orderId']}, {"$set":{"parseError":True}})
76
                traceback.print_exc()
14811 amit.gupta 77
 
16371 amit.gupta 78
    def getTrackingUrls(self, userId):
79
        missingOrderUrls = []
80
        #missingOrders = self._getMissingOrders({'userId':userId})
81
        #for missingOrder in missingOrders:
82
        #    missingOrderUrls.append(ORDER_REDIRECT_URL%(missingOrder['merchantOrderId']))
16382 amit.gupta 83
        orders = self._getActiveOrders({'userId':userId, "subOrders.trackingUrl":{"$exists":False} }, {"merchantOrderId":1})
16371 amit.gupta 84
        for order in orders:
16382 amit.gupta 85
            print order
86
            missingOrderUrls.append("https://paytm.com/shop/orderdetail/%s?actions=1&channel=web&version=2"%(order.get("merchantOrderId")))
87
        return missingOrderUrls
16371 amit.gupta 88
 
89
    def trackOrdersForUser(self, userId, url, rawHtml):
16421 amit.gupta 90
        merchantOrderId = find_between(rawHtml, "https://paytm.com/shop/orderdetail/","?actions=1&channel=web&version=2")
16391 amit.gupta 91
        directory = "/PaytmTrack/User" + str(userId)
92
        if not os.path.exists(directory):
93
            os.makedirs(directory)
94
 
16382 amit.gupta 95
        executeBulk = False
16391 amit.gupta 96
        filename = directory + "/" + merchantOrderId + "-" +  datetime.strftime(datetime.now(), '%d-%m:%H:%M:%S')   
97
        f = open(filename,'w')
98
        f.write(rawHtml) # python will convert \n to os.linesep
16421 amit.gupta 99
        f.close() # you can omit in most cases as the destructor will call if
100
        rawHtml = find_between(rawHtml,"<pre>", "</pre>")
101
        if rawHtml == "":
102
            raise    
103
        ordermap = json.loads(rawHtml).get("order")
16401 amit.gupta 104
        merchantOrder = self.db.merchantOrder.find_one({"merchantOrderId":merchantOrderId})
16388 amit.gupta 105
        try:
106
            bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
107
            closed=True
108
            for item in ordermap.get("items"):
16389 amit.gupta 109
                merchantSubOrderId = str(item.get("id"))
16388 amit.gupta 110
                for subOrder in merchantOrder.get("subOrders"):
111
                    if not subOrder.get("closed"):
112
                        if merchantSubOrderId == subOrder.get("merchantSubOrderId") and item.get("status_text") != subOrder.get("detailedStatus"):
113
                            executeBulk = True
114
                            findMap = {"orderId":merchantOrder.get("orderId"), "subOrders.merchantSubOrderId":subOrder.get("merchantSubOrderId")}
115
                            newSub = {}
116
                            detailedStatus = item.get("status_text")
117
                            newSub['detailedStatus'] = detailedStatus
118
                            status  = self._getStatusFromDetailedStatus(detailedStatus)
119
                            newSub['status'] = status if status else subOrder.get("status")  
120
                            updateMap = self.getUpdateMap(newSub, subOrder.get("cashBackStatus"))
121
                            bulk.find(findMap).update({'$set' : updateMap})
122
                            closed = closed and newSub['closed']
123
                            break
124
                        else:
125
                            continue
126
            if executeBulk:
16387 amit.gupta 127
                bulk.find({"orderId":merchantOrder.get("orderId")}).update({"$set":{"closed":closed, "parseError":False}})
128
                bulk.execute()
16388 amit.gupta 129
        except:
130
                tprint("Could not update " + str(merchantOrder['orderId']) + " For store " + self.getName())
131
                self.db.merchantOrder.update({"orderId":merchantOrder['orderId']}, {"$set":{"parseError":True}})
132
                traceback.print_exc()
16371 amit.gupta 133
 
16283 amit.gupta 134
    def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
16421 amit.gupta 135
 
136
        #Expected is json
137
        orderSuccessUrl = find_between(orderSuccessUrl, "<pre>", "</pre>")
138
        if orderSuccessUrl != "": 
139
            try:
140
                resp = {}
141
                #orderSuccessUrl = "https://paytm.com/shop/orderdetail/1155961075?actions=1&channel=web&version=2"
142
                ordermap = json.loads(rawHtml).get("order")
143
                if not ordermap.get("need_shipping"):
144
                    resp['result'] = 'RECHARGE_ORDER_IGNORED'
145
                    return resp
146
                elif ordermap.get("payment_status") == "PROCESSING":
147
                    resp['result'] = 'PAYMENT_PENDING_IGNORED'
148
                    return resp
149
                order = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
150
                order.deliveryCharges = ordermap.get("shipping_charges") - ordermap.get("shipping_discount")
151
                order.merchantOrderId = str(ordermap.get("id"))  
152
                order.discountApplied = ordermap.get("discount_amount")
153
                order.paidAmount = ordermap.get("grandtotal")
154
                order.placedOn = datetime.strftime(getISTDate(ordermap.get("created_at")),"%d-%m-%Y %H:%M:%S") 
155
                order.requireDetail = False
156
                order.status = 'success'
157
                order.totalAmount = ordermap.get("subtotal")
158
                subOrders = []
159
                order.subOrders = subOrders
160
                coupon_code = None
161
                total_cashback = 0
162
                for item in ordermap.get("items"):
163
                    product = item.get("product")
164
                    shareUrl = product.get("seourl").replace("catalog.paytm.com/v1", "paytm.com/shop")
165
                    paytmcashback = 0
166
                    if item.get("promo_code"):
167
                        coupon_code = item.get("promo_code")
168
                        for s in item.get("promo_text").split(): 
169
                            if s.isdigit():
170
                                paytmcashback = int(s)
171
                                total_cashback += paytmcashback
172
                                break
173
                    amountPaid = item.get("subtotal") - paytmcashback 
174
                    detailedStatus = item.get("status_text")
175
                    status = self._getStatusFromDetailedStatus(detailedStatus)
176
                    if status == None:
177
                        status = MStore.ORDER_PLACED
178
                    subOrder = SubOrder(item.get("title"), item.get("product").get(""), ordermap.get("date"), amountPaid, status, item.get("quantity"))
179
                    subOrder.imgUrl = product.get("thumbnail")
180
                    subOrder.detailedStatus = detailedStatus
181
                    subOrder.productUrl = shareUrl
182
                    subOrder.productCode = product.get("url").split("?")[0].split("/")[-1]
183
                    subOrder.merchantSubOrderId = str(item.get("id"))
184
                    if status == MStore.ORDER_PLACED: 
185
                        if item.get("status_flow")[1].get("date"):
186
                            subOrder.estimatedShippingDate = datetime.strftime(getISTDate(item.get("status_flow")[1].get("date")), "%d %b")
187
                        if item.get("status_flow")[2].get("date"):
188
                            subOrder.estimatedDeliveryDate = datetime.strftime(getISTDate(item.get("status_flow")[2].get("date")), "%d %b")
189
                    else:
190
                        subOrder.closed = False
191
                    subOrders.append(subOrder)
192
                if coupon_code:
193
                    usage = paytm_coupon_usages()
194
                    usage.cashback = total_cashback
195
                    usage.coupon = coupon_code
196
                    usage.user_id = userId
197
                    usage.order_id = orderId
198
                    session.commit()
199
                self.populateDerivedFields(order)
200
                if self._saveToOrder(todict(order)):
201
                    resp['result'] = 'ORDER_CREATED'
16382 amit.gupta 202
                else:
16421 amit.gupta 203
                    resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
204
            except:
205
                resp['result'] = 'ORDER_NOT_CREATED'
206
 
207
        else:
16382 amit.gupta 208
            resp['result'] = 'ORDER_NOT_CREATED'
16421 amit.gupta 209
        return resp
16382 amit.gupta 210
 
16371 amit.gupta 211
    def _getStatusFromDetailedStatus(self, detailedStatus):
212
        for key, value in Store.OrderStatusMap.iteritems():
213
            if detailedStatus.lower() in value:
214
                return key
16375 amit.gupta 215
        print "Detailed Status-", detailedStatus,  "need to be mapped for Store-", self.store_name
16371 amit.gupta 216
        return None
217
def getISTDate(tzString):
218
    tzDate = datetime.strptime(tzString, "%Y-%m-%dT%H:%M:%S.%fZ") 
219
    tzDate = tzDate + timedelta(0,19800)
220
    return tzDate
221
 
14811 amit.gupta 222
def main():
223
    store = getStore(6)
16283 amit.gupta 224
    #store.scrapeStoreOrders()
16404 amit.gupta 225
    store.parseOrderRawHtml(312119, 'SUB1', 14, readSSh("/home/amit/paytm.json"), "someurl")
16383 amit.gupta 226
    #print store.getTrackingUrls(14)
14811 amit.gupta 227
 
228
if __name__ == '__main__':
229
    main()