Subversion Repositories SmartDukaan

Rev

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