Subversion Repositories SmartDukaan

Rev

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

Rev 16378 Rev 16382
Line 18... Line 18...
18
 
18
 
19
from dtr.storage.DataService import paytm_coupon_usages
19
from dtr.storage.DataService import paytm_coupon_usages
20
 
20
 
21
class Store(MStore):
21
class Store(MStore):
22
    OrderStatusMap = {
22
    OrderStatusMap = {
23
                      main.Store.ORDER_PLACED : ['in process', 'ready to be shipped', 'order recieved', 'order received', 'pending confirmation'],
23
                      main.Store.ORDER_PLACED : ['in process', 'ready to be shipped', 'order recieved', 'order received', 'pending confirmation', 'waiting for courier pickup'],
24
                      main.Store.ORDER_DELIVERED : ['delivered'],
24
                      main.Store.ORDER_DELIVERED : ['delivered'],
25
                      main.Store.ORDER_SHIPPED : ['in transit', 'shipped'],
25
                      main.Store.ORDER_SHIPPED : ['in transit', 'shipped'],
26
                      main.Store.ORDER_CANCELLED : ['failed', 'payment failed']
26
                      main.Store.ORDER_CANCELLED : ['failed', 'payment failed']
27
                      
27
                      
28
                      }
28
                      }
Line 77... Line 77...
77
    def getTrackingUrls(self, userId):
77
    def getTrackingUrls(self, userId):
78
        missingOrderUrls = []
78
        missingOrderUrls = []
79
        #missingOrders = self._getMissingOrders({'userId':userId})
79
        #missingOrders = self._getMissingOrders({'userId':userId})
80
        #for missingOrder in missingOrders:
80
        #for missingOrder in missingOrders:
81
        #    missingOrderUrls.append(ORDER_REDIRECT_URL%(missingOrder['merchantOrderId']))
81
        #    missingOrderUrls.append(ORDER_REDIRECT_URL%(missingOrder['merchantOrderId']))
82
        orders = self._getActiveOrders({'userId':userId, "subOrders.trackingUrl":{"$exists":False} })
82
        orders = self._getActiveOrders({'userId':userId, "subOrders.trackingUrl":{"$exists":False} }, {"merchantOrderId":1})
83
        for order in orders:
83
        for order in orders:
-
 
84
            print order
84
            "https://paytm.com/shop/orderdetail/%s?actions=1&channel=web&version=2"%("")
85
            missingOrderUrls.append("https://paytm.com/shop/orderdetail/%s?actions=1&channel=web&version=2"%(order.get("merchantOrderId")))
85
            return missingOrderUrls
86
        return missingOrderUrls
86
 
87
 
87
    def trackOrdersForUser(self, userId, url, rawHtml):
88
    def trackOrdersForUser(self, userId, url, rawHtml):
-
 
89
        executeBulk = False
88
        ordermap = json.loads(rawHtml).get("order")
90
        ordermap = json.loads(rawHtml).get("order")
-
 
91
        merchantOrderId = str(ordermap.get("id"))
-
 
92
        merchantOrder = self.db.merchantOrder.findOne({"merchantOrderId":merchantOrderId})
-
 
93
        bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
-
 
94
        closed=True
89
        for item in ordermap.get("items"):
95
        for item in ordermap.get("items"):
-
 
96
            merchantSubOrderId = item.get("id")
-
 
97
            for subOrder in merchantOrder.get("subOrders"):
-
 
98
                if not subOrder.get("closed"):
-
 
99
                    if merchantSubOrderId == subOrder.get("merchantSubOrderId") and item.get("status_text") != subOrder.get("detailedStatus"):
-
 
100
                        findMap = {"orderId":merchantOrder.get("orderId"), "subOrders.merchantSubOrderId":subOrder.get("merchantSubOrderId")}
-
 
101
                        newSub = {}
-
 
102
                        detailedStatus = item.get("status_text")
-
 
103
                        newSub['detailedStatus'] = detailedStatus
-
 
104
                        status  = self._getStatusFromDetailedStatus(detailedStatus)
-
 
105
                        newSub['status'] = status if status else subOrder.get("status")  
-
 
106
                        updateMap = self.getUpdateMap(newSub, subOrder.get("cashBackStatus"))
-
 
