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