Subversion Repositories SmartDukaan

Rev

Rev 10401 | Rev 10414 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
10401 amar.kumar 1
from elixir import *
2
from shop2020.config.client.ConfigClient import ConfigClient
3
from shop2020.model.v1.catalog.impl import DataService
4
from shop2020.model.v1.catalog.impl.DataService import SnapdealItem, MarketplaceItems, Item
5
from shop2020.thriftpy.model.v1.order.ttypes import OrderSource
6
import mechanize
7
import sys
8
import cookielib
9
from time import sleep
10
import json
11
import smtplib
12
from datetime import datetime
13
from shop2020.utils import EmailAttachmentSender
14
from shop2020.utils.EmailAttachmentSender import get_attachment_part
15
from email.mime.text import MIMEText
16
import email
17
from email.mime.multipart import MIMEMultipart
18
import email.encoders
19
 
20
config_client = ConfigClient()
21
host = config_client.get_property('staging_hostname')
22
DataService.initialize(db_hostname=host)
23
 
24
class __SnapdealInfo:
25
    def __init__(self, sellingPrice, weight, transferPrice, commission, commissionPercentage, courierCost, sellingPriceSnapdeal, transferPriceSnapdeal, fixedMargin, fixedMarginPercentage, collectionCharges, logisticCostSnapdeal, weightSnapdeal, supc, itemId):
26
 
27
        self.sellingPrice = sellingPrice
28
        self.weight = weight
29
        self.transferPrice = transferPrice
30
        self.commission = commission
31
        self.commissionPercentage = commissionPercentage
32
        self.courierCost = courierCost
33
        self.sellingPriceSnapdeal = sellingPriceSnapdeal
34
        self.transferPriceSnapdeal = transferPriceSnapdeal
35
        self.fixedMargin = fixedMargin
36
        self.fixedMarginPercentage = fixedMarginPercentage
37
        self.collectionCharges = collectionCharges
38
        self.logisticCostSnapdeal = logisticCostSnapdeal
39
        self.weightSnapdeal = weightSnapdeal
40
        self.supc = supc
41
        self.itemId = itemId
42
 
43
def getBrowserObject():
44
    br = mechanize.Browser(factory=mechanize.RobustFactory())
45
    cj = cookielib.LWPCookieJar()
46
    br.set_cookiejar(cj)
47
    br.set_handle_equiv(True)
48
    br.set_handle_redirect(True)
49
    br.set_handle_referer(True)
50
    br.set_handle_robots(False)
51
    br.set_debug_http(False)
52
    br.set_debug_redirects(False)
53
    br.set_debug_responses(False)
54
 
55
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
56
 