107
                        bulk.find(findMap).update({'$set' : updateMap})
-
 
108
                        closed = closed and newSub['closed']
-
 
109
                        break
-
 
110
                    else:
-
 
111
                        continue
90
            pass
112
                    
91
        
113
        
92
    def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
114
    def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
-
 
115
        try:
93
        resp = {}
116
            resp = {}
94
        #orderSuccessUrl = "https://paytm.com/shop/orderdetail/1155961075?actions=1&channel=web&version=2"
117
            #orderSuccessUrl = "https://paytm.com/shop/orderdetail/1155961075?actions=1&channel=web&version=2"
95
        ordermap = json.loads(rawHtml).get("order")
118
            ordermap = json.loads(rawHtml).get("order")
96
        if not ordermap.get("need_shipping"):
119
            if not ordermap.get("need_shipping"):
97
            resp['result'] = 'PAYTM_RECHARGE_ORDER'
120
                resp['result'] = 'RECHARGE_ORDER_IGNORED'
98
            return resp
121
                return resp
99
        elif ordermap.get("payment_status") == "PROCESSING":
122
            elif ordermap.get("payment_status") == "PROCESSING":
100
            resp['result'] = 'ORDER_PENDING_PAYMENT'
123
                resp['result'] = 'PAYMENT_PENDING_IGNORED'
101
            return resp
124
                return resp
102
        order = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
125
            order = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
103
        order.deliveryCharges = ordermap.get("shipping_charges") - ordermap.get("shipping_discount")
126
            order.deliveryCharges = ordermap.get("shipping_charges") - ordermap.get("shipping_discount")
104
        order.merchantOrderId = str(ordermap.get("id"))  
127
            order.merchantOrderId = str(ordermap.get("id"))  
105
        order.discountApplied = ordermap.get("discount_amount")
128
            order.discountApplied = ordermap.get("discount_amount")
106
        order.paidAmount = ordermap.get("grandtotal")
129
            order.paidAmount = ordermap.get("grandtotal")
107
        order.placedOn = ordermap.get("date") + " "+ ordermap.get("time") 
130
            order.placedOn = ordermap.get("date") + " "+ ordermap.get("time") 
108
        order.requireDetail = False
131
            order.requireDetail = False
109
        order.status = 'success'
132
            order.status = 'success'
110
        order.totalAmount = ordermap.get("subtotal")
133
            order.totalAmount = ordermap.get("subtotal")
111
        subOrders = []
134
            subOrders = []
112
        order.subOrders = subOrders
135
            order.subOrders = subOrders
113
        coupon_code = None
136
            coupon_code = None
114
        total_cashback = 0
137
            total_cashback = 0
115
        for item in ordermap.get("items"):
138
            for item in ordermap.get("items"):
116
            product = item.get("product")
139
                product = item.get("product")
117
            shareUrl = product.get("seourl").replace("catalog.paytm.com/v1", "paytm.com/shop")
140
                shareUrl = product.get("seourl").replace("catalog.paytm.com/v1", "paytm.com/shop")
118
            paytmcashback = 0
141
                paytmcashback = 0
119
            if item.get("promo_code"):
142
                if item.get("promo_code"):
120
                coupon_code = item.get("promo_code")
143
                    coupon_code = item.get("promo_code")
121
                for s in item.get("promo_text").split(): 
144
                    for s in item.get("promo_text").split(): 
122
                    if s.isdigit():
145
                        if s.isdigit():
123
                        paytmcashback = int(s)
146
                            paytmcashback = int(s)
124
                        total_cashback += paytmcashback
147
                            total_cashback += paytmcashback
125
                        break
148
                            break
126
            amountPaid = item.get("subtotal") - paytmcashback 
149
                amountPaid = item.get("subtotal") - paytmcashback 
127
            detailedStatus = item.get("status_text")
150
                detailedStatus = item.get("status_text")
128
            status = self._getStatusFromDetailedStatus(detailedStatus)
151
                status = self._getStatusFromDetailedStatus(detailedStatus)
129
            if status == None:
152
                if status == None:
130
                status = MStore.ORDER_PLACED
153
                    status = MStore.ORDER_PLACED
131
            subOrder = SubOrder(item.get("title"), item.get("product").get(""), ordermap.get("date"), amountPaid, status, item.get("quantity"))
