| 13569 |
amit.gupta |
1 |
'''
|
|
|
2 |
Created on Jan 15, 2015
|
|
|
3 |
|
|
|
4 |
@author: amit
|
|
|
5 |
'''
|
| 14854 |
amit.gupta |
6 |
from bs4 import BeautifulSoup
|
| 13569 |
amit.gupta |
7 |
from bson.binary import Binary
|
| 13680 |
amit.gupta |
8 |
from datetime import datetime, date, timedelta
|
| 13569 |
amit.gupta |
9 |
from dtr import main
|
| 16975 |
amit.gupta |
10 |
from dtr.api.Service import Orders
|
| 13576 |
amit.gupta |
11 |
from dtr.dao import AffiliateInfo, Order, SubOrder
|
| 14398 |
amit.gupta |
12 |
from dtr.main import getBrowserObject, ScrapeException, getStore, ParseException, \
|
|
|
13 |
Store as MStore, ungzipResponse, tprint
|
| 14415 |
amit.gupta |
14 |
from dtr.storage import Mongo
|
| 17387 |
amit.gupta |
15 |
from dtr.storage.DataService import Order_Parse_Info, All_user_addresses, \
|
|
|
16 |
OrdersRaw
|
| 15350 |
amit.gupta |
17 |
from dtr.storage.Mongo import getImgSrc, getDealRank
|
| 16946 |
amit.gupta |
18 |
from dtr.utils import utils
|
| 17387 |
amit.gupta |
19 |
from dtr.utils.utils import fetchResponseUsingProxy, readSSh
|
| 16975 |
amit.gupta |
20 |
from elixir import *
|
| 13662 |
amit.gupta |
21 |
from pprint import pprint
|
| 13569 |
amit.gupta |
22 |
from pymongo import MongoClient
|
| 17387 |
amit.gupta |
23 |
from pyquery import PyQuery
|
| 15350 |
amit.gupta |
24 |
from urlparse import urlparse, parse_qs
|
| 16946 |
amit.gupta |
25 |
from xlrd import open_workbook
|
| 16975 |
amit.gupta |
26 |
import csv
|
| 13569 |
amit.gupta |
27 |
import json
|
| 16946 |
amit.gupta |
28 |
import os.path
|
| 13569 |
amit.gupta |
29 |
import pymongo
|
|
|
30 |
import re
|
| 14443 |
amit.gupta |
31 |
import time
|
| 13662 |
amit.gupta |
32 |
import traceback
|
| 13569 |
amit.gupta |
33 |
import urllib
|
| 13603 |
amit.gupta |
34 |
|
| 13721 |
amit.gupta |
35 |
USERNAME='profittill2@gmail.com'
|
| 13569 |
amit.gupta |
36 |
PASSWORD='spice@2020'
|
| 16946 |
amit.gupta |
37 |
AFFILIATE_URL='http://affiliate.snapdeal.com/login/'
|
| 13569 |
amit.gupta |
38 |
POST_URL='https://api-p03.hasoffers.com/v3/Affiliate_Report.json'
|
|
|
39 |
ORDER_TRACK_URL='https://m.snapdeal.com/orderSummary'
|
|
|
40 |
CONFIG_URL='http://affiliate.snapdeal.com/publisher/js/config.php'
|
|
|
41 |
|
| 16946 |
amit.gupta |
42 |
NEW_REPORT_URI_TEMPLATE = "http://affiliate.snapdeal.com/affiliate/reports/orders/report/?fromDate=%s&toDate=%s&dump_report=True&request_type=product&status=%s"
|
|
|
43 |
#"http://affiliate.snapdeal.com/affiliate/reports/orders/report/?fromDate=2015-04-01&toDate=2015-09-15&dump_report=True&request_type=product&status=cancelled
|
|
|
44 |
#"http://affiliate.snapdeal.com/affiliate/reports/orders/report/?fromDate=07-09-2015&toDate=13-09-2015&dump_report=True&request_type=product&status=cancelled
|
|
|
45 |
|
| 13662 |
amit.gupta |
46 |
class Store(MStore):
|
| 13569 |
amit.gupta |
47 |
|
|
|
48 |
'''
|
|
|
49 |
This is to map order statuses of our system to order statuses of snapdeal.
|
|
|
50 |
And our statuses will change accordingly.
|
|
|
51 |
|
|
|
52 |
'''
|
|
|
53 |
OrderStatusMap = {
|
| 16968 |
amit.gupta |
54 |
MStore.ORDER_PLACED : ['in progress', 'pending for verification', 'not available', 'in process', 'processing', 'processed', 'under verification'],
|
| 14678 |
amit.gupta |
55 |
MStore.ORDER_DELIVERED : ['delivered'],
|
| 14861 |
amit.gupta |
56 |
MStore.ORDER_SHIPPED : ['in transit', 'dispatched'],
|
| 17387 |
amit.gupta |
57 |
MStore.ORDER_CANCELLED : ['closed for vendor reallocation', 'cancelled', 'product returned by courier', 'returned', 'n/a', 'courier returned', 'a new order placed with a different seller', 'closed', 'cancellation in progress']
|
| 13569 |
amit.gupta |
58 |
}
|
| 13662 |
amit.gupta |
59 |
|
|
|
60 |
CONF_CB_AMOUNT = MStore.CONF_CB_DISCOUNTED_PRICE
|
| 13569 |
amit.gupta |
61 |
def __init__(self,store_id):
|
|
|
62 |
super(Store, self).__init__(store_id)
|
|
|
63 |
|
|
|
64 |
def getName(self):
|
|
|
65 |
return "snapdeal"
|
|
|
66 |
|
|
|
67 |
def scrapeAffiliate(self, startDate=None, endDate=None):
|
|
|
68 |
br = getBrowserObject()
|
|
|
69 |
br.open(AFFILIATE_URL)
|
|
|
70 |
br.select_form(nr=0)
|
| 16946 |
amit.gupta |
71 |
#br.form['data[User][password]'] = PASSWORD
|
|
|
72 |
#br.form['data[User][email]'] = USERNAME
|
|
|
73 |
br.form['email'] = USERNAME
|
|
|
74 |
br.form['password'] = PASSWORD
|
| 13569 |
amit.gupta |
75 |
br.submit()
|
|
|
76 |
|
| 16946 |
amit.gupta |
77 |
#after logged in successfully
|
|
|
78 |
|
|
|
79 |
#response = br.open(CONFIG_URL)
|
|
|
80 |
#find token to fetch api
|
|
|
81 |
#token = re.findall('"session_token":"(.*?)"', ungzipResponse(response), re.IGNORECASE)[0]
|
|
|
82 |
#print token
|
|
|
83 |
#allOffers = self._getAllOffers(br, token)
|
|
|
84 |
|
|
|
85 |
#fetch api using new report uri
|
| 17009 |
amit.gupta |
86 |
endDate=date.today() - timedelta(days=1)
|
| 16946 |
amit.gupta |
87 |
if startDate is None:
|
| 17048 |
amit.gupta |
88 |
startDate = endDate - timedelta(days=45)
|
| 16946 |
amit.gupta |
89 |
|
|
|
90 |
endDate = endDate.strftime('%d-%m-%Y')
|
|
|
91 |
startDate = startDate.strftime('%d-%m-%Y')
|
|
|
92 |
statuses=['cancelled', 'approved']
|
|
|
93 |
directory = "/SnapAff/"
|
|
|
94 |
curDate = directory + datetime.now().strftime('%Y-%m-%d')
|
|
|
95 |
if not os.path.exists(directory):
|
|
|
96 |
os.makedirs(directory)
|
|
|
97 |
for status in statuses:
|
| 16997 |
amit.gupta |
98 |
if status == "approved":
|
|
|
99 |
print "app"
|
| 16946 |
amit.gupta |
100 |
reportUrl = NEW_REPORT_URI_TEMPLATE%(startDate, endDate, status)
|
|
|
101 |
print reportUrl
|
|
|
102 |
filename=curDate + "-" + status
|
|
|
103 |
fileobj = open(filename,"wb")
|
|
|
104 |
fileobj.write(utils.ungzipResponse(br.open(reportUrl)))
|
|
|
105 |
fileobj.close()
|
|
|
106 |
with open(filename, 'rb') as csvfile:
|
|
|
107 |
reader = csv.reader(csvfile)
|
| 17234 |
amit.gupta |
108 |
self._saveToAffiliate(reader, status)
|
| 13569 |
amit.gupta |
109 |
|
| 13662 |
amit.gupta |
110 |
def _setLastSaleDate(self, saleDate):
|
| 13680 |
amit.gupta |
111 |
self.db.lastSaleDtate.update({'storeId':self.store_id}, {'$set':{'saleDate':saleDate}})
|
| 13569 |
amit.gupta |
112 |
|
| 13662 |
amit.gupta |
113 |
|
|
|
114 |
|
|
|
115 |
def _getLastSaleDate(self,):
|
|
|
116 |
lastDaySaleObj = self.db.lastDaySale.find_one({"storeId":self.store_id})
|
|
|
117 |
if lastDaySaleObj is None:
|
|
|
118 |
return datetime.min
|
|
|
119 |
|
| 14854 |
amit.gupta |
120 |
|
|
|
121 |
|
|
|
122 |
def _parseB(self, orderId, subTagId, userId, page, orderSuccessUrl):
|
|
|
123 |
soup = BeautifulSoup(page)
|
|
|
124 |
|
|
|
125 |
orderDetailContainerDivs = soup.body.find("div", {'class':'cardLayoutWrap'}).findAll('div', recursive=False)
|
|
|
126 |
orderDetailDiv = orderDetailContainerDivs.pop(0)
|
|
|
127 |
paymentDetailDiv = orderDetailContainerDivs.pop(0)
|
|
|
128 |
subOrders = orderDetailContainerDivs
|
|
|
129 |
|
|
|
130 |
placedOn = orderDetailDiv.span.text.split(':')[1].strip()
|
|
|
131 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
|
|
132 |
merchantOrder.placedOn = placedOn
|
|
|
133 |
merchantOrder.merchantOrderId = parse_qs(urlparse(orderSuccessUrl).query)['order'][0]
|
|
|
134 |
|
|
|
135 |
paymentDivs = paymentDetailDiv.findAll('div', recursive=False)
|
|
|
136 |
paymentDivs.pop(0)
|
|
|
137 |
for orderTr in paymentDivs:
|
|
|
138 |
orderTrString = str(orderTr)
|
|
|
139 |
if "Total Amount Paid" in orderTrString:
|
|
|
140 |
amountPaid = orderTr.div.find('div', {'class':'detailBlock'}).text.strip()
|
|
|
141 |
merchantOrder.paidAmount = int(re.findall(r'\d+', amountPaid)[0])
|
|
|
142 |
elif "Total Amount" in orderTrString:
|
|
|
143 |
merchantOrder.totalAmount = re.findall(r'\d+', orderTrString)[0]
|
|
|
144 |
elif "Delivery Charges" in orderTrString:
|
|
|
145 |
merchantOrder.deliveryCharges = re.findall(r'\d+', orderTrString)[0]
|
|
|
146 |
elif "Discount Applied" in orderTrString:
|
|
|
147 |
merchantOrder.discountApplied = re.findall(r'\d+', orderTrString)[0]
|
|
|
148 |
elif "Offer Discount" in orderTrString:
|
|
|
149 |
merchantOrder.discountApplied = re.findall(r'\d+', orderTrString)[0]
|
|
|
150 |
|
|
|
151 |
merchantSubOrders = []
|
|
|
152 |
for subOrderElement in subOrders:
|
| 14883 |
amit.gupta |
153 |
subOrder = self.parseSubOrderB(subOrderElement, placedOn)
|
|
|
154 |
if subOrder is not None:
|
| 15350 |
amit.gupta |
155 |
dealRank = getDealRank(subOrder.productCode, self.store_id, merchantOrder.userId)
|
|
|
156 |
subOrder.dealRank = dealRank.get('rank')
|
|
|
157 |
subOrder.rankDesc = dealRank.get('description')
|
| 16283 |
amit.gupta |
158 |
subOrder.maxNlc = dealRank.get('maxNlc')
|
|
|
159 |
subOrder.minNlc = dealRank.get('minNlc')
|
|
|
160 |
subOrder.db = dealRank.get('dp')
|
|
|
161 |
subOrder.itemStatus = dealRank.get('status')
|
| 14883 |
amit.gupta |
162 |
merchantSubOrders.append(subOrder)
|
| 14854 |
amit.gupta |
163 |
merchantOrder.subOrders = merchantSubOrders
|
|
|
164 |
return merchantOrder
|
|
|
165 |
|
| 13760 |
amit.gupta |
166 |
def _parse(self, orderId, subTagId, userId, page, orderSuccessUrl):
|
| 13662 |
amit.gupta |
167 |
|
| 13760 |
amit.gupta |
168 |
#page=page.decode("utf-8")
|
| 14854 |
amit.gupta |
169 |
soup = BeautifulSoup(page)
|
| 13760 |
amit.gupta |
170 |
#orderHead = soup.find(name, attrs, recursive, text)
|
|
|
171 |
sections = soup.findAll("section")
|
|
|
172 |
|
|
|
173 |
#print sections
|
|
|
174 |
|
|
|
175 |
order = sections[1]
|
|
|
176 |
orderTrs = order.findAll("tr")
|
|
|
177 |
|
|
|
178 |
placedOn = str(orderTrs[0].findAll("td")[1].text)
|
|
|
179 |
|
|
|
180 |
#Pop two section elements
|
|
|
181 |
sections.pop(0)
|
|
|
182 |
sections.pop(0)
|
|
|
183 |
subOrders = sections
|
|
|
184 |
|
|
|
185 |
|
|
|
186 |
merchantSubOrders = []
|
|
|
187 |
|
|
|
188 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
| 14447 |
amit.gupta |
189 |
merchantOrder.placedOn = placedOn
|
| 14023 |
amit.gupta |
190 |
merchantOrder.merchantOrderId = re.findall(r'\d+', str(soup.find("div", {"class":"deals_heading"})))[1]
|
| 13760 |
amit.gupta |
191 |
for orderTr in orderTrs:
|
|
|
192 |
orderTrString = str(orderTr)
|
|
|
193 |
if "Total Amount" in orderTrString:
|
|
|
194 |
merchantOrder.totalAmount = re.findall(r'\d+', orderTrString)[0]
|
|
|
195 |
elif "Delivery Charges" in orderTrString:
|
|
|
196 |
merchantOrder.deliveryCharges = re.findall(r'\d+', orderTrString)[0]
|
|
|
197 |
elif "Discount Applied" in orderTrString:
|
|
|
198 |
merchantOrder.discountApplied = re.findall(r'\d+', orderTrString)[0]
|
|
|
199 |
elif "Paid Amount" in orderTrString:
|
|
|
200 |
merchantOrder.paidAmount = re.findall(r'\d+', orderTrString)[0]
|
|
|
201 |
|
|
|
202 |
for subOrderElement in subOrders:
|
| 13809 |
amit.gupta |
203 |
subOrders = self.parseSubOrder(subOrderElement, placedOn)
|
|
|
204 |
merchantSubOrders.extend(subOrders)
|
| 13760 |
amit.gupta |
205 |
|
|
|
206 |
merchantOrder.subOrders = merchantSubOrders
|
|
|
207 |
return merchantOrder
|
|
|
208 |
|
|
|
209 |
def parseSubOrder(self, subOrderElement, placedOn):
|
| 13809 |
amit.gupta |
210 |
subOrders = []
|
| 13760 |
amit.gupta |
211 |
productUrl = str(subOrderElement.find("a")['href'])
|
|
|
212 |
subTable = subOrderElement.find("table", {"class":"lrPad"})
|
|
|
213 |
subTrs = subTable.findAll("tr")
|
|
|
214 |
unitPrice=None
|
| 14458 |
amit.gupta |
215 |
offerDiscount = 0
|
| 13760 |
amit.gupta |
216 |
deliveryCharges = None
|
|
|
217 |
amountPaid = None
|
| 14458 |
amit.gupta |
218 |
amount = 0
|
| 14473 |
amit.gupta |
219 |
sdCash = 0
|
|
|
220 |
unitPrice = 0
|
| 13760 |
amit.gupta |
221 |
for subTr in subTrs:
|
|
|
222 |
subTrString = str(subTr)
|
|
|
223 |
if "Unit Price" in subTrString:
|
| 14473 |
amit.gupta |
224 |
unitPrice = int(re.findall(r'\d+', subTrString)[0])
|
| 13760 |
amit.gupta |
225 |
if "Quantity" in subTrString:
|
| 14458 |
amit.gupta |
226 |
qty = int(re.findall(r'\d+', subTrString)[0])
|
| 13760 |
amit.gupta |
227 |
elif "Offer Discount" in subTrString:
|
| 14458 |
amit.gupta |
228 |
offerDiscount += int(re.findall(r'\d+', subTrString)[0])
|
| 14861 |
amit.gupta |
229 |
elif "SD Cash" in subTrString:
|
| 14473 |
amit.gupta |
230 |
sdCash = int(re.findall(r'\d+', subTrString)[0])
|
| 13760 |
amit.gupta |
231 |
elif "Delivery Charges" in subTrString:
|
| 14473 |
amit.gupta |
232 |
deliveryCharges = int(re.findall(r'\d+', subTrString)[0])
|
| 13760 |
amit.gupta |
233 |
elif "Subtotal" in subTrString:
|
|
|
234 |
if int(qty) > 0:
|
| 14459 |
amit.gupta |
235 |
amountPaid = int(re.findall(r'\d+', subTrString)[0])/qty
|
| 13760 |
amit.gupta |
236 |
else:
|
| 14459 |
amit.gupta |
237 |
amountPaid = 0
|
| 14458 |
amit.gupta |
238 |
if qty>0:
|
| 14473 |
amit.gupta |
239 |
amount = unitPrice - offerDiscount - sdCash
|
|
|
240 |
amount = 0 if amount < 0 else amount
|
| 13760 |
amit.gupta |
241 |
|
| 14459 |
amit.gupta |
242 |
div1 = subOrderElement.find("div", {"class": "blk lrPad subordrs"})
|
|
|
243 |
if div1 is None:
|
| 13760 |
amit.gupta |
244 |
raise ParseException("subOrder", "Could not Parse suborders for Snapdeal")
|
|
|
245 |
|
| 14459 |
amit.gupta |
246 |
for strDiv in str(div1).split("<div class=\"seperator\"></div>"):
|
|
|
247 |
div = BeautifulSoup(strDiv)
|
| 13760 |
amit.gupta |
248 |
productTitle = str(subOrderElement.find("a").text)
|
|
|
249 |
productUrl = "http://m.snapdeal.com/" + productUrl
|
|
|
250 |
subOrder = SubOrder(productTitle, productUrl, placedOn, amountPaid)
|
|
|
251 |
|
|
|
252 |
subOrder.amountPaid = amountPaid
|
|
|
253 |
subOrder.deliveryCharges = deliveryCharges
|
|
|
254 |
subOrder.offerDiscount = offerDiscount
|
| 13809 |
amit.gupta |
255 |
subOrder.unitPrice = int(unitPrice)
|
| 13760 |
amit.gupta |
256 |
subOrder.productCode = re.findall(r'\d+$', productUrl)[0]
|
| 14415 |
amit.gupta |
257 |
subOrder.imgUrl = Mongo.getImgSrc(subOrder.productCode, self.store_id).get('thumbnail')
|
| 14458 |
amit.gupta |
258 |
cashbackStatus = Store.CB_NA
|
|
|
259 |
cashbackAmount = 0
|
|
|
260 |
percentage = 0
|
|
|
261 |
if amount > 0:
|
|
|
262 |
(cashbackAmount, percentage) = self.getCashbackAmount(subOrder.productCode, amount)
|
| 14473 |
amit.gupta |
263 |
if cashbackAmount > 0:
|
| 14476 |
amit.gupta |
264 |
cashbackStatus = Store.CB_PENDING
|
| 13760 |
amit.gupta |
265 |
subOrder.cashBackStatus = cashbackStatus
|
|
|
266 |
subOrder.cashBackAmount = cashbackAmount
|
| 14458 |
amit.gupta |
267 |
subOrder.cashBackPercentage = percentage
|
| 13760 |
amit.gupta |
268 |
|
|
|
269 |
|
|
|
270 |
trackAnchor = div.find("a")
|
|
|
271 |
if trackAnchor is not None:
|
|
|
272 |
subOrder.tracingkUrl = str(trackAnchor['href'])
|
|
|
273 |
|
|
|
274 |
divStr = str(div)
|
|
|
275 |
divStr = divStr.replace("\n","").replace("\t", "")
|
|
|
276 |
|
|
|
277 |
for line in divStr.split("<br />"):
|
|
|
278 |
if "Suborder ID" in line:
|
|
|
279 |
subOrder.merchantSubOrderId = re.findall(r'\d+', line)[0]
|
|
|
280 |
elif "Status" in line:
|
| 14402 |
amit.gupta |
281 |
print line
|
| 13760 |
amit.gupta |
282 |
subOrder.detailedStatus = re.findall('>(.*?)</span>', line, re.IGNORECASE)[0]
|
|
|
283 |
elif "Est. Shipping Date" in line:
|
|
|
284 |
subOrder.estimatedShippingDate = line.split(":")[1].strip()
|
|
|
285 |
elif "Est. Delivery Date" in line:
|
|
|
286 |
subOrder.estimatedDeliveryDate = line.split(":")[1].strip()
|
|
|
287 |
elif "Courier Name" in line:
|
|
|
288 |
subOrder.courierName = line.split(":")[1].strip()
|
|
|
289 |
elif "Tracking No" in line:
|
|
|
290 |
subOrder.trackingNumber = line.split(":")[1].strip()
|
| 13809 |
amit.gupta |
291 |
subOrders.append(subOrder)
|
|
|
292 |
return subOrders
|
| 13760 |
amit.gupta |
293 |
|
| 14854 |
amit.gupta |
294 |
def parseSubOrderB(self, subOrderElement, placedOn):
|
|
|
295 |
subOrders = []
|
|
|
296 |
prodDivs = subOrderElement.findAll('div', recursive=False)
|
|
|
297 |
prodDetailDiv = prodDivs[1].findAll('div', recursive=False)
|
|
|
298 |
|
|
|
299 |
offerDiscount = 0
|
|
|
300 |
deliveryCharges = None
|
|
|
301 |
amountPaid = 0
|
|
|
302 |
sdCash = 0
|
|
|
303 |
unitPrice = 0
|
|
|
304 |
|
|
|
305 |
paymentDivs = prodDivs[2].findAll('div', recursive=False)
|
|
|
306 |
for paymentDiv in paymentDivs:
|
|
|
307 |
strPaymentDiv = str(paymentDiv)
|
|
|
308 |
if "Unit Price" in strPaymentDiv:
|
| 14883 |
amit.gupta |
309 |
try:
|
|
|
310 |
unitPrice = int(re.findall(r'\d+', strPaymentDiv)[0])
|
|
|
311 |
except:
|
|
|
312 |
return None
|
| 14872 |
amit.gupta |
313 |
elif "Offer Discount" in strPaymentDiv:
|
|
|
314 |
offerDiscount += int(re.findall(r'\d+', strPaymentDiv)[0])
|
|
|
315 |
elif "Discount" in strPaymentDiv:
|
|
|
316 |
offerDiscount += int(re.findall(r'\d+', strPaymentDiv)[0])
|
| 14861 |
amit.gupta |
317 |
elif "SD Cash" in strPaymentDiv:
|
| 14854 |
amit.gupta |
318 |
sdCash = int(re.findall(r'\d+', strPaymentDiv)[0])
|
|
|
319 |
elif "Delivery Charges" in strPaymentDiv:
|
|
|
320 |
deliveryCharges = int(re.findall(r'\d+', strPaymentDiv)[0])
|
|
|
321 |
elif "Subtotal" in strPaymentDiv:
|
|
|
322 |
amountPaid = int(re.findall(r'\d+', paymentDiv.find('div', {'class':'itemPriceDetail'}).text)[0])
|
|
|
323 |
|
|
|
324 |
amount = unitPrice - offerDiscount - sdCash
|
|
|
325 |
|
|
|
326 |
imgDiv = prodDetailDiv[0]
|
|
|
327 |
otherDiv = prodDetailDiv[1]
|
|
|
328 |
productTitle = otherDiv.find('div',{'class':'orderName'}).text.strip()
|
|
|
329 |
|
|
|
330 |
productUrl = imgDiv.a['href']
|
|
|
331 |
subOrder = SubOrder(productTitle, productUrl, placedOn, amountPaid)
|
| 14863 |
amit.gupta |
332 |
subOrder.merchantSubOrderId = prodDivs[0].text.split(':')[1].strip()
|
| 14854 |
amit.gupta |
333 |
subOrder.detailedStatus = otherDiv.find('div',{'class':'orderStatus'}).span.text.strip()
|
| 15882 |
amit.gupta |
334 |
if subOrder.detailedStatus.lower() == "processing":
|
|
|
335 |
processingDetailedStatus = subOrderElement.find('div', {'class':'trackingMessage'}).text.strip()
|
|
|
336 |
if processingDetailedStatus.lower() == 'a new order placed with a different seller':
|
|
|
337 |
subOrder.detailedStatus = processingDetailedStatus
|
| 14854 |
amit.gupta |
338 |
deliveryStatus = otherDiv.find('div',{'class':'orderDelivery'})
|
|
|
339 |
if deliveryStatus is not None:
|
|
|
340 |
delString = deliveryStatus.text.strip()
|
|
|
341 |
arr = delString.split(':')
|
|
|
342 |
if "On" in arr[0]:
|
|
|
343 |
subOrder.deliveredOn = arr[1].strip()
|
|
|
344 |
elif "Exp. Delivery by" in arr[0]:
|
|
|
345 |
subOrder.estimatedDeliveryDate = arr[1].strip()
|
| 15877 |
amit.gupta |
346 |
elif "Est. delivery between" in arr[0]:
|
| 15880 |
amit.gupta |
347 |
subOrder.estimatedDeliveryDate = arr[0].split("between")[1].strip()
|
| 15881 |
amit.gupta |
348 |
elif "Est. shipping between" in arr[0]:
|
|
|
349 |
subOrder.estimatedShippingDate = arr[0].split("between")[1].strip()
|
| 14854 |
amit.gupta |
350 |
else:
|
|
|
351 |
subOrder.estimatedShippingDate = arr[1].strip()
|
|
|
352 |
|
|
|
353 |
subOrder.imgUrl = imgDiv.a.img['src']
|
|
|
354 |
subOrder.productCode = re.findall(r'\d+$', productUrl)[0]
|
|
|
355 |
subOrder.deliveryCharges = deliveryCharges
|
|
|
356 |
subOrder.offerDiscount = offerDiscount
|
|
|
357 |
subOrder.unitPrice = int(unitPrice)
|
|
|
358 |
cashbackStatus = Store.CB_NA
|
|
|
359 |
cashbackAmount = 0
|
|
|
360 |
percentage = 0
|
|
|
361 |
if amountPaid > 0:
|
|
|
362 |
(cashbackAmount, percentage) = self.getCashbackAmount(subOrder.productCode, amount)
|
|
|
363 |
if cashbackAmount > 0:
|
|
|
364 |
cashbackStatus = Store.CB_PENDING
|
|
|
365 |
subOrder.cashBackStatus = cashbackStatus
|
|
|
366 |
subOrder.cashBackAmount = cashbackAmount
|
|
|
367 |
subOrder.cashBackPercentage = percentage
|
|
|
368 |
|
|
|
369 |
|
|
|
370 |
courierDet = subOrderElement.find('div', {'class':'courierDetail'})
|
|
|
371 |
if courierDet is not None:
|
|
|
372 |
subOrder.courierName = courierDet.span.text.strip()
|
|
|
373 |
trackingDet = subOrderElement.find('div', {'class':'trackingNo'})
|
|
|
374 |
if trackingDet is not None:
|
|
|
375 |
subOrder.trackingUrl = trackingDet.span.a['href']
|
|
|
376 |
subOrder.trackingNumber = trackingDet.span.a.text.strip()
|
|
|
377 |
|
|
|
378 |
subOrders.append(subOrder)
|
|
|
379 |
return subOrder
|
| 17387 |
amit.gupta |
380 |
|
|
|
381 |
def getOrderJSON(self, rawHtml, supcMap):
|
|
|
382 |
#print rawHtml
|
|
|
383 |
# replace_with = {
|
|
|
384 |
# '<': '>',
|
|
|
385 |
# '>': '<',
|
|
|
386 |
# '&': '&',
|
|
|
387 |
# '"': '"', # should be escaped in attributes
|
|
|
388 |
# "'": ''' # should be escaped in attributes
|
|
|
389 |
# }
|
|
|
390 |
pq = PyQuery(rawHtml)
|
|
|
391 |
jsonValue = pq("#orderJSON").attr("value")
|
|
|
392 |
jsonValue.replace(""", '"')
|
|
|
393 |
jsonValue.replace("&", '&')
|
|
|
394 |
jsonValue.replace(">", '>')
|
|
|
395 |
jsonValue.replace("<", '<')
|
|
|
396 |
jsonValue.replace("'", "'")
|
|
|
397 |
allSupcElements = pq('div.mdt-layout')('div.mdt-card')('div.order-item')
|
|
|
398 |
for supcElement in allSupcElements:
|
|
|
399 |
try:
|
|
|
400 |
supcElement = pq(supcElement)
|
|
|
401 |
title = supcElement('div.order-heading').text().strip()
|
|
|
402 |
productUrl = supcElement.attr("data-href")
|
|
|
403 |
imgUrl = supcElement.find('img').attr('src')
|
|
|
404 |
supc = imgUrl.split('-')[-3]
|
|
|
405 |
supcMap[supc] = {'title':title, 'imgUrl':imgUrl, 'productUrl':productUrl}
|
|
|
406 |
except:
|
|
|
407 |
pass
|
|
|
408 |
return json.loads(jsonValue)
|
| 14854 |
amit.gupta |
409 |
|
| 13576 |
amit.gupta |
410 |
def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
|
| 13760 |
amit.gupta |
411 |
#print merchantOrder
|
| 13796 |
amit.gupta |
412 |
resp = {}
|
| 17387 |
amit.gupta |
413 |
url = ORDER_TRACK_URL + re.findall('.*(\?.*?)$', orderSuccessUrl,re.IGNORECASE)[0]
|
|
|
414 |
supcMap = {}
|
| 13582 |
amit.gupta |
415 |
try:
|
| 14854 |
amit.gupta |
416 |
try:
|
| 17387 |
amit.gupta |
417 |
orderJSON = self.getOrderJSON(rawHtml, supcMap)
|
| 14854 |
amit.gupta |
418 |
except:
|
| 14861 |
amit.gupta |
419 |
traceback.print_exc()
|
| 17387 |
amit.gupta |
420 |
try:
|
|
|
421 |
page = fetchResponseUsingProxy(orderSuccessUrl)
|
|
|
422 |
orderJSON = self.getOrderJSON(page,supcMap)
|
|
|
423 |
except:
|
|
|
424 |
traceback.print_exc()
|
|
|
425 |
orderJSON = None
|
|
|
426 |
if orderJSON is None:
|
|
|
427 |
page =fetchResponseUsingProxy(url)
|
|
|
428 |
page = ungzipResponse(page)
|
|
|
429 |
try:
|
|
|
430 |
merchantOrder = self._parseB(orderId, subTagId, userId, page, orderSuccessUrl)
|
|
|
431 |
except:
|
|
|
432 |
traceback.print_exc()
|
|
|
433 |
merchantOrder = self._parse(orderId, subTagId, userId, page, orderSuccessUrl)
|
|
|
434 |
else:
|
|
|
435 |
merchantOrder = self._parseC(orderId, subTagId, userId, supcMap, orderJSON, orderSuccessUrl)
|
| 14854 |
amit.gupta |
436 |
|
| 14312 |
amit.gupta |
437 |
merchantOrder.orderTrackingUrl = url
|
|
|
438 |
|
|
|
439 |
if self._saveToOrder(todict(merchantOrder)):
|
|
|
440 |
resp['result'] = 'ORDER_CREATED'
|
|
|
441 |
else:
|
|
|
442 |
resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
|
| 17387 |
amit.gupta |
443 |
print "=================", resp, orderId, "=============="
|
| 13796 |
amit.gupta |
444 |
return resp
|
| 13582 |
amit.gupta |
445 |
except:
|
|
|
446 |
print "Error occurred"
|
| 13603 |
amit.gupta |
447 |
traceback.print_exc()
|
| 14312 |
amit.gupta |
448 |
resp['result'] = 'ORDER_NOT_CREATED'
|
| 17387 |
amit.gupta |
449 |
print "=================", resp, orderId, "=============="
|
| 13796 |
amit.gupta |
450 |
return resp
|
| 13781 |
amit.gupta |
451 |
|
| 13569 |
amit.gupta |
452 |
|
|
|
453 |
#soup = BeautifulSoup(rawHtml,convertEntities=BeautifulSoup.HTML_ENTITIES)
|
|
|
454 |
#soup.find(name, attrs, recursive, text)
|
| 17387 |
amit.gupta |
455 |
def _parseC(self, orderId, subTagId, userId, supcMap, orderJSON, orderSuccessUrl):
|
|
|
456 |
print orderJSON
|
|
|
457 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
|
|
458 |
placedOn = datetime.strftime(utils.fromTimeStamp(orderJSON['created']/1000), "%a, %d %b, %Y")
|
|
|
459 |
merchantOrder.placedOn = placedOn
|
|
|
460 |
merchantOrder.merchantOrderId = orderJSON['code']
|
|
|
461 |
merchantOrder.paidAmount = orderJSON['paidAmount']
|
|
|
462 |
merchantOrder.deliveryCharges = orderJSON['shippingCharges']
|
|
|
463 |
merchantOrder.closed= False
|
|
|
464 |
merchantSubOrders = []
|
|
|
465 |
for s in orderJSON['suborders']:
|
|
|
466 |
print s
|
|
|
467 |
if not supcMap.has_key(s['supcCode']):
|
|
|
468 |
url = "http://www.snapdeal.com/search/autoSuggestion?q=%s&catId=0&ver=3"%s['supcCode']
|
|
|
469 |
html = utils.fetchResponseUsingProxy(url)
|
|
|
470 |
ul = PyQuery(html)('ul.top-products')
|
|
|
471 |
title = ul('div.product-text').text().strip()
|
|
|
472 |
productUrl = ul('a').attr("href").split("?")[0]
|
|
|
473 |
imgUrl = ul('img').attr('src')
|
|
|
474 |
supcMap[s['supcCode']] = {'title':title, 'imgUrl':imgUrl, 'productUrl':productUrl}
|
|
|
475 |
map1 = supcMap[s['supcCode']]
|
|
|
476 |
|
|
|
477 |
amountPaid = s['paidAmount']
|
|
|
478 |
productTitle = map1['title']
|
|
|
479 |
productUrl = map1['productUrl']
|
|
|
480 |
subOrder = SubOrder(productTitle, productUrl, placedOn, amountPaid)
|
|
|
481 |
if(s.get('deliveryDate') is not None):
|
|
|
482 |
print "Delivered On",
|
|
|
483 |
subOrder.deliveredOn = datetime.strftime(utils.fromTimeStamp(s.get('deliveryDate')/1000),'%Y-%m-%d')
|
|
|
484 |
subOrder.status = MStore.ORDER_DELIVERED
|
|
|
485 |
subOrder.detailedStatus = MStore.ORDER_DELIVERED
|
|
|
486 |
elif s['suborderStatus'].get('macroDescription')== 'Closed':
|
|
|
487 |
if s['suborderStatus'].get('value')== 'Close for vendor reallocation':
|
|
|
488 |
subOrder.detailedStatus = 'Close for vendor reallocation'
|
|
|
489 |
subOrder.status = MStore.ORDER_CANCELLED
|
|
|
490 |
|
|
|
491 |
try:
|
|
|
492 |
subOrder.detailedStatus = s['suborderStatus']['macroDescription']
|
|
|
493 |
subOrder.status = self._getStatusFromDetailedStatus(subOrder.detailedStatus)
|
|
|
494 |
except:
|
|
|
495 |
print "----------------", s['suborderStatus']
|
| 13576 |
amit.gupta |
496 |
|
| 17387 |
amit.gupta |
497 |
subOrder.merchantSubOrderId = s['code']
|
|
|
498 |
subOrder.deliveryCharges = s['shippingCharges']
|
| 17389 |
amit.gupta |
499 |
subOrder.productCode = re.findall(r'\d+$', productUrl)[0]
|
| 17387 |
amit.gupta |
500 |
subOrder.imgUrl = map1['imgUrl']
|
|
|
501 |
subOrder.unitPrice = s['offerPrice'] -s['internalCashbackValue'] - s['externalCashbackValue']
|
|
|
502 |
subOrder.amount = subOrder.unitPrice - s['offerDiscount'] - s['sdCash']
|
|
|
503 |
try:
|
|
|
504 |
try:
|
|
|
505 |
if s['shipDateRange']['start']==s['shipDateRange']['end']:
|
|
|
506 |
subOrder.estimatedShippingDate = datetime.strftime(utils.fromTimeStamp(s['shipDateRange']['start']/1000),'%Y-%m-%d')
|
|
|
507 |
else:
|
|
|
508 |
subOrder.estimatedShippingDate = datetime.strftime(utils.fromTimeStamp(s['shipDateRange']['start']/1000),'%Y-%m-%d') + " - " + datetime.strftime(utils.fromTimeStamp(s['shipDateRange']['end']/1000),'%Y-%m-%d')
|
|
|
509 |
except:
|
|
|
510 |
if s['deliveryDateRange']['start']==s['deliveryDateRange']['end']:
|
|
|
511 |
subOrder.estimatedDeliveryDate = datetime.strftime(utils.fromTimeStamp(s['deliveryDateRange']['start']/1000),'%Y-%m-%d')
|
|
|
512 |
else:
|
|
|
513 |
subOrder.estimatedDeliveryDate = datetime.strftime(utils.fromTimeStamp(s['deliveryDateRange']['start']/1000),'%Y-%m-%d') + " - " + datetime.strftime('%Y-%m-%d',utils.fromTimeStamp(s['deliveryDateRange']['end']/1000),'%Y-%m-%d')
|
|
|
514 |
except:
|
|
|
515 |
pass
|
|
|
516 |
subOrder.offerDiscount = s['offerDiscount']
|
|
|
517 |
subOrder.unitPrice = s['offerPrice']
|
|
|
518 |
merchantSubOrders.append(subOrder)
|
|
|
519 |
|
|
|
520 |
merchantOrder.subOrders = merchantSubOrders
|
|
|
521 |
self.populateDerivedFields(merchantOrder)
|
|
|
522 |
return merchantOrder
|
|
|
523 |
|
| 13576 |
amit.gupta |
524 |
def _getStatusFromDetailedStatus(self, detailedStatus):
|
|
|
525 |
for key, value in Store.OrderStatusMap.iteritems():
|
| 14678 |
amit.gupta |
526 |
if detailedStatus.lower() in value:
|
| 13576 |
amit.gupta |
527 |
return key
|
| 14675 |
amit.gupta |
528 |
print "Detailed Status need to be mapped", detailedStatus, self.store_id
|
| 14861 |
amit.gupta |
529 |
return None
|
| 13569 |
amit.gupta |
530 |
|
| 13610 |
amit.gupta |
531 |
|
| 13569 |
amit.gupta |
532 |
def scrapeStoreOrders(self,):
|
| 13760 |
amit.gupta |
533 |
#collectionMap = {'palcedOn':1}
|
| 13576 |
amit.gupta |
534 |
orders = self._getActiveOrders()
|
|
|
535 |
for order in orders:
|
| 14696 |
amit.gupta |
536 |
print "Order", self.store_name, order['orderId']
|
| 14398 |
amit.gupta |
537 |
try:
|
|
|
538 |
url = ORDER_TRACK_URL + re.findall('.*(\?.*?)$', order['orderSuccessUrl'],re.IGNORECASE)[0]
|
| 14758 |
amit.gupta |
539 |
page = fetchResponseUsingProxy(url)
|
| 14398 |
amit.gupta |
540 |
#page=page.decode("utf-8")
|
| 14861 |
amit.gupta |
541 |
soup = BeautifulSoup(page)
|
|
|
542 |
try:
|
|
|
543 |
self.tryBParsing(order, soup)
|
|
|
544 |
except:
|
|
|
545 |
traceback.print_exc()
|
|
|
546 |
sections = soup.findAll("section")
|
|
|
547 |
orderEl = sections[1]
|
|
|
548 |
orderTrs = orderEl.findAll("tr")
|
|
|
549 |
|
|
|
550 |
placedOn = str(orderTrs[0].findAll("td")[1].text)
|
|
|
551 |
sections.pop(0)
|
|
|
552 |
sections.pop(0)
|
|
|
553 |
|
|
|
554 |
subOrders = sections
|
|
|
555 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
|
|
556 |
closed = True
|
|
|
557 |
for subOrderElement in subOrders:
|
|
|
558 |
div1 = subOrderElement.findAll("div", {"class": "blk lrPad subordrs"})
|
|
|
559 |
if len(div1)<=0:
|
|
|
560 |
raise ParseException("subOrder", "Could not Parse suborders for Snapdeal")
|
|
|
561 |
subOrder = None
|
|
|
562 |
breakFlag = False
|
|
|
563 |
for strDiv in str(div1).split("<div class=\"seperator\"></div>"):
|
|
|
564 |
div = BeautifulSoup(strDiv)
|
|
|
565 |
divStr = str(div)
|
|
|
566 |
divStr = divStr.replace("\n","").replace("\t", "")
|
|
|
567 |
updateMap = {}
|
|
|
568 |
for line in divStr.split("<br />"):
|
|
|
569 |
if "Suborder ID" in line:
|
|
|
570 |
merchantSubOrderId = re.findall(r'\d+', line)[0]
|
|
|
571 |
#break if suborder is inactive
|
|
|
572 |
subOrder = self._isSubOrderActive(order, merchantSubOrderId)
|
|
|
573 |
if subOrder is None:
|
|
|
574 |
subOrders = self.parseSubOrder(subOrderElement, placedOn)
|
|
|
575 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict(subOrders)}}})
|
|
|
576 |
print "Added new suborders to Order id - ", order['orderId']
|
|
|
577 |
closed = False
|
|
|
578 |
breakFlag = True
|
|
|
579 |
break
|
|
|
580 |
elif subOrder['closed']:
|
|
|
581 |
breakFlag = True
|
|
|
582 |
break
|
|
|
583 |
else:
|
|
|
584 |
findMap = {"orderId": order['orderId'], "subOrders.merchantSubOrderId": merchantSubOrderId}
|
|
|
585 |
elif "Status :" in line:
|
|
|
586 |
detailedStatus = re.findall('>(.*?)</span>', line, re.IGNORECASE)[0]
|
|
|
587 |
updateMap["subOrders.$.detailedStatus"] = detailedStatus
|
|
|
588 |
status = self._getStatusFromDetailedStatus(detailedStatus)
|
|
|
589 |
closedStatus = status in [Store.ORDER_DELIVERED, Store.ORDER_CANCELLED]
|
|
|
590 |
if status is not None:
|
|
|
591 |
updateMap["subOrders.$.status"] = status
|
|
|
592 |
if detailedStatus == 'Closed For Vendor Reallocation':
|
|
|
593 |
#if it is more than 6hours mark closed.
|
|
|
594 |
closeAt = subOrder.get("closeAt")
|
|
|
595 |
if closeAt is None:
|
|
|
596 |
closeAt = datetime.now() + timedelta(hours=6)
|
|
|
597 |
updateMap["subOrders.$.closeAt"] = datetime.strftime(closeAt,"%Y-%m-%d %H:%M:%S")
|
|
|
598 |
else:
|
|
|
599 |
closeAt = datetime.strptime(closeAt,"%Y-%m-%d %H:%M:%S")
|
|
|
600 |
if datetime.now() > closeAt:
|
|
|
601 |
closedStatus = True
|
| 16969 |
amit.gupta |
602 |
#Close if not applicable suborders are not closed
|
|
|
603 |
if utils.fromTimeStamp(order['createdOnInt'] + 35*86400*1000) < datetime.now() and subOrder['cashBackStatus']==utils.CB_NA:
|
|
|
604 |
closedStatus=True
|
| 14861 |
amit.gupta |
605 |
|
|
|
606 |
|
|
|
607 |
if closedStatus:
|
|
|
608 |
#if status is closed then change the paybackStatus accordingly
|
|
|
609 |
updateMap["subOrders.$.closed"] = True
|
|
|
610 |
if status == Store.ORDER_DELIVERED:
|
|
|
611 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
612 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_APPROVED
|
|
|
613 |
elif status == Store.ORDER_CANCELLED:
|
|
|
614 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
615 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_CANCELLED
|
|
|
616 |
|
| 14398 |
amit.gupta |
617 |
else:
|
| 14861 |
amit.gupta |
618 |
closed = False
|
|
|
619 |
elif "Est. Shipping Date" in line:
|
|
|
620 |
estimatedShippingDate = line.split(":")[1].strip()
|
|
|
621 |
updateMap["subOrders.$.estimatedShippingDate"] = estimatedShippingDate
|
|
|
622 |
elif "Est. Delivery Date" in line:
|
|
|
623 |
estimatedDeliveryDate = line.split(":")[1].strip()
|
|
|
624 |
updateMap["subOrders.$.estimatedDeliveryDate"] = estimatedDeliveryDate
|
|
|
625 |
elif "Courier Name" in line:
|
|
|
626 |
courierName = line.split(":")[1].strip()
|
|
|
627 |
updateMap["subOrders.$.courierName"] = courierName
|
|
|
628 |
elif "Tracking No" in line:
|
|
|
629 |
trackingNumber = line.split(":")[1].strip()
|
|
|
630 |
updateMap["subOrders.$.trackingNumber"] = trackingNumber
|
|
|
631 |
|
|
|
632 |
if breakFlag:
|
|
|
633 |
continue
|
|
|
634 |
|
|
|
635 |
bulk.find(findMap).update({'$set' : updateMap})
|
|
|
636 |
bulk.find({'orderId': order['orderId']}).update({'$set':{'closed': closed,"parseError":False}})
|
|
|
637 |
result = bulk.execute()
|
|
|
638 |
tprint(result)
|
| 14398 |
amit.gupta |
639 |
except:
|
| 14847 |
amit.gupta |
640 |
tprint("Could not update " + str(order['orderId']) + "For store " + self.getName())
|
| 14692 |
amit.gupta |
641 |
self.db.merchantOrder.update({"orderId":order['orderId']}, {"$set":{"parseError":True}})
|
| 14398 |
amit.gupta |
642 |
traceback.print_exc()
|
| 13576 |
amit.gupta |
643 |
|
| 14854 |
amit.gupta |
644 |
def tryBParsing(self, order, soup):
|
|
|
645 |
orderDetailContainerDivs = soup.body.find("div", {'class':'cardLayoutWrap'}).findAll('div', recursive=False)
|
|
|
646 |
orderDetailDiv = orderDetailContainerDivs.pop(0)
|
|
|
647 |
placedOn = orderDetailDiv.span.text.split(':')[1].strip()
|
|
|
648 |
|
|
|
649 |
orderDetailContainerDivs.pop(0)
|
|
|
650 |
|
|
|
651 |
subOrders = orderDetailContainerDivs
|
|
|
652 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
|
|
653 |
closed = True
|
|
|
654 |
for subOrderElement in subOrders:
|
|
|
655 |
prodDivs = subOrderElement.findAll('div', recursive=False)
|
|
|
656 |
merchantSubOrderId = prodDivs[0].text.split(':')[1].strip()
|
|
|
657 |
subOrder = None
|
| 14861 |
amit.gupta |
658 |
subOrder = self._isSubOrderActive(order, merchantSubOrderId)
|
|
|
659 |
if subOrder is None:
|
| 14864 |
amit.gupta |
660 |
try:
|
| 14883 |
amit.gupta |
661 |
subOrder = self.parseSubOrderB(subOrderElement, placedOn)
|
|
|
662 |
if subOrder is None:
|
|
|
663 |
continue
|
|
|
664 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict([subOrder])}}})
|
| 14864 |
amit.gupta |
665 |
print "Added new suborders to Order id - ", order['orderId']
|
|
|
666 |
closed = False
|
|
|
667 |
except:
|
|
|
668 |
pass
|
| 14861 |
amit.gupta |
669 |
continue
|
|
|
670 |
elif subOrder['closed']:
|
|
|
671 |
continue
|
|
|
672 |
else:
|
| 14864 |
amit.gupta |
673 |
prodDetailDiv = prodDivs[1].findAll('div', recursive=False)
|
|
|
674 |
otherDiv = prodDetailDiv[1]
|
|
|
675 |
trackBlock = subOrderElement.find('div',{'class':'trackingDetailsBlock'})
|
| 14861 |
amit.gupta |
676 |
findMap = {"orderId": order['orderId'], "subOrders.merchantSubOrderId": merchantSubOrderId}
|
|
|
677 |
updateMap = {}
|
|
|
678 |
detailedStatus = otherDiv.find('div',{'class':'orderStatus'}).span.text.strip()
|
| 16298 |
amit.gupta |
679 |
|
| 15882 |
amit.gupta |
680 |
if 'A new order placed with a different seller' in str(trackBlock):
|
| 14861 |
amit.gupta |
681 |
#if it is more than 6hours mark closed.
|
|
|
682 |
closeAt = subOrder.get("closeAt")
|
|
|
683 |
if closeAt is None:
|
|
|
684 |
closeAt = datetime.now() + timedelta(hours=6)
|
|
|
685 |
updateMap["subOrders.$.closeAt"] = datetime.strftime(closeAt,"%Y-%m-%d %H:%M:%S")
|
| 16298 |
amit.gupta |
686 |
bulk.find(findMap).update({'$set' : updateMap})
|
| 16301 |
amit.gupta |
687 |
closed=False
|
| 16298 |
amit.gupta |
688 |
continue
|
| 14854 |
amit.gupta |
689 |
else:
|
| 14861 |
amit.gupta |
690 |
closeAt = datetime.strptime(closeAt,"%Y-%m-%d %H:%M:%S")
|
|
|
691 |
if datetime.now() > closeAt:
|
| 16298 |
amit.gupta |
692 |
detailedStatus = 'A new order placed with a different seller'
|
| 14861 |
amit.gupta |
693 |
|
| 16298 |
amit.gupta |
694 |
|
|
|
695 |
status = self._getStatusFromDetailedStatus(detailedStatus)
|
|
|
696 |
closedStatus = status in [Store.ORDER_DELIVERED, Store.ORDER_CANCELLED]
|
|
|
697 |
updateMap["subOrders.$.detailedStatus"] = detailedStatus
|
|
|
698 |
if status is not None:
|
|
|
699 |
updateMap["subOrders.$.status"] = status
|
| 14861 |
amit.gupta |
700 |
|
|
|
701 |
if closedStatus:
|
|
|
702 |
#if status is closed then change the paybackStatus accordingly
|
|
|
703 |
updateMap["subOrders.$.closed"] = True
|
|
|
704 |
if status == Store.ORDER_DELIVERED:
|
|
|
705 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
706 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_APPROVED
|
|
|
707 |
elif status == Store.ORDER_CANCELLED:
|
|
|
708 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
709 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_CANCELLED
|
|
|
710 |
|
|
|
711 |
else:
|
|
|
712 |
closed = False
|
| 14854 |
amit.gupta |
713 |
|
| 14861 |
amit.gupta |
714 |
deliveryStatus = otherDiv.find('div',{'class':'orderDelivery'})
|
|
|
715 |
if deliveryStatus is not None:
|
|
|
716 |
delString = deliveryStatus.text.strip()
|
|
|
717 |
arr = delString.split(':')
|
|
|
718 |
if "On" in arr[0]:
|
|
|
719 |
updateMap['subOrders.$.deliveredOn'] = arr[1].strip()
|
|
|
720 |
elif "Exp. Delivery by" in arr[0]:
|
|
|
721 |
updateMap['subOrders.$.estimatedDeliveryDate'] = arr[1].strip()
|
| 15877 |
amit.gupta |
722 |
elif "Est. delivery between" in arr[0]:
|
|
|
723 |
updateMap['subOrders.$.estimatedDeliveryDate'] = delString.split("between")[1].strip()
|
| 17237 |
amit.gupta |
724 |
elif "Est. shipping between" in arr[0]:
|
|
|
725 |
updateMap['subOrders.$.estimatedShippingDate'] = delString.split("between")[1].strip()
|
| 14861 |
amit.gupta |
726 |
else:
|
|
|
727 |
updateMap['subOrders.$.estimatedShippingDate'] = arr[1].strip()
|
|
|
728 |
courierDet = subOrderElement.find('div', {'class':'courierDetail'})
|
|
|
729 |
if courierDet is not None:
|
|
|
730 |
updateMap['subOrders.$.courierName'] = courierDet.span.text.strip()
|
|
|
731 |
trackingDet = subOrderElement.find('div', {'class':'trackingNo'})
|
|
|
732 |
if trackingDet is not None:
|
|
|
733 |
updateMap['subOrders.$.trackingUrl'] = trackingDet.span.a['href']
|
|
|
734 |
updateMap['subOrders.$.trackingNumber'] = trackingDet.span.a.text.strip()
|
| 14854 |
amit.gupta |
735 |
bulk.find(findMap).update({'$set' : updateMap})
|
|
|
736 |
bulk.find({'orderId': order['orderId']}).update({'$set':{'closed': closed,"parseError":False}})
|
|
|
737 |
result = bulk.execute()
|
|
|
738 |
tprint(result)
|
|
|
739 |
|
| 13576 |
amit.gupta |
740 |
|
| 17234 |
amit.gupta |
741 |
def _saveToAffiliate(self, offers, status):
|
| 16946 |
amit.gupta |
742 |
collection = self.db.snapdealOrderAffiliateInfo1
|
|
|
743 |
#mcollection = self.db.merchantOrder
|
| 14443 |
amit.gupta |
744 |
for offer in offers:
|
| 16946 |
amit.gupta |
745 |
count = 0
|
|
|
746 |
for row in offers:
|
|
|
747 |
if count==0:
|
|
|
748 |
count += 1
|
|
|
749 |
continue
|
|
|
750 |
offer = self.covertToObj(row)
|
|
|
751 |
if offer.orderId:
|
| 17048 |
amit.gupta |
752 |
dict1 = todict(offer)
|
| 17166 |
amit.gupta |
753 |
dict1["_id"] = dict1["orderId"] + "-" + dict1["productCode"]
|
| 17234 |
amit.gupta |
754 |
dict1['status'] = status
|
| 17048 |
amit.gupta |
755 |
collection.save(dict1)
|
| 16946 |
amit.gupta |
756 |
# def _saveToAffiliate(self, offers):
|
|
|
757 |
# collection = self.db.snapdealOrderAffiliateInfo
|
|
|
758 |
# mcollection = self.db.merchantOrder
|
|
|
759 |
# for offer in offers:
|
|
|
760 |
# offer = self.covertToObj(offer)
|
|
|
761 |
# collection.update({"adId":offer.adId, "saleAmount":offer.saleAmount, "payOut":offer.payOut},{"$set":todict(offer)}, upsert=True)
|
|
|
762 |
# mcollection.update({"subTagId":offer.subTagId, "storeId":self.store_id, "subOrders.missingAff":True}, {"$set":{"subOrders.$.missingAff":False}})
|
| 13569 |
amit.gupta |
763 |
|
|
|
764 |
|
|
|
765 |
def _getAllOffers(self, br, token):
|
|
|
766 |
allOffers = []
|
|
|
767 |
nextPage = 1
|
|
|
768 |
while True:
|
|
|
769 |
data = getPostData(token, nextPage)
|
|
|
770 |
response = br.open(POST_URL, data)
|
| 13680 |
amit.gupta |
771 |
rmap = json.loads(ungzipResponse(response))
|
| 13569 |
amit.gupta |
772 |
if rmap is not None:
|
|
|
773 |
rmap = rmap['response']
|
| 14492 |
amit.gupta |
774 |
print rmap
|
| 13569 |
amit.gupta |
775 |
if rmap is not None and len(rmap['errors'])==0:
|
|
|
776 |
allOffers += rmap['data']['data']
|
|
|
777 |
nextPage += 1
|
|
|
778 |
if rmap['data']['pageCount']<nextPage:
|
|
|
779 |
break
|
|
|
780 |
|
|
|
781 |
return allOffers
|
|
|
782 |
|
| 16946 |
amit.gupta |
783 |
# def covertToObj(self,offer):
|
|
|
784 |
# offerData = offer['Stat']
|
|
|
785 |
# offer1 = AffiliateInfo(offerData['affiliate_info1'], self.store_id, offerData['conversion_status'], offerData['ad_id'],
|
|
|
786 |
# offerData['datetime'], int(float(offerData['payout'])), offer['Offer']['name'], offerData['ip'], int(float(offerData['conversion_sale_amount'])))
|
|
|
787 |
# offer1.saleTime = int(time.mktime(datetime.strptime(offer1.saleDate, "%Y-%m-%d %H:%M:%S").timetuple()))
|
|
|
788 |
# return offer1
|
| 16975 |
amit.gupta |
789 |
def parseInfo(self,):
|
|
|
790 |
from pyquery import PyQuery as pq
|
| 16985 |
amit.gupta |
791 |
orders = list(session.query(Orders).filter_by(store_id=self.store_id).filter_by(status='ORDER_CREATED').group_by(Orders.user_id).all())
|
| 16975 |
amit.gupta |
792 |
try:
|
|
|
793 |
for order in orders:
|
|
|
794 |
try:
|
|
|
795 |
doc = pq(order.rawhtml)
|
| 16985 |
amit.gupta |
796 |
a1= " ".join(["" if not div.text else div.text.replace("\t","").replace("\n","").strip() for div in pq(doc('article')[-1])('div')]).strip()
|
|
|
797 |
a2 = ",".join(["" if not div.text else div.text.replace("\t","").replace("\n","").replace(" ", "") for div in pq(doc('article')[-2])('div')]).strip()
|
|
|
798 |
user_address = All_user_addresses()
|
|
|
799 |
user_address.address = a1
|
| 16975 |
amit.gupta |
800 |
all = a2.split(",")
|
| 16985 |
amit.gupta |
801 |
user_address.source = 'order'
|
|
|
802 |
user_address.user_id = order.user_id
|
|
|
803 |
#user_address. = all[3].split(":")[1]
|
|
|
804 |
#user_address. = all[2].split(":")[1]
|
|
|
805 |
#orderInfo.mobile = all[-1].split(":")[1]
|
| 16977 |
amit.gupta |
806 |
adSplit = a1.split(",")
|
| 16985 |
amit.gupta |
807 |
user_address.city = adSplit[-2].strip()
|
|
|
808 |
user_address.pincode = adSplit[-1].strip().split(" ")[0]
|
| 16991 |
amit.gupta |
809 |
user_address.state = adSplit[-1].strip().split(" ")[1]
|
| 16975 |
amit.gupta |
810 |
session.commit()
|
|
|
811 |
except:
|
|
|
812 |
session.rollback()
|
|
|
813 |
continue
|
|
|
814 |
finally:
|
|
|
815 |
session.close()
|
| 16946 |
amit.gupta |
816 |
|
| 13569 |
amit.gupta |
817 |
def covertToObj(self,offer):
|
| 16946 |
amit.gupta |
818 |
product,category,order_code,quantity,price,sales,commission_rate,commission_earned,datetime1,affiliate_sub_id1,affiliate_sub_id2 = offer
|
|
|
819 |
offer1 = AffiliateInfo(affiliate_sub_id1, 3, None, None, utils.toTimeStamp(datetime.strptime(datetime1, "%m-%d-%Y %H:%M")),
|
| 16997 |
amit.gupta |
820 |
|
| 16946 |
amit.gupta |
821 |
offer1.orderId = order_code if order_code else None
|
|
|
822 |
offer1.productCode = product
|
|
|
823 |
offer1.unitPrice = int(float(price))
|
|
|
824 |
offer1.quantity = int(quantity)
|
| 16997 |
amit.gupta |
825 |
offer1.payOut
|
| 13569 |
amit.gupta |
826 |
return offer1
|
|
|
827 |
def getPostData(token, page = 1, limit= 20, startDate=None, endDate=None):
|
| 13680 |
amit.gupta |
828 |
endDate=date.today() + timedelta(days=1)
|
|
|
829 |
startDate=endDate - timedelta(days=31)
|
| 13569 |
amit.gupta |
830 |
|
|
|
831 |
parameters = (
|
|
|
832 |
("page",str(page)),
|
|
|
833 |
("limit",str(limit)),
|
|
|
834 |
("fields[]","Stat.offer_id"),
|
|
|
835 |
("fields[]","Stat.datetime"),
|
|
|
836 |
("fields[]","Offer.name"),
|
|
|
837 |
("fields[]","Stat.conversion_status"),
|
|
|
838 |
("fields[]","Stat.conversion_sale_amount"),
|
|
|
839 |
("fields[]","Stat.payout"),
|
|
|
840 |
("fields[]","Stat.ip"),
|
|
|
841 |
("fields[]","Stat.ad_id"),
|
|
|
842 |
("fields[]","Stat.affiliate_info1"),
|
|
|
843 |
("sort[Stat.datetime]","desc"),
|
|
|
844 |
("filters[Stat.date][conditional]","BETWEEN"),
|
|
|
845 |
("filters[Stat.date][values][]",startDate.strftime('%Y-%m-%d')),
|
|
|
846 |
("filters[Stat.date][values][]",endDate.strftime('%Y-%m-%d')),
|
|
|
847 |
("data_start",startDate.strftime('%Y-%m-%d')),
|
|
|
848 |
("data_end",endDate.strftime('%Y-%m-%d')),
|
|
|
849 |
("Method","getConversions"),
|
|
|
850 |
("NetworkId","jasper"),
|
|
|
851 |
("SessionToken",token),
|
|
|
852 |
)
|
|
|
853 |
#Encode the parameters
|
|
|
854 |
return urllib.urlencode(parameters)
|
|
|
855 |
|
| 16975 |
amit.gupta |
856 |
|
| 13569 |
amit.gupta |
857 |
def main():
|
| 14458 |
amit.gupta |
858 |
#print todict([1,2,"3"])
|
| 14402 |
amit.gupta |
859 |
store = getStore(3)
|
| 16946 |
amit.gupta |
860 |
#store.scrapeStoreOrders()
|
| 17387 |
amit.gupta |
861 |
#https://m.snapdeal.com/purchaseMobileComplete?code=3fbc8a02a1c4d3c4e906f46886de0464&order=5808451506
|
|
|
862 |
#https://m.snapdeal.com/purchaseMobileComplete?code=9f4dfa49ff08a16d04c5e4bf519506fc&order=9611672826
|
|
|
863 |
|
|
|
864 |
orders = session.query(OrdersRaw).filter_by(store_id=3).filter_by(status='ORDER_NOT_CREATED').all()
|
|
|
865 |
for o in orders:
|
|
|
866 |
result = store.parseOrderRawHtml(o.id, o.sub_tag, o.user_id, o.rawhtml, o.order_url)['result']
|
|
|
867 |
o.status = result
|
|
|
868 |
session.commit()
|
|
|
869 |
#store.parseOrderRawHtml(332221, "3232311", 2, readSSh("/home/amit/snapdeal.html"), "https://m.snapdeal.com/purchaseMobileComplete?code=3fbc8a02a1c4d3c4e906f46886de0464&order=5808451506")
|
|
|
870 |
#store.scrapeStoreOrders()
|
| 13662 |
amit.gupta |
871 |
#store._isSubOrderActive(8, "5970688907")
|
| 17237 |
amit.gupta |
872 |
#store.scrapeAffiliate(datetime(2015,4,1))
|
| 14758 |
amit.gupta |
873 |
#store.scrapeStoreOrders()
|
| 16997 |
amit.gupta |
874 |
#store.parseInfo()
|
| 13569 |
amit.gupta |
875 |
|
|
|
876 |
|
| 14459 |
amit.gupta |
877 |
|
| 13576 |
amit.gupta |
878 |
def todict(obj, classkey=None):
|
|
|
879 |
if isinstance(obj, dict):
|
|
|
880 |
data = {}
|
|
|
881 |
for (k, v) in obj.items():
|
|
|
882 |
data[k] = todict(v, classkey)
|
|
|
883 |
return data
|
|
|
884 |
elif hasattr(obj, "_ast"):
|
|
|
885 |
return todict(obj._ast())
|
|
|
886 |
elif hasattr(obj, "__iter__"):
|
|
|
887 |
return [todict(v, classkey) for v in obj]
|
|
|
888 |
elif hasattr(obj, "__dict__"):
|
|
|
889 |
data = dict([(key, todict(value, classkey))
|
|
|
890 |
for key, value in obj.__dict__.iteritems()
|
|
|
891 |
if not callable(value) and not key.startswith('_')])
|
|
|
892 |
if classkey is not None and hasattr(obj, "__class__"):
|
|
|
893 |
data[classkey] = obj.__class__.__name__
|
|
|
894 |
return data
|
|
|
895 |
else:
|
|
|
896 |
return obj
|
| 14239 |
amit.gupta |
897 |
|
|
|
898 |
if __name__ == '__main__':
|
|
|
899 |
main()
|