Subversion Repositories SmartDukaan

Rev

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

Rev 16404 Rev 16421
Line 9... Line 9...
9
from dtr.dao import Order, SubOrder
9
from dtr.dao import Order, SubOrder
10
from dtr.main import getBrowserObject, getStore, ParseException, ungzipResponse, \
10
from dtr.main import getBrowserObject, getStore, ParseException, ungzipResponse, \
11
    Store as MStore, sourceMap, tprint, todict
11
    Store as MStore, sourceMap, tprint, todict
12
from dtr.sources.amazon import readSSh
12
from dtr.sources.amazon import readSSh
13
from dtr.storage.DataService import paytm_coupon_usages
13
from dtr.storage.DataService import paytm_coupon_usages
14
from dtr.utils.utils import fetchResponseUsingProxy
14
from dtr.utils.utils import fetchResponseUsingProxy, find_between
15
from elixir import *
15
from elixir import *
16
from pymongo.mongo_client import MongoClient
16
from pymongo.mongo_client import MongoClient
17
import json
17
import json
18
import os
18
import os
19
import traceback
19
import traceback
Line 85... Line 85...
85
            print order
85
            print order
86
            missingOrderUrls.append("https://paytm.com/shop/orderdetail/%s?actions=1&channel=web&version=2"%(order.get("merchantOrderId")))
86
            missingOrderUrls.append("https://paytm.com/shop/orderdetail/%s?actions=1&channel=web&version=2"%(order.get("merchantOrderId")))
87
        return missingOrderUrls
87
        return missingOrderUrls
88
 
88
 
89
    def trackOrdersForUser(self, userId, url, rawHtml):
89
    def trackOrdersForUser(self, userId, url, rawHtml):
-
 
90
        merchantOrderId = find_between(rawHtml, "https://paytm.com/shop/orderdetail/","?actions=1&channel=web&version=2")
90
        directory = "/PaytmTrack/User" + str(userId)
91
        directory = "/PaytmTrack/User" + str(userId)
91
        if not os.path.exists(directory):
92
        if not os.path.exists(directory):
92
            os.makedirs(directory)
93
            os.makedirs(directory)
93
            
94
            
94
        executeBulk = False
95
        executeBulk = False
95
        ordermap = json.loads(rawHtml).get("order")
-
 
96
        merchantOrderId = str(ordermap.get("id"))
-
 
97
        filename = directory + "/" + merchantOrderId + "-" +  datetime.strftime(datetime.now(), '%d-%m:%H:%M:%S')   
96
        filename = directory + "/" + merchantOrderId + "-" +  datetime.strftime(datetime.now(), '%d-%m:%H:%M:%S')   
98
        f = open(filename,'w')
97
        f = open(filename,'w')
99
        f.write(rawHtml) # python will convert \n to os.linesep
98
        f.write(rawHtml) # python will convert \n to os.linesep
100
        f.close() # you can omit in most cases as the destructor will call if    
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")
101
        merchantOrder = self.db.merchantOrder.find_one({"merchantOrderId":merchantOrderId})
104
        merchantOrder = self.db.merchantOrder.find_one({"merchantOrderId":merchantOrderId})
102
        try:
105
        try:
103
            bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
106
            bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
104
            closed=True
107
            closed=True
105
            for item in ordermap.get("items"):
108
            for item in ordermap.get("items"):
Line 127... Line 130...
127
                tprint("Could not update " + str(merchantOrder['orderId']) + " For store " + self.getName())
130
                tprint("Could not update " + str(merchantOrder['orderId']) + " For store " + self.getName())
128
                self.db.merchantOrder.update({"orderId":merchantOrder['orderId']}, {"$set":{"parseError":True}})
131
                self.db.merchantOrder.update({"orderId":merchantOrder['orderId']}, {"$set":{"parseError":True}})
129
                traceback.print_exc()
132
                traceback.print_exc()
130
        
133
        
131
    def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
134
    def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
-
 
135
        
-
 
136
        #Expected is json
-
 
137
        orderSuccessUrl = find_between(orderSuccessUrl, "<pre>", "</pre>")
-
 
138
        if orderSuccessUrl != "": 
132
        try:
139
            try:
133
            resp = {}
140
                resp = {}
134
            #orderSuccessUrl = "https://paytm.com/shop/orderdetail/1155961075?actions=1&channel=web&version=2"
141
                #orderSuccessUrl = "https://paytm.com/shop/orderdetail/1155961075?actions=1&channel=web&version=2"
135
            ordermap = json.loads(rawHtml).get("order")
142
                ordermap = json.loads(rawHtml).get("order")
136
            if not ordermap.get("need_shipping"):
143
                if not ordermap.get("need_shipping"):
137
                resp['result'] = 'RECHARGE_ORDER_IGNORED'
144
                    resp['result'] = 'RECHARGE_ORDER_IGNORED'
138
                return resp
145
                    return resp
139
            elif ordermap.get("payment_status") == "PROCESSING":
146
                elif ordermap.get("payment_status") == "PROCESSING":
140
                resp['result'] = 'PAYMENT_PENDING_IGNORED'
147
                    resp['result'] = 'PAYMENT_PENDING_IGNORED'
141
                return resp
148
                    return resp
142
            order = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
149
                order = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
143
            order.deliveryCharges = ordermap.get("shipping_charges") - ordermap.get("shipping_discount")
150
                order.deliveryCharges = ordermap.get("shipping_charges") - ordermap.get("shipping_discount")
144
            order.merchantOrderId = str(ordermap.get("id"))  
151
                order.merchantOrderId = str(ordermap.get("id"))  
145
            order.discountApplied = ordermap.get("discount_amount")
152
                order.discountApplied = ordermap.get("discount_amount")