154
                subOrder = SubOrder(item.get("title"), item.get("product").get(""), ordermap.get("date"), amountPaid, status, item.get("quantity"))
132
            subOrder.imgUrl = product.get("thumbnail")
155
                subOrder.imgUrl = product.get("thumbnail")
133
            subOrder.detailedStatus = detailedStatus
156
                subOrder.detailedStatus = detailedStatus
134
            subOrder.productUrl = shareUrl
157
                subOrder.productUrl = shareUrl
135
            subOrder.productCode = product.get("url").split("?")[0].split("/")[-1]
158
                subOrder.productCode = product.get("url").split("?")[0].split("/")[-1]
136
            subOrder.merchantSubOrderId = str(item.get("id"))
159
                subOrder.merchantSubOrderId = str(item.get("id"))
137
            if status == MStore.ORDER_PLACED: 
160
                if status == MStore.ORDER_PLACED: 
138
                if item.get("status_flow")[1].get("date"):
161
                    if item.get("status_flow")[1].get("date"):
139
                    subOrder.estimatedDeliveryDate = datetime.strftime(getISTDate(item.get("status_flow")[1].get("date")), "%d %b")
162
                        subOrder.estimatedShippingDate = datetime.strftime(getISTDate(item.get("status_flow")[1].get("date")), "%d %b")
140
                if item.get("status_flow")[2].get("date"):
163
                    if item.get("status_flow")[2].get("date"):
141
                    subOrder.estimatedShippingDate = datetime.strftime(getISTDate(item.get("status_flow")[2].get("date")), "%d %b")
164
                        subOrder.estimatedDeliveryDate = datetime.strftime(getISTDate(item.get("status_flow")[2].get("date")), "%d %b")
-
 
165
                else:
-
 
166
                    subOrder.closed = False
-
 
167
                subOrders.append(subOrder)
-
 
168
            if coupon_code:
-
 
169
                usage = paytm_coupon_usages()
-
 
170
                usage.cashback = total_cashback
-
 
171
                usage.coupon = coupon_code
-
 
172
                usage.user_id = userId
-
 
173
                usage.order_id = orderId
-
 
174
                session.commit()
-
 
175
            self.populateDerivedFields(order)
-
 
176
            if self._saveToOrder(todict(order)):
-
 
177
                resp['result'] = 'ORDER_CREATED'
142
            else:
178
            else:
143
                subOrder.closed = False
-
 
144
            subOrders.append(subOrder)
-
 
145
        if coupon_code:
-
 
146
            usage = paytm_coupon_usages()
-
 
147
            usage.cashback = total_cashback
-
 
148
            usage.coupon = coupon_code
-
 
149
            usage.user_id = userId
-
 
150
            usage.order_id = orderId
-
 
151
            session.commit()
-
 
152
        self.populateDerivedFields(order)
-
 
153
        if self._saveToOrder(todict(order)):
-
 
154
            resp['result'] = 'ORDER_CREATED'
179
                resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
155
        else:
180
        except:
156
            resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
181
            resp['result'] = 'ORDER_NOT_CREATED'
157
        
182
            
158
        return resp
183
        return resp
159
        
184
        
160
    def _getStatusFromDetailedStatus(self, detailedStatus):
185
    def _getStatusFromDetailedStatus(self, detailedStatus):
161
        for key, value in Store.OrderStatusMap.iteritems():
186
        for key, value in Store.OrderStatusMap.iteritems():
162
            if detailedStatus.lower() in value:
187
            if detailedStatus.lower() in value:
Line 169... Line 194...
169
    return tzDate
194
    return tzDate
170
 
195
 
171
def main():
196
def main():
172
    store = getStore(6)
197
    store = getStore(6)
173
    #store.scrapeStoreOrders()
198
    #store.scrapeStoreOrders()
174
    store.parseOrderRawHtml(312119, 'SUB1', 14, readSSh("/home/amit/paytm.json"), "someurl")
199
    #store.parseOrderRawHtml(312119, 'SUB1', 14, readSSh("/home/amit/paytm.json"), "someurl")
-
 
200
    print store.getTrackingUrls(14)
175
    
201
    
176
if __name__ == '__main__':
202
if __name__ == '__main__':
177
    main()
203
    main()
178
204