57
    br.addheaders = [('User-agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'),
58
                     ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
59
                     ('Accept-Encoding', 'gzip,deflate,sdch'),                  
60
                     ('Accept-Language', 'en-US,en;q=0.8'),                     
61
                     ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3')]
62
    return br
63
 
64
def login(url):
65
    br = getBrowserObject()
66
    br.open(url)
67
    response = br.open(url)
68
    br.select_form(nr=0)
69
    br.form['username'] = "saholic-snapdeal@saholic.com"
70
    br.form['password'] = "bc452ce4"
71
    print "Trying to login"
72
    response = br.submit()
73
    return br
74
 
75
def populateStuff(br):
76
    exceptionList = []
77
    fetchedItems = []
78
    items = session.query(SnapdealItem,MarketplaceItems).join((MarketplaceItems,SnapdealItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).all()
79
    for item in items:
80
        snapdealItem = item[0]
81
        marketplaceItem = item[1]
10404 kshitij.so 82
        try:
83
            print "Inside try for fetch data"
84
            snapdealInfo = fetchData(br,snapdealItem.supc)
85
        except Exception as e:
86
            exceptionList.append(item)
87
            print "Unable to fetch details ",e
88
            continue
89
        snapdealInfo.sellingPrice = snapdealItem.sellingPrice
90
        snapdealInfo.courierCost = snapdealItem.courierCost
91
        snapdealInfo.transferPrice = snapdealItem.transferPrice
92
        snapdealInfo.commissionPercentage = marketplaceItem.commission
93
        snapdealInfo.commission = snapdealItem.commission
94
        snapdealInfo.itemId = snapdealItem.item_id
95
        fetchedItems.append(snapdealInfo)
10401 amar.kumar 96
    return exceptionList, fetchedItems
97
 
98
def fetchData(br,supc):
99
    url="http://seller.snapdeal.com/pricing/search?searchType=SUPC&searchValue=%s&gridType=normal&_search=false&nd=1396007375971&rows=30&page=1&sidx=&sord=asc"%(supc)
100
    sleep(1)
101
    response = br.open(url)
102
    dataform = str(response.read()).strip("'<>() ").replace('\'', '\"')
103
    struct = json.loads(dataform)
104
    sdObj = struct['rows'][0]
105
    print sdObj
106
    snapdealInfo = __SnapdealInfo(None,None,None,None,None,None,sdObj['sellingPrice'],sdObj['netSellerPayable'],sdObj['fixedMarginAmount'],sdObj['fixedMarginPercent'],sdObj['collectionCharges'],sdObj['logisticCost'],sdObj['deadWeight'],supc,None)
107
    return snapdealInfo
108
 
109
def filterData(fetchedItems):
110
    for data in fetchedItems:
111
        if ( data.transferPrice - data.transferPriceSnapdeal >= -3 ) and (data.transferPrice - data.transferPriceSnapdeal <= 3):
112
            print "Removing itemId ",data.itemId
113
            fetchedItems.remove(data)
114
    return fetchedItems
115
 
116
def sendMail(filteredData,exceptionList):
117
    xstr = lambda s: s or ""
118
    message="""<html>
119
            <body>
120
            <h3>Low TP On Snapdeal</h3>
121
            <table border="1" style="width:100%;">
122
            <thead>
123
            <tr><th>Item Id</th>
124
            <th>Product Name</th>
125
            <th>Our System Selling Price</th>
126
            <th>Selling Price Snapdeal</th>
127
            <th>Our System Transfer Price</th>
128
            <th>Snapdeal Transfer Price</th>
129
            <th>Our System Commission</th>
130
            <th>Snapdeal Commission</th>
131
            <th>Our System Commission %</th>
132
            <th>Snapdeal Commission %</th>
133
            <th>Our System Weight</th>
134
            <th>Snapdeal Weight</th>
135
            <th>Our Courier Cost</th>
136
            <th>Snapdeal Courier Charges</th>
137
            </tr></thead>
138
            <tbody>"""
139
    for data in filteredData:
140
        if data.transferPriceSnapdeal < data.transferPrice:
141
            it = Item.query.filter_by(id=data.itemId).one()
142
            message+="""<tr>
143
            <td style="text-align:center">"""+str(data.itemId)+"""</td>
144
            <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
145
            <td style="text-align:center">"""+str(data.sellingPrice)+"""</td>
146
            <td style="text-align:center">"""+str(data.sellingPriceSnapdeal)+"""</td>
147
            <td style="text-align:center">"""+str(data.transferPrice)+"""</td>
148
            <td style="text-align:center">"""+str(data.transferPriceSnapdeal)+"""</td>
149
            <td style="text-align:center">"""+str(data.commission*1.1236)+"""</td>
150
            <td style="text-align:center">"""+str(round(float(data.fixedMargin)+float(data.collectionCharges),2))+"""</td>
151
            <td style="text-align:center">"""+str(data.commissionPercentage)+"%"+"""</td>
152
            <td style="text-align:center">"""+str(round(float(data.fixedMarginPercentage)/1.1236,2))+"%"+"""</td>
153
            <td style="text-align:center">"""+str(it.weight*100)+" gms"+"""</td>
154
            <td style="text-align:center">"""+str(data.weightSnapdeal)+" gms"+"""</td>
155
            <td style="text-align:center">"""+str(data.courierCost*1.1236)+"""</td>
156
            <td style="text-align:center">"""+str(data.logisticCostSnapdeal)+" gms"+"""</td>
157
            </tr>"""
158
    message+="""</tbody></table>"""
159
    message+="""
160
            <h3>High TP On Snapdeal</h3>
161
            <table border="1" style="width:100%;">
162
            <thead>
163
            <tr><th>Item Id</th>
164
            <th>Product Name</th>
165
            <th>Our System Selling Price</th>
166
            <th>Selling Price Snapdeal</th>
167
            <th>Our System Transfer Price</th>
168
            <th>Snapdeal Transfer Price</th>
169
            <th>Our System Commission</th>
170
            <th>Snapdeal Commission</th>
171
            <th>Our System Commission %</th>
172
            <th>Snapdeal Commission %</th>
173
            <th>Our System Weight</th>
174
            <th>Snapdeal Weight</th>
175
            <th>Our Courier Cost</th>
176
            <th>Snapdeal Courier Charges</th>
177
            </tr></thead>
178
            <tbody>"""
179
    for data in filteredData:
180
        if data.transferPriceSnapdeal >= data.transferPrice:
181
            it = Item.query.filter_by(id=data.itemId).one()
182
            message+="""<tr>
183
            <td style="text-align:center">"""+str(data.itemId)+"""</td>
184
            <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
185
            <td style="text-align:center">"""+str(data.sellingPrice)+"""</td>
186
            <td style="text-align:center">"""+str(data.sellingPriceSnapdeal)+"""</td>
187
            <td style="text-align:center">"""+str(data.transferPrice)+"""</td>
188
            <td style="text-align:center">"""+str(data.transferPriceSnapdeal)+"""</td>
189
            <td style="text-align:center">"""+str(data.commission*1.1236)+"""</td>
190
            <td style="text-align:center">"""+str(round(float(data.fixedMargin)+float(data.collectionCharges),2))+"""</td>
191
            <td style="text-align:center">"""+str(data.commissionPercentage)+"%"+"""</td>
192
            <td style="text-align:center">"""+str(round(float(data.fixedMarginPercentage)/1.1236,2))+"%"+"""</td>
193
            <td style="text-align:center">"""+str(it.weight*100)+" gms"+"""</td>
194
            <td style="text-align:center">"""+str(data.weightSnapdeal)+" gms"+"""</td>
195
            <td style="text-align:center">"""+str(data.courierCost*1.1236)+"""</td>
196
            <td style="text-align:center">"""+str(data.logisticCostSnapdeal)+"""</td>
197
            </tr>"""
198
    message+="""</tbody></table>"""
199
    message+="""
200
            <h3>Unable To Fetch Items</h3>
201
            <table border="1" style="width:100%;">
202
            <thead>
203
            <tr><th>Item Id</th>
204
            <th>Product Name</th>
205
            <th>Our System Selling Price</th>
206
            <th>Our System Transfer Price</th>
207
            <th>Our System Commission</th>
208
            <th>Our System Commission %</th>
209
            <th>Our System Weight</th>
210
            <th>Our Courier Cost</th>
211
            </tr></thead>
212
            <tbody>"""
213
    for data in exceptionList:
214
        snapdealItem = data[0]
215
        marketplaceItem = data[1]
216
        it = Item.query.filter_by(id=data.itemId).one()
217
        message+="""<tr>
218
            <td style="text-align:center">"""+str(data.itemId)+"""</td>
219
            <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
220
            <td style="text-align:center">"""+str(snapdealItem.sellingPrice)+"""</td>
221
            <td style="text-align:center">"""+str(snapdealItem.transferPrice)+"""</td>
222
            <td style="text-align:center">"""+str(snapdealItem.commission*1.1236)+"""</td>
223
            <td style="text-align:center">"""+str(marketplaceItem.commissionPercentage)+"%"+"""</td>
224
            <td style="text-align:center">"""+str(it.weight*100)+" gms"+"""</td>
225
            <td style="text-align:center">"""+str(snapdealItem.courierCost*1.1236)+"""</td>
226
            </tr>"""
227
    message+="""</tbody></table></body></html>"""
228
    print message
229
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
230
    mailServer.ehlo()
231
    mailServer.starttls()
232
    mailServer.ehlo()
233
 
234
    recipients = ['kshitij.sood@saholic.com']
235
    #recipients = ['rajneesh.arora@saholic.com','rajveer.singh@saholic.com','vikram.raghav@saholic.com','kshitij.sood@saholic.com','khushal.bhatia@saholic.com','chaitnaya.vats@saholic.com','chandan.kumar@saholic.com','manoj.kumar@saholic.com','yukti.jain@saholic.com','ankush.dhingra@saholic.com','manoj.pal@saholic.com']
236
    msg = MIMEMultipart()
237
    msg['Subject'] = "Snapdeal TP Reconciliation" + ' - ' + str(datetime.now())
238
    msg['From'] = ""
239
    msg['To'] = ",".join(recipients)
240
    msg.preamble = "Snapdeal TP Reconciliation" + ' - ' + str(datetime.now())
241
    html_msg = MIMEText(message, 'html')
242
    msg.attach(html_msg)
243
    try:
244
        mailServer.login("build@shop2020.in", "cafe@nes")
245
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
246
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
247
    except Exception as e:
248
        print e
249
        print "Unable to send Snapdeal TP Reconciliation mail.Lets try with local SMTP."
250
        smtpServer = smtplib.SMTP('localhost')
251
        smtpServer.set_debuglevel(1)
252
        sender = 'support@shop2020.in'
253
    try:
254
        smtpServer.sendmail(sender, recipients, msg.as_string())
255
        print "Successfully sent email"
256
    except:
257
        print "Error: unable to send email."
258
 
259
def main():
260
    print "Opening snapdeal seller login page"
261
    br = login("http://selleraccounts.snapdeal.com/")
262
    exceptionList, fetchedItems = populateStuff(br)
263
    filteredData = filterData(fetchedItems)
264
    sendMail(filteredData,exceptionList)
265
 
266
 
267
if __name__ == "__main__":
268
    main()
269
 
270