| 13569 |
amit.gupta |
1 |
'''
|
|
|
2 |
Created on Jan 15, 2015
|
|
|
3 |
|
|
|
4 |
@author: amit
|
|
|
5 |
'''
|
| 13690 |
amit.gupta |
6 |
from BeautifulSoup import BeautifulSoup
|
| 13721 |
amit.gupta |
7 |
from datetime import datetime, date, timedelta
|
| 13569 |
amit.gupta |
8 |
from dtr import main
|
| 14412 |
amit.gupta |
9 |
from dtr.dao import AffiliateInfo, Order, SubOrder, FlipkartAffiliateInfo
|
| 13690 |
amit.gupta |
10 |
from dtr.main import getBrowserObject, getStore, ParseException, ungzipResponse, \
|
| 14398 |
amit.gupta |
11 |
Store as MStore, sourceMap, tprint
|
| 21246 |
amit.gupta |
12 |
from dtr.storage.DataService import Clicks, Users, FlipkartOrders, OrdersRaw
|
| 16209 |
amit.gupta |
13 |
from dtr.utils import utils
|
| 20395 |
amit.gupta |
14 |
from dtr.utils.utils import fetchResponseUsingProxy, todict, getSkuData,\
|
|
|
15 |
ORDER_PLACED
|
| 15539 |
amit.gupta |
16 |
from elixir import *
|
| 13690 |
amit.gupta |
17 |
from pprint import pprint
|
|
|
18 |
from pymongo.mongo_client import MongoClient
|
| 17238 |
amit.gupta |
19 |
import StringIO
|
|
|
20 |
import csv
|
| 13690 |
amit.gupta |
21 |
import hashlib
|
| 13658 |
manas |
22 |
import importlib
|
| 13690 |
amit.gupta |
23 |
import json
|
|
|
24 |
import mechanize
|
| 14412 |
amit.gupta |
25 |
import pymongo
|
| 13658 |
manas |
26 |
import re
|
| 14338 |
amit.gupta |
27 |
import traceback
|
| 13658 |
manas |
28 |
import urllib
|
| 18156 |
amit.gupta |
29 |
import urllib2
|
| 20392 |
amit.gupta |
30 |
from urlparse import urlparse
|
| 17238 |
amit.gupta |
31 |
import zipfile
|
| 13658 |
manas |
32 |
USERNAME='saholic1@gmail.com'
|
|
|
33 |
PASSWORD='spice@2020'
|
| 21264 |
amit.gupta |
34 |
ORDER_TRACK_URL='https://www.flipkart.com/order_details?src=or&pr=1&type=physical&'
|
| 17238 |
amit.gupta |
35 |
AFFILIATE_URL='https://affiliate.flipkart.com/'
|
|
|
36 |
AFFILIATE_LOGIN_URL='https://affiliate.flipkart.com/a_login'
|
|
|
37 |
AFF_REPORT_URL = "https://affiliate.flipkart.com/downloads/a_downloadRequest?type=OrdersReport¶meters=%s"
|
|
|
38 |
AFF_DOWNLOAD_URL="https://affiliate.flipkart.com/downloads/file?id=%s"
|
| 13690 |
amit.gupta |
39 |
AFF_STATUS_CANCELLED='cancelled'
|
|
|
40 |
AFF_STATUS_APPROVED='approved'
|
|
|
41 |
AFF_STATUS_DISAPPROVED='disapproved'
|
|
|
42 |
AFF_STATUS_PENDING='pending'
|
| 17238 |
amit.gupta |
43 |
statuses = [AFF_STATUS_CANCELLED, AFF_STATUS_APPROVED, AFF_STATUS_DISAPPROVED,AFF_STATUS_PENDING ]
|
| 15539 |
amit.gupta |
44 |
categoryMap = {3:"Mobiles", 5:"Tablets"}
|
| 21269 |
amit.gupta |
45 |
mobileAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4'
|
| 13658 |
manas |
46 |
|
| 21266 |
amit.gupta |
47 |
headers = {
|
| 21269 |
amit.gupta |
48 |
'User-Agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4',
|
| 21266 |
amit.gupta |
49 |
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
|
|
50 |
'Accept-Language' : 'en-US,en;q=0.8',
|
|
|
51 |
'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
|
|
|
52 |
'Connection':'keep-alive',
|
|
|
53 |
'Accept-Encoding' : 'gzip,deflate,sdch'
|
|
|
54 |
}
|
|
|
55 |
|
| 21273 |
amit.gupta |
56 |
TRACK_URLS = []
|
|
|
57 |
TRACK_HEADERS = {
|
|
|
58 |
"sn":"2.VIBAC8BD9D21024F649B0482FAC385814A.SIE6C5F25D78974A5EB850D89167D52009.VSE7C76F85C2EE463786F89407CA46CA31.1492756338",
|
|
|
59 |
"Connection":"keep-alive",
|
|
|
60 |
"Referer":"https://www.flipkart.com/rv/orders?link=myAccounts",
|
|
|
61 |
"cache-control":"no-cache",
|
|
|
62 |
"Accept":"/",
|
|
|
63 |
"Accept-Language":"en-US,en;q=0.8",
|
|
|
64 |
"content-type":"application/json",
|
|
|
65 |
"User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML:like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36",
|
|
|
66 |
"flipkart_secure":"true",
|
|
|
67 |
"sc":"",
|
|
|
68 |
"Accept-Encoding":"gzip:deflate:sdch:br",
|
|
|
69 |
"x-user-agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML:like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36 FKUA/msite/0.0.1/msite/Mobile,Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML:like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36 FKUA/msite/0.0.1/msite/Mobile",
|
|
|
70 |
"pragma":"no-cache",
|
|
|
71 |
"issecureresource":"true"
|
|
|
72 |
}
|
|
|
73 |
|
|
|
74 |
|
| 13781 |
amit.gupta |
75 |
class Store(MStore):
|
| 13658 |
manas |
76 |
OrderStatusMap = {
|
| 14679 |
amit.gupta |
77 |
main.Store.ORDER_PLACED : ['approval', 'processing', 'shipping'],
|
|
|
78 |
main.Store.ORDER_DELIVERED : ['your item has been delivered'],
|
| 14680 |
amit.gupta |
79 |
main.Store.ORDER_SHIPPED : ['in transit', 'shipment yet to be delivered'],
|
|
|
80 |
main.Store.ORDER_CANCELLED : ['shipment is returned', 'your item has been returned', 'your shipment has been cancelled', 'your shipment has been cancelled.']
|
| 13658 |
manas |
81 |
|
|
|
82 |
}
|
|
|
83 |
def __init__(self,store_id):
|
|
|
84 |
client = MongoClient('mongodb://localhost:27017/')
|
|
|
85 |
self.db = client.dtr
|
|
|
86 |
super(Store, self).__init__(store_id)
|
|
|
87 |
|
| 13569 |
amit.gupta |
88 |
def getName(self):
|
|
|
89 |
return "flipkart"
|
|
|
90 |
|
| 21273 |
amit.gupta |
91 |
def trackOrdersForUser(self, userId, url, rawHtml):
|
|
|
92 |
rawHtml = re.sub(r'[^\x00-\x7F]+',' ', rawHtml)
|
|
|
93 |
if url not in TRACK_URLS:
|
|
|
94 |
for lis in re.findall('SN:"(.*?)"', rawHtml):
|
|
|
95 |
TRACK_HEADERS['sn'] = lis
|
|
|
96 |
break
|
|
|
97 |
for lis in re.findall('SN:"(.*?)"', rawHtml):
|
|
|
98 |
TRACK_HEADERS['User-Agent'] = lis.split(" fkUA")[0]
|
|
|
99 |
TRACK_HEADERS['x-user-agent'] = lis
|
|
|
100 |
break
|
|
|
101 |
|
|
|
102 |
return {"headers":TRACK_HEADERS, "urls":TRACK_URLS}
|
|
|
103 |
else:
|
|
|
104 |
return 'PARSED_SUCCESS'
|
|
|
105 |
#parse json here
|
|
|
106 |
#jsonObject = json.loads(readSSh("/home/amit/node/serve/res.json"))
|
|
|
107 |
|
| 17238 |
amit.gupta |
108 |
|
|
|
109 |
def requestDownload(self):
|
|
|
110 |
#"https://affiliate.flipkart.com/downloads/a_downloadRequest?type=OrdersReport¶meters=%7B%22filter%22%3A%22approved%22%2C%22till%22%3A%222015-10-03%22%2C%22from%22%3A%222015-04-03%22%7D"
|
|
|
111 |
requestReportUrl = "https://affiliate.flipkart.com/downloads/a_downloadRequest?type=OrdersReport¶meters=%s"
|
|
|
112 |
br = getBrowserObject()
|
|
|
113 |
br.set_debug_responses(True)
|
|
|
114 |
br.open(AFFILIATE_URL)
|
|
|
115 |
response = br.response() # copy
|
|
|
116 |
#token = re.findall('window.__FK = "(.*?)"', utils.ungzipResponse(response), re.IGNORECASE)[0]
|
|
|
117 |
data = {
|
|
|
118 |
'j_username':'saholic1@gmail.com',
|
|
|
119 |
'j_password':'spice@2020'
|
|
|
120 |
}
|
|
|
121 |
print utils.ungzipResponse(br.open(AFFILIATE_LOGIN_URL, urllib.urlencode(data)))
|
|
|
122 |
till = datetime.strftime(date.today(),"%Y-%m-%d")
|
|
|
123 |
start = datetime.strftime(date.today() - timedelta(4), "%Y-%m-%d")
|
|
|
124 |
#target = open("dowloadreportids", 'w')
|
|
|
125 |
#target.truncate()
|
|
|
126 |
for status in statuses:
|
|
|
127 |
#try:
|
|
|
128 |
data = {"till":till, "from":start, "filter":status}
|
|
|
129 |
print json.dumps(data)
|
|
|
130 |
request = requestReportUrl%(urllib.quote_plus(json.dumps(data).replace(" ", "")))
|
|
|
131 |
print request
|
|
|
132 |
response = utils.ungzipResponse(br.open(request))
|
|
|
133 |
response = json.loads(response)
|
|
|
134 |
print response
|
|
|
135 |
if(response['status']=="OK"):
|
|
|
136 |
self.db.flipkartdownloadids.save(response)
|
|
|
137 |
else:
|
|
|
138 |
utils.sendmail(['amit.gupta@shop2020.in'], '', "Could not get request data for Flipkart Affiliate downlaod")
|
|
|
139 |
#break
|
|
|
140 |
#except:
|
|
|
141 |
utils.sendmail(['amit.gupta@shop2020.in'], '', "Could not get request data for Flipkart Affiliate downlaod due to Internal Server Error")
|
|
|
142 |
#break
|
|
|
143 |
|
|
|
144 |
|
| 13690 |
amit.gupta |
145 |
def scrapeStoreOrders(self,):
|
|
|
146 |
orders = self._getActiveOrders()
|
| 13721 |
amit.gupta |
147 |
for order in orders:
|
| 14692 |
amit.gupta |
148 |
print "Order", self.store_name, order['orderId']
|
| 14398 |
amit.gupta |
149 |
try:
|
|
|
150 |
closed = True
|
| 20421 |
amit.gupta |
151 |
url = ORDER_TRACK_URL + urlparse(order['orderSuccessUrl']).query
|
| 21266 |
amit.gupta |
152 |
page = fetchResponseUsingProxy(url, headers)
|
| 14398 |
amit.gupta |
153 |
soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
|
|
|
154 |
|
|
|
155 |
sections = soup.findAll("div", {"class":"ui-app-card-body"})
|
|
|
156 |
sections.pop(1)
|
| 13721 |
amit.gupta |
157 |
|
| 14398 |
amit.gupta |
158 |
mainOrder = soup.find("ul",{"class":"m-bottom p-cart"})
|
|
|
159 |
fkSubOrders = mainOrder.findAll("li")
|
|
|
160 |
|
|
|
161 |
#remove unwanted list
|
|
|
162 |
fkSubOrders.pop(-1)
|
|
|
163 |
|
|
|
164 |
|
|
|
165 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
|
|
166 |
#fetching suborders details
|
|
|
167 |
for subOrder in fkSubOrders:
|
|
|
168 |
updateMap = {}
|
| 14692 |
amit.gupta |
169 |
ul = subOrder.find("ul")
|
|
|
170 |
if ul is None:
|
|
|
171 |
ul = subOrder.findAll("div", recursive=False)[0].div.div
|
|
|
172 |
orderItems = ul.findAll("div", recursive=False)
|
| 14398 |
amit.gupta |
173 |
for orderItem in orderItems:
|
|
|
174 |
closedStatus = False
|
| 20422 |
amit.gupta |
175 |
divs = orderItem.findAll('div', recursive=False)
|
|
|
176 |
orderTracking = divs[2]
|
|
|
177 |
merchantSubOrderId = divs[3].get('id')
|
| 14398 |
amit.gupta |
178 |
subOrder = self._isSubOrderActive(order, merchantSubOrderId)
|
|
|
179 |
if subOrder is None:
|
|
|
180 |
break
|
| 14460 |
amit.gupta |
181 |
elif subOrder['closed']:
|
|
|
182 |
break
|
| 14398 |
amit.gupta |
183 |
findMap = {"orderId": order['orderId'], "subOrders.merchantSubOrderId": merchantSubOrderId}
|
|
|
184 |
orderTrackingDetDiv = divs[3].find('div',{'class':'c-tabs-content m-top active'})
|
| 20422 |
amit.gupta |
185 |
cashbackStatus = subOrder.get("cashBackStatus")
|
| 20420 |
amit.gupta |
186 |
if orderTrackingDetDiv is not None:
|
|
|
187 |
orderTrackingDet = str(orderTrackingDetDiv.find("div", "tracking-remark").text)
|
|
|
188 |
updateMap["subOrders.$.detailedStatus"] = orderTrackingDet
|
|
|
189 |
tr = orderTracking.findAll("div",{"class":"tap-bullet-area c-tab-trigger"})
|
|
|
190 |
|
|
|
191 |
tr = orderTracking.findAll("div",{"class":"tap-bullet-area c-tab-trigger"})
|
|
|
192 |
|
|
|
193 |
if "approveDetails-ongoing" in str(tr) or "processingDetails-ongoing" in str(tr):
|
|
|
194 |
status=MStore.ORDER_PLACED
|
|
|
195 |
elif "shippingDetails-ongoing" in str(tr):
|
|
|
196 |
status = MStore.ORDER_SHIPPED
|
|
|
197 |
elif "delivery-complete" in str(tr):
|
|
|
198 |
status = MStore.ORDER_DELIVERED
|
| 20421 |
amit.gupta |
199 |
if cashbackStatus != Store.CB_NA:
|
| 20420 |
amit.gupta |
200 |
cashbackStatus = Store.CB_APPROVED
|
|
|
201 |
closedStatus = True
|
|
|
202 |
if "dead" in str(tr) or "shippingDetails-returnOngoing" in str(tr) or "shippingDetails-return" in str(tr):
|
|
|
203 |
status = MStore.ORDER_CANCELLED
|
|
|
204 |
closedStatus = True
|
|
|
205 |
if cashbackStatus == Store.CB_PENDING:
|
|
|
206 |
cashbackStatus = Store.CB_CANCELLED
|
|
|
207 |
else:
|
|
|
208 |
updateMap["subOrders.$.detailedStatus"] = "Refunded"
|
| 14398 |
amit.gupta |
209 |
status = MStore.ORDER_CANCELLED
|
|
|
210 |
closedStatus = True
|
|
|
211 |
if cashbackStatus == Store.CB_PENDING:
|
|
|
212 |
cashbackStatus = Store.CB_CANCELLED
|
| 20417 |
amit.gupta |
213 |
print "Sub Order Status " + str(status)
|
| 14398 |
amit.gupta |
214 |
|
|
|
215 |
updateMap["subOrders.$.cashBackStatus"] = cashbackStatus
|
|
|
216 |
updateMap["subOrders.$.status"] = status
|
|
|
217 |
updateMap["subOrders.$.closed"] = closedStatus
|
|
|
218 |
if closed:
|
|
|
219 |
closed = closedStatus
|
|
|
220 |
bulk.find(findMap).update({'$set' : updateMap})
|
| 14692 |
amit.gupta |
221 |
bulk.find({'orderId': order['orderId']}).update({'$set':{'closed': closed, 'parseError':False}})
|
| 14398 |
amit.gupta |
222 |
bulk.execute()
|
|
|
223 |
except:
|
| 14692 |
amit.gupta |
224 |
self.db.merchantOrder.update({"orderId":order['orderId']}, {"$set":{"parseError":True}})
|
| 14847 |
amit.gupta |
225 |
tprint("Could not update " + str(order['orderId']) + ' for store ' + self.getName())
|
| 14398 |
amit.gupta |
226 |
traceback.print_exc()
|
| 17238 |
amit.gupta |
227 |
|
|
|
228 |
def scrapeAffiliate(self, deltaDays=0):
|
|
|
229 |
if deltaDays is None:
|
|
|
230 |
deltaDays=0
|
|
|
231 |
endDate=date.today() - timedelta(days=1)
|
|
|
232 |
startDate = endDate - timedelta(days=deltaDays)
|
| 15539 |
amit.gupta |
233 |
|
| 17238 |
amit.gupta |
234 |
endDate = datetime.strftime(endDate, "%Y-%m-%d")
|
|
|
235 |
startDate = datetime.strftime(startDate, "%Y-%m-%d")
|
| 17241 |
amit.gupta |
236 |
url = "https://affiliate-api.flipkart.net/affiliate/report/orders/detail/json?startDate=%s&endDate=%s&status=%s&offset=0"
|
| 17238 |
amit.gupta |
237 |
|
|
|
238 |
for status in statuses:
|
| 17241 |
amit.gupta |
239 |
nextUrl = url%(startDate, endDate, status)
|
|
|
240 |
while nextUrl:
|
| 17243 |
amit.gupta |
241 |
req = urllib2.Request(nextUrl)
|
| 17242 |
amit.gupta |
242 |
nextUrl=''
|
| 17238 |
amit.gupta |
243 |
req.add_header('Fk-Affiliate-Id', 'saholic1g')
|
|
|
244 |
req.add_header('Fk-Affiliate-Token', 'a757444e260c46be8c4aeb20352246ac')
|
|
|
245 |
resp = urllib2.urlopen(req)
|
|
|
246 |
resString = json.loads(resp.read())
|
|
|
247 |
orderList = resString["orderList"]
|
|
|
248 |
if orderList:
|
|
|
249 |
for order in orderList:
|
|
|
250 |
order['sales'] = int(order['sales']['amount'])
|
|
|
251 |
order['tentativeCommission'] = int(order['tentativeCommission']['amount'])
|
|
|
252 |
subTagId = order.get("affExtParam1")
|
|
|
253 |
userId = None
|
|
|
254 |
email = None
|
|
|
255 |
if subTagId:
|
|
|
256 |
click = session.query(Clicks).filter_by(tag = subTagId).first()
|
|
|
257 |
if click is not None:
|
|
|
258 |
userId= click.user_id
|
|
|
259 |
user = session.query(Users.email).filter_by(id = userId).first()
|
|
|
260 |
if user is not None:
|
|
|
261 |
email = user.email
|
|
|
262 |
|
|
|
263 |
flipkartOrder = FlipkartOrders()
|
|
|
264 |
flipkartOrder.subtagId = subTagId
|
|
|
265 |
flipkartOrder.user_id = userId
|
|
|
266 |
flipkartOrder.identifier = order.get("identifier")
|
|
|
267 |
flipkartOrder.email = email
|
| 18465 |
amit.gupta |
268 |
flipkartOrder.created = datetime.strptime(order.get("orderDate"), "%d-%m-%Y %H:%M:%S")
|
| 17238 |
amit.gupta |
269 |
flipkartOrder.status = order.get("status")
|
|
|
270 |
flipkartOrder.title = order.get("title")
|
|
|
271 |
flipkartOrder.price = order.get("price")
|
|
|
272 |
flipkartOrder.quantity = order.get("quantity")
|
|
|
273 |
flipkartOrder.productCode = order.get("productId")
|
|
|
274 |
flipkartOrder.affiliateOrderItemId = order.get("affiliateOrderItemId")
|
|
|
275 |
flipkartOrder.payOut = order['tentativeCommission']
|
|
|
276 |
flipkartOrder.payOutPercentage = order['commissionRate']
|
|
|
277 |
skuData = getSkuData(2, order.get("productId"))
|
|
|
278 |
if skuData is not None:
|
|
|
279 |
flipkartOrder.catalogId = skuData.get("skuBundleId")
|
|
|
280 |
flipkartOrder.brand = skuData.get("brand")
|
|
|
281 |
flipkartOrder.model = skuData.get("model_name")
|
|
|
282 |
flipkartOrder.category = categoryMap.get(skuData.get("category_id"))
|
|
|
283 |
flipkartOrder.title =skuData.get("source_product_name")
|
|
|
284 |
|
|
|
285 |
session.commit()
|
| 17241 |
amit.gupta |
286 |
nextUrl = resString['next']
|
| 13721 |
amit.gupta |
287 |
|
| 14412 |
amit.gupta |
288 |
def _saveToAffiliate(self, offers):
|
| 17238 |
amit.gupta |
289 |
collection = self.db.flipkartOrderAffiliateInfo1
|
|
|
290 |
count=0
|
|
|
291 |
for row in offers:
|
|
|
292 |
if count==0:
|
|
|
293 |
count += 1
|
|
|
294 |
continue
|
|
|
295 |
offer = self.covertToObj(row)
|
|
|
296 |
collection.save(offer)
|
|
|
297 |
|
|
|
298 |
def covertToObj(self,offer):
|
|
|
299 |
affiliateorderitemid,title,productid,category,quantity,sales,price,commissionrate,tentativecommission,status,orderdate,saleschannel,customertype,affextparam1, affextparam2 = offer
|
|
|
300 |
saleMap = {
|
|
|
301 |
"affiliateorderitemid":affiliateorderitemid,
|
|
|
302 |
"title":title,
|
|
|
303 |
"productid":productid,
|
|
|
304 |
"category":category,
|
|
|
305 |
"quantity":quantity,
|
|
|
306 |
"saleAmount":sales,
|
|
|
307 |
"price":price,
|
|
|
308 |
"commissionrate":commissionrate,
|
|
|
309 |
"payOut":tentativecommission,
|
|
|
310 |
"conversionStatus":status,
|
|
|
311 |
"saleDate":orderdate,
|
|
|
312 |
"saleschannel":saleschannel,
|
|
|
313 |
"customertype":customertype,
|
|
|
314 |
"affextparam1":affextparam1,
|
|
|
315 |
"_id":affiliateorderitemid
|
|
|
316 |
}
|
|
|
317 |
return saleMap
|
| 14412 |
amit.gupta |
318 |
|
|
|
319 |
|
| 13658 |
manas |
320 |
def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
|
| 13796 |
amit.gupta |
321 |
resp= {}
|
| 13781 |
amit.gupta |
322 |
try:
|
|
|
323 |
merchantOrderId = re.findall('reference_id=(.*?)&', orderSuccessUrl,re.IGNORECASE)[0]
|
| 21270 |
amit.gupta |
324 |
if len(self.db.merchantOrder.find({"merchantOrderId":merchantOrderId})) == 0:
|
|
|
325 |
br = getBrowserObject(mobileAgent)
|
|
|
326 |
url = ORDER_TRACK_URL + urlparse(orderSuccessUrl).query
|
|
|
327 |
|
|
|
328 |
response = br.open(url)
|
|
|
329 |
page = ungzipResponse(response)
|
|
|
330 |
|
|
|
331 |
print merchantOrderId
|
|
|
332 |
|
|
|
333 |
soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
|
|
|
334 |
|
|
|
335 |
sections = soup.findAll("div", {"class":"ui-app-card-body"})
|
|
|
336 |
sections.pop(1)
|
|
|
337 |
|
|
|
338 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
|
|
339 |
merchantOrder.closed = True
|
|
|
340 |
merchantOrder.orderTrackingUrl = url
|
|
|
341 |
for data in sections:
|
|
|
342 |
name = data.findAll("span")
|
|
|
343 |
i=0
|
|
|
344 |
while i< len(name):
|
|
|
345 |
if "key" in str(name[i]):
|
|
|
346 |
if "Grand Total" in str(name[i]):
|
|
|
347 |
#Total Amount
|
|
|
348 |
merchantOrder.paidAmount = int(re.findall(r'\d+', name[i+1].text)[0])
|
|
|
349 |
elif "Order Date" in str(name[i]):
|
|
|
350 |
merchantOrder.placedOn = name[i+1].text
|
|
|
351 |
i=i+1
|
|
|
352 |
|
|
|
353 |
merchantOrder.merchantOrderId = merchantOrderId
|
|
|
354 |
|
|
|
355 |
mainOrder = soup.find("ul",{"class":"m-bottom p-cart"})
|
|
|
356 |
fkSubOrders = mainOrder.findAll("li")
|
|
|
357 |
#remove unwanted list
|
|
|
358 |
fkSubOrders.pop(-1)
|
|
|
359 |
subOrders = []
|
|
|
360 |
merchantOrder.subOrders = subOrders
|
|
|
361 |
|
|
|
362 |
for subOrder in fkSubOrders:
|
|
|
363 |
orderItems = subOrder.findAll("div", "product-list-item", recursive=True)
|
|
|
364 |
for orderItem in orderItems:
|
|
|
365 |
if not orderItem.has_key("id"):
|
|
|
366 |
continue
|
|
|
367 |
divs = orderItem.findAll('div', recursive=False)
|
|
|
368 |
content = divs[0]
|
|
|
369 |
orderTracking = divs[2]
|
|
|
370 |
merchantSubOrderId = divs[3].get('id')
|
|
|
371 |
imgUrl = content.find('img')['src']
|
|
|
372 |
lineDet = content.find("div",{"class":"product-info"})
|
|
|
373 |
productTitle = lineDet.find("a",{"class":"product-title"}).text
|
|
|
374 |
productUrl = str(lineDet.find("a")['href'])
|
|
|
375 |
|
|
|
376 |
start='pid='
|
|
|
377 |
s=str(lineDet.find("a")['href'])
|
|
|
378 |
productCode = re.findall(re.escape(start)+"(.*)",s)[0].strip()
|
|
|
379 |
mname = lineDet.findAll("span")
|
|
|
380 |
k=0
|
|
|
381 |
while k<len(mname):
|
|
|
382 |
if "note" in str(mname[k]):
|
|
|
383 |
if "Color:" in str(mname[k]):
|
|
|
384 |
productTitle = productTitle + " " + mname[k+1].text
|
|
|
385 |
|
|
|
386 |
elif "Qty:" in str(mname[k]):
|
|
|
387 |
quantity = int(mname[k+1].text)
|
|
|
388 |
elif "Subtotal:" in str(mname[k]):
|
|
|
389 |
amountPaid = int(re.findall(r'\d+', mname[k+1].text)[0])
|
|
|
390 |
elif "Delivery:" in str(mname[k]):
|
|
|
391 |
#Delivery Date for sub order
|
|
|
392 |
print "Delivery Date " +mname[k+1].text
|
|
|
393 |
k=k+1
|
|
|
394 |
merchantsubOrder = SubOrder(productTitle, productUrl, merchantOrder.placedOn, amountPaid,MStore.ORDER_PLACED, quantity)
|
|
|
395 |
merchantsubOrder.imgUrl = imgUrl
|
|
|
396 |
merchantsubOrder.productCode = productCode
|
|
|
397 |
merchantsubOrder.merchantSubOrderId = merchantSubOrderId
|
|
|
398 |
print "productCode", productCode
|
|
|
399 |
print "amountPaid", amountPaid
|
|
|
400 |
cashbackAmount, cashbackPercent = self.getCashbackAmount(productCode, amountPaid)
|
|
|
401 |
cashbackStatus = Store.CB_PENDING
|
|
|
402 |
if cashbackAmount <= 0:
|
|
|
403 |
cashbackStatus = Store.CB_NA
|
|
|
404 |
merchantsubOrder.cashBackAmount = cashbackAmount
|
|
|
405 |
merchantsubOrder.cashBackStatus = cashbackStatus
|
|
|
406 |
merchantsubOrder.cashBackPercentage = cashbackPercent
|
|
|
407 |
activePart = orderItem.find("div", "c-tabs-content m-top active")
|
|
|
408 |
if activePart is not None:
|
|
|
409 |
merchantsubOrder.detailedStatus = str(activePart.find("div", "tracking-remark").text)
|
|
|
410 |
|
|
|
411 |
#To track shipping details
|
|
|
412 |
status=ORDER_PLACED
|
|
|
413 |
tr = orderTracking.findAll("div",{"class":"tap-bullet-area c-tab-trigger"})
|
|
|
414 |
if "approveDetails-ongoing" in str(tr) or "processingDetails-ongoing" in str(tr):
|
|
|
415 |
pass
|
|
|
416 |
elif "shippingDetails-ongoing" in str(tr):
|
|
|
417 |
status = MStore.ORDER_SHIPPED
|
|
|
418 |
elif "delivery-complete" in str(tr):
|
|
|
419 |
status = MStore.ORDER_DELIVERED
|
|
|
420 |
if cashbackStatus!=MStore.CB_NA:
|
|
|
421 |
merchantsubOrder.cashBackStatus = MStore.CB_APPROVED
|
|
|
422 |
merchantsubOrder.closed = True
|
|
|
423 |
if "dead" in str(tr) or "shippingDetails-returnOngoing" in str(tr) or "shippingDetails-return" in str(tr):
|
|
|
424 |
status = MStore.ORDER_CANCELLED
|
|
|
425 |
if merchantsubOrder.cashBackStatus != MStore.CB_NA:
|
|
|
426 |
merchantsubOrder.cashBackStatus = MStore.CB_CANCELLED
|
|
|
427 |
merchantsubOrder.closed = True
|
|
|
428 |
print "Sub Order Status " + str(status)
|
|
|
429 |
merchantsubOrder.status=status
|
|
|
430 |
if merchantOrder.closed:
|
|
|
431 |
merchantOrder.closed = merchantsubOrder.closed
|
|
|
432 |
subOrders.append(merchantsubOrder)
|
| 13781 |
amit.gupta |
433 |
|
| 21270 |
amit.gupta |
434 |
if self._saveToOrder(todict(merchantOrder)):
|
|
|
435 |
resp['result'] = 'ORDER_CREATED'
|
|
|
436 |
else:
|
|
|
437 |
resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
|
| 14312 |
amit.gupta |
438 |
else:
|
|
|
439 |
resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
|
|
|
440 |
|
| 13796 |
amit.gupta |
441 |
return resp
|
| 13781 |
amit.gupta |
442 |
except:
|
| 14338 |
amit.gupta |
443 |
traceback.print_exc()
|
| 14312 |
amit.gupta |
444 |
resp['result'] = 'ORDER_NOT_CREATED'
|
| 13796 |
amit.gupta |
445 |
return resp
|
| 13781 |
amit.gupta |
446 |
|
| 14617 |
amit.gupta |
447 |
def _getStatusFromDetailedStatus(self, detailedStatus):
|
|
|
448 |
for key, value in Store.OrderStatusMap.iteritems():
|
| 14626 |
amit.gupta |
449 |
if detailedStatus.lower() in value:
|
| 14617 |
amit.gupta |
450 |
return key
|
| 14676 |
amit.gupta |
451 |
print "Detailed Status need to be mapped", detailedStatus, "Store:", self.store_name
|
| 20392 |
amit.gupta |
452 |
raise ParseException("_getStatusFromDetailedStatus", "Found new order status" + detailedStatus)
|
| 13658 |
manas |
453 |
|
|
|
454 |
def _saveToOrderFlipkart(self, order):
|
|
|
455 |
collection = self.db.merchantOrder
|
|
|
456 |
order = collection.insert(order)
|
|
|
457 |
|
| 13690 |
amit.gupta |
458 |
|
|
|
459 |
|
|
|
460 |
def hex_md5(password):
|
|
|
461 |
m = hashlib.md5()
|
|
|
462 |
print(m.digest())
|
|
|
463 |
|
| 13658 |
manas |
464 |
def main():
|
| 16210 |
amit.gupta |
465 |
store = getStore(2)
|
| 21246 |
amit.gupta |
466 |
store.parseOrderRawHtml(1, '1234', 14, '', 'https://www.flipkart.com/rv/orderConfirmation/orderresponse?pr=1&reference_id=OD1088257258903640&src=or&type=physical&token=e0fa1db468ba77bfb8cdac938e051ef3')
|
|
|
467 |
#store.scrapeStoreOrders()
|
| 13679 |
manas |
468 |
|
| 16209 |
amit.gupta |
469 |
if __name__ == '__main__':
|
|
|
470 |
main()
|
| 14145 |
amit.gupta |
471 |
|