146
            order.paidAmount = ordermap.get("grandtotal")
153
                order.paidAmount = ordermap.get("grandtotal")
147
            order.placedOn = datetime.strftime(getISTDate(ordermap.get("created_at")),"%d-%m-%Y %H:%M:%S") 
154
                order.placedOn = datetime.strftime(getISTDate(ordermap.get("created_at")),"%d-%m-%Y %H:%M:%S") 
148
            order.requireDetail = False
155
                order.requireDetail = False
149
            order.status = 'success'
156
                order.status = 'success'
150
            order.totalAmount = ordermap.get("subtotal")
157
                order.totalAmount = ordermap.get("subtotal")
151
            subOrders = []
158
                subOrders = []
152
            order.subOrders = subOrders
159
                order.subOrders = subOrders
153
            coupon_code = None
160
                coupon_code = None
154
            total_cashback = 0
161
                total_cashback = 0
155
            for item in ordermap.get("items"):
162
                for item in ordermap.get("items"):
156
                product = item.get("product")
163
                    product = item.get("product")
157
                shareUrl = product.get("seourl").replace("catalog.paytm.com/v1", "paytm.com/shop")
164
                    shareUrl = product.get("seourl").replace("catalog.paytm.com/v1", "paytm.com/shop")
158
                paytmcashback = 0
165
                    paytmcashback = 0
159
                if item.get("promo_code"):
166
                    if item.get("promo_code"):
160
                    coupon_code = item.get("promo_code")
167
                        coupon_code = item.get("promo_code")
161
                    for s in item.get("promo_text").split(): 
168
                        for s in item.get("promo_text").split(): 
162
                        if s.isdigit():
169
                            if s.isdigit():
163
                            paytmcashback = int(s)
170
                                paytmcashback = int(s)
164
                            total_cashback += paytmcashback
171
                                total_cashback += paytmcashback
165
                            break
172
                                break
166
                amountPaid = item.get("subtotal") - paytmcashback 
173
                    amountPaid = item.get("subtotal") - paytmcashback 
167
                detailedStatus = item.get("status_text")
174
                    detailedStatus = item.get("status_text")
168
                status = self._getStatusFromDetailedStatus(detailedStatus)
175
                    status = self._getStatusFromDetailedStatus(detailedStatus)
169
                if status == None:
176
                    if status == None:
170
                    status = MStore.ORDER_PLACED
177
                        status = MStore.ORDER_PLACED
171
                subOrder = SubOrder(item.get("title"), item.get("product").get(""), ordermap.get("date"), amountPaid, status, item.get("quantity"))
178
                    subOrder = SubOrder(item.get("title"), item.get("product").get(""), ordermap.get("date"), amountPaid, status, item.get("quantity"))
172
                subOrder.imgUrl = product.get("thumbnail")
179
                    subOrder.imgUrl = product.get("thumbnail")
173
                subOrder.detailedStatus = detailedStatus
180
                    subOrder.detailedStatus = detailedStatus
174
                subOrder.productUrl = shareUrl
181
                    subOrder.productUrl = shareUrl
175
                subOrder.productCode = product.get("url").split("?")[0].split("/")[-1]
182
                    subOrder.productCode = product.get("url").split("?")[0].split("/")[-1]
176
                subOrder.merchantSubOrderId = str(item.get("id"))
183
                    subOrder.merchantSubOrderId = str(item.get("id"))
177
                if status == MStore.ORDER_PLACED: 
184
                    if status == MStore.ORDER_PLACED: 
178
                    if item.get("status_flow")[1].get("date"):
185
                        if item.get("status_flow")[1].get("date"):
179
                        subOrder.estimatedShippingDate = datetime.strftime(getISTDate(item.get("status_flow")[1].get("date")), "%d %b")
186
                            subOrder.estimatedShippingDate = datetime.strftime(getISTDate(item.get("status_flow")[1].get("date")), "%d %b")
180
                    if item.get("status_flow")[2].get("date"):
187
                        if item.get("status_flow")[2].get("date"):
181
                        subOrder.estimatedDeliveryDate = datetime.strftime(getISTDate(item.get("status_flow")[2].get("date")), "%d %b")
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'
182
                else:
202
                else:
183
                    subOrder.closed = False
203
                    resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
184
                subOrders.append(subOrder)
-
 
185
            if coupon_code:
204
            except:
186
                usage = paytm_coupon_usages()
-
 
187
                usage.cashback = total_cashback
-
 
188
                usage.coupon = coupon_code
-
 
189
                usage.user_id = userId
-
 
190
                usage.order_id = orderId
-
 
191
                session.commit()
-
 
192
            self.populateDerivedFields(order)
-
 
193
            if self._saveToOrder(todict(order)):
-
 
194
                resp['result'] = 'ORDER_CREATED'
205
                resp['result'] = 'ORDER_NOT_CREATED'
195
            else:
206
                
196
                resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
-
 
197
        except:
207
        else:
198
            resp['result'] = 'ORDER_NOT_CREATED'
208
            resp['result'] = 'ORDER_NOT_CREATED'
199
            
-
 
200
        return resp
209
        return resp
201
        
210
            
202
    def _getStatusFromDetailedStatus(self, detailedStatus):
211
    def _getStatusFromDetailedStatus(self, detailedStatus):
203
        for key, value in Store.OrderStatusMap.iteritems():
212
        for key, value in Store.OrderStatusMap.iteritems():
204
            if detailedStatus.lower() in value:
213
            if detailedStatus.lower() in value:
205
                return key
214
                return key
206
        print "Detailed Status-", detailedStatus,  "need to be mapped for Store-", self.store_name
215
        print "Detailed Status-", detailedStatus,  "need to be mapped for Store-", self.store_name