Subversion Repositories SmartDukaan

Rev

Rev 15451 | Rev 15453 | 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
11098 kshitij.so 4
from shop2020.model.v1.catalog.impl.DataService import SnapdealItem, MarketplaceItems, Item, Category, \
5
MarketPlaceUpdateHistory
10401 amar.kumar 6
from shop2020.thriftpy.model.v1.order.ttypes import OrderSource
7
import mechanize
8
import sys
9
import cookielib
10
from time import sleep
11
import json
12
import smtplib
10414 kshitij.so 13
import xlwt
10401 amar.kumar 14
from datetime import datetime
15
from shop2020.utils import EmailAttachmentSender
16
from shop2020.utils.EmailAttachmentSender import get_attachment_part
17
from email.mime.text import MIMEText
18
import email
19
from email.mime.multipart import MIMEMultipart
20
import email.encoders
11098 kshitij.so 21
import copy
14893 kshitij.so 22
import traceback
10401 amar.kumar 23
 
24
config_client = ConfigClient()
25
host = config_client.get_property('staging_hostname')
26
DataService.initialize(db_hostname=host)
27
 
11098 kshitij.so 28
courierCostToSync = []
29
oldPricing = []
30
 
10401 amar.kumar 31
class __SnapdealInfo:
10414 kshitij.so 32
    def __init__(self, sellingPrice, weight, transferPrice, commission, commissionPercentage, courierCost, sellingPriceSnapdeal, transferPriceSnapdeal, fixedMargin, \
33
                 fixedMarginPercentage, collectionCharges, logisticCostSnapdeal, weightSnapdeal, supc, itemId, parentCategory, productGroup ,brand, modelName, modelNumber, \
11098 kshitij.so 34
                 color,reason,woodenPackagingCost):
10401 amar.kumar 35
 
36
        self.sellingPrice = sellingPrice
37
        self.weight = weight
38
        self.transferPrice = transferPrice
39
        self.commission = commission
40
        self.commissionPercentage = commissionPercentage
41
        self.courierCost = courierCost
42
        self.sellingPriceSnapdeal = sellingPriceSnapdeal
43
        self.transferPriceSnapdeal = transferPriceSnapdeal
44
        self.fixedMargin = fixedMargin
45
        self.fixedMarginPercentage = fixedMarginPercentage
46
        self.collectionCharges = collectionCharges
47
        self.logisticCostSnapdeal = logisticCostSnapdeal
48
        self.weightSnapdeal = weightSnapdeal
49
        self.supc = supc
50
        self.itemId = itemId
10414 kshitij.so 51
        self.parentCategory = parentCategory
52
        self.productGroup = productGroup
53
        self.brand = brand
54
        self.modelName = modelName
55
        self.modelNumber = modelNumber
10428 kshitij.so 56
        self.color = color
57
        self.reason = reason 
11098 kshitij.so 58
        self.woodenPackagingCost = woodenPackagingCost
10414 kshitij.so 59
 
10401 amar.kumar 60
 
61
def getBrowserObject():
62
    br = mechanize.Browser(factory=mechanize.RobustFactory())
63
    cj = cookielib.LWPCookieJar()
64
    br.set_cookiejar(cj)
65
    br.set_handle_equiv(True)
66
    br.set_handle_redirect(True)
67
    br.set_handle_referer(True)
68
    br.set_handle_robots(False)
69
    br.set_debug_http(False)
70
    br.set_debug_redirects(False)
71
    br.set_debug_responses(False)
72
 
73
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
74
 
75
    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'),
76
                     ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
77
                     ('Accept-Encoding', 'gzip,deflate,sdch'),                  
78
                     ('Accept-Language', 'en-US,en;q=0.8'),                     
79
                     ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3')]
80
    return br
81
 
82
def login(url):
83
    br = getBrowserObject()
84
    br.open(url)
85
    response = br.open(url)
15450 kshitij.so 86
    ungzipResponse(response, br)
87
    br.select_form(name="pgLogin:navbar")
88
    br.form['pgLogin:navbar:txtUserName'] = "saholic-snapdeal@saholic.com"
89
    br.form['pgLogin:navbar:txtPassword'] = "snapsaholic15"
10401 amar.kumar 90
    print "Trying to login"
91
    response = br.submit()
92
    return br
93
 
15450 kshitij.so 94
def ungzipResponse(r,b):
95
    headers = r.info()
96
    if headers['Content-Encoding']=='gzip':
97
        import gzip
98
        print "********************"
99
        print "Deflating gzip response"
100
        print "********************"
101
        gz = gzip.GzipFile(fileobj=r, mode='rb')
102
        html = gz.read()
103
        gz.close()
104
        headers["Content-type"] = "text/html; charset=utf-8"
105
        r.set_data( html )
106
        b.set_response(r)
107
 
108
 
10401 amar.kumar 109
def populateStuff(br):
110
    exceptionList = []
111
    fetchedItems = []
10414 kshitij.so 112
    items = session.query(SnapdealItem,MarketplaceItems,Item).join((MarketplaceItems,SnapdealItem.item_id==MarketplaceItems.itemId)).join((Item,SnapdealItem.item_id==Item.id)).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).all()
11098 kshitij.so 113
    #items = session.query(SnapdealItem,MarketplaceItems,Item).join((MarketplaceItems,SnapdealItem.item_id==MarketplaceItems.itemId)).join((Item,SnapdealItem.item_id==Item.id)).filter(SnapdealItem.item_id==12613).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).all()
10401 amar.kumar 114
    for item in items:
115
        snapdealItem = item[0]
116
        marketplaceItem = item[1]
10414 kshitij.so 117
        ds_item = item[2] 
118
        category = Category.query.filter_by(id=ds_item.category).one()
119
        parent_category = Category.query.filter_by(id=category.parent_category_id).first()
10404 kshitij.so 120
        try:
121
            snapdealInfo = fetchData(br,snapdealItem.supc)
122
        except Exception as e:
123
            exceptionList.append(item)
14893 kshitij.so 124
            traceback.print_exc()
10404 kshitij.so 125
            print "Unable to fetch details ",e
126
            continue
127
        snapdealInfo.sellingPrice = snapdealItem.sellingPrice
11102 kshitij.so 128
        snapdealInfo.courierCost = snapdealItem.courierCostMarketplace
10404 kshitij.so 129
        snapdealInfo.transferPrice = snapdealItem.transferPrice
130
        snapdealInfo.commissionPercentage = marketplaceItem.commission
131
        snapdealInfo.commission = snapdealItem.commission
132
        snapdealInfo.itemId = snapdealItem.item_id
10414 kshitij.so 133
        snapdealInfo.parentCategory = parent_category.display_name
134
        snapdealInfo.productGroup = ds_item.product_group
135
        snapdealInfo.brand = ds_item.brand
136
        snapdealInfo.modelName = ds_item.model_name
137
        snapdealInfo.modelNumber = ds_item.model_number
138
        snapdealInfo.color = ds_item.color
139
        snapdealInfo.weight = ds_item.weight
10404 kshitij.so 140
        fetchedItems.append(snapdealInfo)
10401 amar.kumar 141
    return exceptionList, fetchedItems
142
 
143
def fetchData(br,supc):
11098 kshitij.so 144
    print "Fetching data for ",supc
15451 kshitij.so 145
    url="http://seller.snapdeal.com/pricing/search?_search=false&gridType=normal&page=1&rows=30&searchType=SUPC&searchValue=%s&sidx=priceUpdateTime&sord=desc"%(supc)
10401 amar.kumar 146
    response = br.open(url)
15452 kshitij.so 147
    print response.read()
12161 kshitij.so 148
    #dataform = str(response.read()).strip("'<>() ").replace('\'', '\"')
149
    struct = json.loads(response.read())
10401 amar.kumar 150
    sdObj = struct['rows'][0]
151
    print sdObj
12817 kshitij.so 152
    if type(sdObj['catalogLive']) is None or not (sdObj['catalogLive']):
11772 kshitij.so 153
        raise
12819 kshitij.so 154
    woodenPackagingCost = 0.0
14892 kshitij.so 155
    woodenPackagingCost = sdObj['extraFulfillmentFeesAfterWaiver'] 
10414 kshitij.so 156
    snapdealInfo = __SnapdealInfo(None,None,None,None,None,None,sdObj['sellingPrice'],sdObj['netSellerPayable'],sdObj['fixedMarginAmount'],sdObj['fixedMarginPercent'],sdObj['collectionCharges'],sdObj['logisticCost'],sdObj['deadWeight'],supc,None, \
12819 kshitij.so 157
                    None, None, None, None, None, None, None,woodenPackagingCost)
10401 amar.kumar 158
    return snapdealInfo
159
 
160
def filterData(fetchedItems):
10414 kshitij.so 161
    filterList = []
10401 amar.kumar 162
    for data in fetchedItems:
163
        if ( data.transferPrice - data.transferPriceSnapdeal >= -3 ) and (data.transferPrice - data.transferPriceSnapdeal <= 3):
11098 kshitij.so 164
            print "continue for",data.itemId
10414 kshitij.so 165
            continue
166
        filterList.append(data)
167
    return filterList
10401 amar.kumar 168
 
169
def sendMail(filteredData,exceptionList):
170
    xstr = lambda s: s or ""
171
    message="""<html>
172
            <body>
173
            <h3>Low TP On Snapdeal</h3>
174
            <table border="1" style="width:100%;">
175
            <thead>
176
            <tr><th>Item Id</th>
177
            <th>Product Name</th>
178
            <th>Our System Selling Price</th>
179
            <th>Selling Price Snapdeal</th>
180
            <th>Our System Transfer Price</th>
181
            <th>Snapdeal Transfer Price</th>
182
            <th>Our System Commission</th>
183
            <th>Snapdeal Commission</th>
184
            <th>Our System Commission %</th>
185
            <th>Snapdeal Commission %</th>
186
            <th>Our System Weight</th>
187
            <th>Snapdeal Weight</th>
188
            <th>Our Courier Cost</th>
189
            <th>Snapdeal Courier Charges</th>
10428 kshitij.so 190
            <th>Reason</th>
10401 amar.kumar 191
            </tr></thead>
192
            <tbody>"""
193
    for data in filteredData:
194
        if data.transferPriceSnapdeal < data.transferPrice:
195
            message+="""<tr>
196
            <td style="text-align:center">"""+str(data.itemId)+"""</td>
10414 kshitij.so 197
            <td style="text-align:center">"""+xstr(data.brand)+" "+xstr(data.modelName)+" "+xstr(data.modelNumber)+" "+xstr(data.color)+"""</td>
10401 amar.kumar 198
            <td style="text-align:center">"""+str(data.sellingPrice)+"""</td>
199
            <td style="text-align:center">"""+str(data.sellingPriceSnapdeal)+"""</td>
200
            <td style="text-align:center">"""+str(data.transferPrice)+"""</td>
201
            <td style="text-align:center">"""+str(data.transferPriceSnapdeal)+"""</td>
15449 kshitij.so 202
            <td style="text-align:center">"""+str(round(data.commission*1.14,2))+"""</td>
10401 amar.kumar 203
            <td style="text-align:center">"""+str(round(float(data.fixedMargin)+float(data.collectionCharges),2))+"""</td>
204
            <td style="text-align:center">"""+str(data.commissionPercentage)+"%"+"""</td>
15449 kshitij.so 205
            <td style="text-align:center">"""+str(round(float(data.fixedMarginPercentage)/1.14,2))+"%"+"""</td>
10414 kshitij.so 206
            <td style="text-align:center">"""+str(data.weight*1000)+" gms"+"""</td>
10401 amar.kumar 207
            <td style="text-align:center">"""+str(data.weightSnapdeal)+" gms"+"""</td>
15449 kshitij.so 208
            <td style="text-align:center">"""+str(round(data.courierCost*1.14,2))+"""</td>
11098 kshitij.so 209
            <td style="text-align:center">"""+str(round(data.logisticCostSnapdeal,2)+round(data.woodenPackagingCost,2))+"""</td>
10428 kshitij.so 210
            <td style="text-align:center">"""+getReason(data)+"""</td>
10401 amar.kumar 211
            </tr>"""
212
    message+="""</tbody></table>"""
213
    message+="""
214
            <h3>High TP On Snapdeal</h3>
215
            <table border="1" style="width:100%;">
216
            <thead>
217
            <tr><th>Item Id</th>
218
            <th>Product Name</th>
219
            <th>Our System Selling Price</th>
220
            <th>Selling Price Snapdeal</th>
221
            <th>Our System Transfer Price</th>
222
            <th>Snapdeal Transfer Price</th>
223
            <th>Our System Commission</th>
224
            <th>Snapdeal Commission</th>
225
            <th>Our System Commission %</th>
226
            <th>Snapdeal Commission %</th>
227
            <th>Our System Weight</th>
228
            <th>Snapdeal Weight</th>
229
            <th>Our Courier Cost</th>
230
            <th>Snapdeal Courier Charges</th>
10428 kshitij.so 231
            <th>Reason</th>
10401 amar.kumar 232
            </tr></thead>
233
            <tbody>"""
234
    for data in filteredData:
235
        if data.transferPriceSnapdeal >= data.transferPrice:
236
            message+="""<tr>
237
            <td style="text-align:center">"""+str(data.itemId)+"""</td>
10414 kshitij.so 238
            <td style="text-align:center">"""+xstr(data.brand)+" "+xstr(data.modelName)+" "+xstr(data.modelNumber)+" "+xstr(data.color)+"""</td>
10401 amar.kumar 239
            <td style="text-align:center">"""+str(data.sellingPrice)+"""</td>
240
            <td style="text-align:center">"""+str(data.sellingPriceSnapdeal)+"""</td>
241
            <td style="text-align:center">"""+str(data.transferPrice)+"""</td>
242
            <td style="text-align:center">"""+str(data.transferPriceSnapdeal)+"""</td>
15449 kshitij.so 243
            <td style="text-align:center">"""+str(round(data.commission*1.14,2))+"""</td>
10401 amar.kumar 244
            <td style="text-align:center">"""+str(round(float(data.fixedMargin)+float(data.collectionCharges),2))+"""</td>
245
            <td style="text-align:center">"""+str(data.commissionPercentage)+"%"+"""</td>
15449 kshitij.so 246
            <td style="text-align:center">"""+str(round(float(data.fixedMarginPercentage)/1.14,2))+"%"+"""</td>
10414 kshitij.so 247
            <td style="text-align:center">"""+str(data.weight*1000)+" gms"+"""</td>
10401 amar.kumar 248
            <td style="text-align:center">"""+str(data.weightSnapdeal)+" gms"+"""</td>
15449 kshitij.so 249
            <td style="text-align:center">"""+str(round(data.courierCost*1.14,2))+"""</td>
11098 kshitij.so 250
            <td style="text-align:center">"""+str(round(data.logisticCostSnapdeal,2)+round(data.woodenPackagingCost,2))+"""</td>
10428 kshitij.so 251
            <td style="text-align:center">"""+getReason(data)+"""</td>
10401 amar.kumar 252
            </tr>"""
253
    message+="""</tbody></table>"""
254
    message+="""
11772 kshitij.so 255
            <h3 style="color:red;font-weight:bold">Please Check</h3>
256
            <h3>Items not live on Snapdeal</h3>
10401 amar.kumar 257
            <table border="1" style="width:100%;">
258
            <thead>
259
            <tr><th>Item Id</th>
260
            <th>Product Name</th>
261
            <th>Our System Selling Price</th>
262
            <th>Our System Transfer Price</th>
263
            <th>Our System Commission</th>
264
            <th>Our System Commission %</th>
265
            <th>Our System Weight</th>
266
            <th>Our Courier Cost</th>
267
            </tr></thead>
268
            <tbody>"""
269
    for data in exceptionList:
270
        snapdealItem = data[0]
271
        marketplaceItem = data[1]
10414 kshitij.so 272
        ds_item = data[2]
10401 amar.kumar 273
        message+="""<tr>
10414 kshitij.so 274
            <td style="text-align:center">"""+str(ds_item.id)+"""</td>
275
            <td style="text-align:center">"""+xstr(ds_item.brand)+" "+xstr(ds_item.model_name)+" "+xstr(ds_item.model_number)+" "+xstr(ds_item.color)+"""</td>
10401 amar.kumar 276
            <td style="text-align:center">"""+str(snapdealItem.sellingPrice)+"""</td>
277
            <td style="text-align:center">"""+str(snapdealItem.transferPrice)+"""</td>
15449 kshitij.so 278
            <td style="text-align:center">"""+str(round(snapdealItem.commission*1.14,2))+"""</td>
10414 kshitij.so 279
            <td style="text-align:center">"""+str(marketplaceItem.commission)+"%"+"""</td>
280
            <td style="text-align:center">"""+str(ds_item.weight*1000)+" gms"+"""</td>
15449 kshitij.so 281
            <td style="text-align:center">"""+str(round(snapdealItem.courierCost*1.14,2))+"""</td>
10401 amar.kumar 282
            </tr>"""
283
    message+="""</tbody></table></body></html>"""
284
    print message
285
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
286
    mailServer.ehlo()
287
    mailServer.starttls()
288
    mailServer.ehlo()
289
 
10434 kshitij.so 290
    #recipients = ['kshitij.sood@saholic.com']
14893 kshitij.so 291
    recipients = ['rajneesh.arora@saholic.com','anikendra.das@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','yatin.singh@saholic.com','sandeep.sachdeva@saholic.com']
10401 amar.kumar 292
    msg = MIMEMultipart()
293
    msg['Subject'] = "Snapdeal TP Reconciliation" + ' - ' + str(datetime.now())
294
    msg['From'] = ""
295
    msg['To'] = ",".join(recipients)
296
    msg.preamble = "Snapdeal TP Reconciliation" + ' - ' + str(datetime.now())
297
    html_msg = MIMEText(message, 'html')
298
    msg.attach(html_msg)
299
    try:
300
        mailServer.login("build@shop2020.in", "cafe@nes")
301
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
302
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
303
    except Exception as e:
304
        print e
305
        print "Unable to send Snapdeal TP Reconciliation mail.Lets try with local SMTP."
306
        smtpServer = smtplib.SMTP('localhost')
307
        smtpServer.set_debuglevel(1)
308
        sender = 'support@shop2020.in'
10420 kshitij.so 309
        try:
310
            smtpServer.sendmail(sender, recipients, msg.as_string())
311
            print "Successfully sent email"
312
        except:
313
            print "Error: unable to send email."
10401 amar.kumar 314
 
10414 kshitij.so 315
def write_report(filteredData,exceptionList):
12953 kshitij.so 316
    wbk = xlwt.Workbook(encoding="UTF-8")
10414 kshitij.so 317
    sheet = wbk.add_sheet('Low TP SD')
318
    xstr = lambda s: s or ""
319
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
320
 
321
    excel_integer_format = '0'
322
    integer_style = xlwt.XFStyle()
323
    integer_style.num_format_str = excel_integer_format
324
 
325
    sheet.write(0, 0, "Item ID", heading_xf)
326
    sheet.write(0, 1, "Category", heading_xf)
327
    sheet.write(0, 2, "Product Group.", heading_xf)
328
    sheet.write(0, 3, "SUPC", heading_xf)
329
    sheet.write(0, 4, "Brand", heading_xf)
330
    sheet.write(0, 5, "Product Name", heading_xf)
331
    sheet.write(0, 6, "Our System SP", heading_xf)
332
    sheet.write(0, 7, "Snapdeal SP", heading_xf)
333
    sheet.write(0, 8, "Our TP", heading_xf)
334
    sheet.write(0, 9, "Snapdeal TP", heading_xf)
335
    sheet.write(0, 10, "Our System Commission", heading_xf)
336
    sheet.write(0, 11, "Snapdeal Commission", heading_xf)
337
    sheet.write(0, 12, "Our System Commission %", heading_xf)
338
    sheet.write(0, 13, "Snapdeal Commission %", heading_xf)
339
    sheet.write(0, 14, "Our System Weight (gms)", heading_xf)
340
    sheet.write(0, 15, "Snapdeal Weight", heading_xf)
341
    sheet.write(0, 16, "Our Courier Cost", heading_xf)
342
    sheet.write(0, 17, "Snapdeal Courier Cost", heading_xf)
10428 kshitij.so 343
    sheet.write(0, 18, "Reason", heading_xf)
10414 kshitij.so 344
 
345
    sheet_iterator=1
346
    for data in filteredData:
347
        if data.transferPriceSnapdeal < data.transferPrice:
348
            sheet.write(sheet_iterator, 0, data.itemId)
349
            sheet.write(sheet_iterator, 1, data.parentCategory)
10420 kshitij.so 350
            sheet.write(sheet_iterator, 2, data.productGroup)
351
            sheet.write(sheet_iterator, 3, data.supc)
10414 kshitij.so 352
            sheet.write(sheet_iterator, 4, data.brand)
353
            sheet.write(sheet_iterator, 5, xstr(data.brand)+" "+xstr(data.modelName)+" "+xstr(data.modelNumber)+" "+xstr(data.color))
354
            sheet.write(sheet_iterator, 6, data.sellingPrice)
355
            sheet.write(sheet_iterator, 7, data.sellingPriceSnapdeal)
356
            sheet.write(sheet_iterator, 8, data.transferPrice)
357
            sheet.write(sheet_iterator, 9, data.transferPriceSnapdeal)
15449 kshitij.so 358
            sheet.write(sheet_iterator, 10, round(data.commission*1.14,2))
10414 kshitij.so 359
            sheet.write(sheet_iterator, 11, round(float(data.fixedMargin)+float(data.collectionCharges),2))
360
            sheet.write(sheet_iterator, 12, data.commissionPercentage)
15449 kshitij.so 361
            sheet.write(sheet_iterator, 13, round(float(data.fixedMarginPercentage)/1.14,2))
10414 kshitij.so 362
            sheet.write(sheet_iterator, 14, data.weight*1000)
363
            sheet.write(sheet_iterator, 15, data.weightSnapdeal)
15449 kshitij.so 364
            sheet.write(sheet_iterator, 16, round(data.courierCost*1.14,2))
11098 kshitij.so 365
            sheet.write(sheet_iterator, 17, round(data.logisticCostSnapdeal,2)+round(data.woodenPackagingCost,2))
366
            sheet.write(sheet_iterator, 18, getReasonSheet(data))
10414 kshitij.so 367
            sheet_iterator+=1
368
 
369
    sheet = wbk.add_sheet('High TP SD')
370
 
371
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
372
 
373
    excel_integer_format = '0'
374
    integer_style = xlwt.XFStyle()
375
    integer_style.num_format_str = excel_integer_format
376
    xstr = lambda s: s or ""
377
 
378
    sheet.write(0, 0, "Item ID", heading_xf)
379
    sheet.write(0, 1, "Category", heading_xf)
380
    sheet.write(0, 2, "Product Group.", heading_xf)
381
    sheet.write(0, 3, "SUPC", heading_xf)
382
    sheet.write(0, 4, "Brand", heading_xf)
383
    sheet.write(0, 5, "Product Name", heading_xf)
384
    sheet.write(0, 6, "Our System SP", heading_xf)
385
    sheet.write(0, 7, "Snapdeal SP", heading_xf)
386
    sheet.write(0, 8, "Our TP", heading_xf)
387
    sheet.write(0, 9, "Snapdeal TP", heading_xf)
388
    sheet.write(0, 10, "Our System Commission", heading_xf)
389
    sheet.write(0, 11, "Snapdeal Commission", heading_xf)
390
    sheet.write(0, 12, "Our System Commission %", heading_xf)
391
    sheet.write(0, 13, "Snapdeal Commission %", heading_xf)
392
    sheet.write(0, 14, "Our System Weight (gms)", heading_xf)
393
    sheet.write(0, 15, "Snapdeal Weight", heading_xf)
394
    sheet.write(0, 16, "Our Courier Cost", heading_xf)
395
    sheet.write(0, 17, "Snapdeal Courier Cost", heading_xf)
10428 kshitij.so 396
    sheet.write(0, 18, "Reason", heading_xf)
10414 kshitij.so 397
 
398
    sheet_iterator=1
399
    for data in filteredData:
400
        if data.transferPriceSnapdeal > data.transferPrice:
401
            sheet.write(sheet_iterator, 0, data.itemId)
402
            sheet.write(sheet_iterator, 1, data.parentCategory)
10420 kshitij.so 403
            sheet.write(sheet_iterator, 2, data.productGroup)
404
            sheet.write(sheet_iterator, 3, data.supc)
10414 kshitij.so 405
            sheet.write(sheet_iterator, 4, data.brand)
406
            sheet.write(sheet_iterator, 5, xstr(data.brand)+" "+xstr(data.modelName)+" "+xstr(data.modelNumber)+" "+xstr(data.color))
407
            sheet.write(sheet_iterator, 6, data.sellingPrice)
408
            sheet.write(sheet_iterator, 7, data.sellingPriceSnapdeal)
409
            sheet.write(sheet_iterator, 8, data.transferPrice)
410
            sheet.write(sheet_iterator, 9, data.transferPriceSnapdeal)
15449 kshitij.so 411
            sheet.write(sheet_iterator, 10, round(data.commission*1.14,2))
10414 kshitij.so 412
            sheet.write(sheet_iterator, 11, round(float(data.fixedMargin)+float(data.collectionCharges),2))
413
            sheet.write(sheet_iterator, 12, data.commissionPercentage)
15449 kshitij.so 414
            sheet.write(sheet_iterator, 13, round(float(data.fixedMarginPercentage)/1.14,2))
10414 kshitij.so 415
            sheet.write(sheet_iterator, 14, data.weight*1000)
416
            sheet.write(sheet_iterator, 15, data.weightSnapdeal)
15449 kshitij.so 417
            sheet.write(sheet_iterator, 16, round(data.courierCost*1.14,2))
11098 kshitij.so 418
            sheet.write(sheet_iterator, 17, round(data.logisticCostSnapdeal,2)+round(data.woodenPackagingCost,2))
419
            sheet.write(sheet_iterator, 18, getReasonSheet(data))
10414 kshitij.so 420
            sheet_iterator+=1
421
 
422
    sheet = wbk.add_sheet('Exceptions')
423
 
424
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
425
 
426
    excel_integer_format = '0'
427
    integer_style = xlwt.XFStyle()
428
    integer_style.num_format_str = excel_integer_format
429
    xstr = lambda s: s or ""
430
 
431
    sheet.write(0, 0, "Item ID", heading_xf)
432
    sheet.write(0, 1, "SUPC", heading_xf)
433
    sheet.write(0, 2, "Brand", heading_xf)
434
    sheet.write(0, 3, "Product Name", heading_xf)
435
    sheet.write(0, 4, "Our System SP", heading_xf)
436
    sheet.write(0, 5, "Our TP", heading_xf)
437
    sheet.write(0, 6, "Our System Commission", heading_xf)
438
    sheet.write(0, 7, "Our System Commission %", heading_xf)
439
    sheet.write(0, 8, "Our System Weight (gms)", heading_xf)
440
    sheet.write(0, 9, "Our Courier Cost", heading_xf)
441
 
442
    sheet_iterator=1
443
    for data in exceptionList:
444
        snapdealItem = data[0]
445
        marketplaceItem = data[1]
446
        ds_item = data[2]
447
        sheet.write(sheet_iterator, 0, ds_item.id)
448
        sheet.write(sheet_iterator, 1, snapdealItem.supc)
449
        sheet.write(sheet_iterator, 2, ds_item.brand)
10415 kshitij.so 450
        sheet.write(sheet_iterator, 3, xstr(ds_item.brand)+" "+xstr(ds_item.model_name)+" "+xstr(ds_item.model_number)+" "+xstr(ds_item.color))
10414 kshitij.so 451
        sheet.write(sheet_iterator, 4, snapdealItem.sellingPrice)
452
        sheet.write(sheet_iterator, 5, snapdealItem.transferPrice)
15449 kshitij.so 453
        sheet.write(sheet_iterator, 6, round(snapdealItem.commission*1.14,2))
10414 kshitij.so 454
        sheet.write(sheet_iterator, 7, marketplaceItem.commission)
455
        sheet.write(sheet_iterator, 8, (ds_item.weight*1000))
15449 kshitij.so 456
        sheet.write(sheet_iterator, 9, round(snapdealItem.courierCost*1.14,2))
10419 kshitij.so 457
        sheet_iterator+=1
10414 kshitij.so 458
 
459
    filename = "/tmp/snapdeal-tp-reconciliation-" + str(datetime.now()) + ".xls"
460
    wbk.save(filename)
461
 
462
    try:
10434 kshitij.so 463
        #EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["kshitij.sood@saholic.com"], " Snapdeal TP Reconciliation "+ str(datetime.now()), "", [get_attachment_part(filename)], [""], [])
464
        EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["chandan.kumar@saholic.com","manoj.kumar@saholic.com","yukti.jain@saholic.com","ankush.dhingra@saholic.com","manoj.pal@saholic.com","sandeep.sachdeva@saholic.com"], " Snapdeal TP Reconciliation "+ str(datetime.now()), "", [get_attachment_part(filename)], ["rajneesh.arora@saholic.com","kshitij.sood@saholic.com","chaitnaya.vats@saholic.com","khushal.bhatia@saholic.com"], [])
10414 kshitij.so 465
    except Exception as e:
466
        print e
467
        print "Unable to send report.Trying with local SMTP"
468
        smtpServer = smtplib.SMTP('localhost')
469
        smtpServer.set_debuglevel(1)
470
        sender = 'support@shop2020.in'
11772 kshitij.so 471
        #recipients = ['kshitij.sood@saholic.com']
10414 kshitij.so 472
        msg = MIMEMultipart()
473
        msg['Subject'] = "Snapdeal TP Reconciliation" + ' - ' + str(datetime.now())
474
        msg['From'] = sender
11772 kshitij.so 475
        recipients = ['rajneesh.arora@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','sandeep.sachdeva@saholic.com']
10414 kshitij.so 476
        msg['To'] = ",".join(recipients)
477
        fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
478
        fileMsg.set_payload(file(filename).read())
479
        email.encoders.encode_base64(fileMsg)
10419 kshitij.so 480
        fileMsg.add_header('Content-Disposition','attachment;filename=snapdeal_tp_recon.xls')
10414 kshitij.so 481
        msg.attach(fileMsg)
482
        try:
483
            smtpServer.sendmail(sender, recipients, msg.as_string())
484
            print "Successfully sent email"
485
        except:
486
            print "Error: unable to send email."
10428 kshitij.so 487
 
488
def getReason(data):
11098 kshitij.so 489
    global courierCostToSync 
10428 kshitij.so 490
    reason=""
491
    if data.sellingPrice!=data.sellingPriceSnapdeal:
492
        reason+="Selling Price is different."
15449 kshitij.so 493
    if data.commissionPercentage!= round(float(data.fixedMarginPercentage)/1.14,2):
10430 kshitij.so 494
        reason+="Commission is different."
15449 kshitij.so 495
    if round(data.courierCost*1.14)!=round(data.logisticCostSnapdeal+data.woodenPackagingCost):
10428 kshitij.so 496
        reason+="Courier Cost is different-Check Weight."
11098 kshitij.so 497
        courierCostToSync.append(data)
10428 kshitij.so 498
    return reason
11098 kshitij.so 499
 
500
def getReasonSheet(data):
501
    reason=""
502
    if data.sellingPrice!=data.sellingPriceSnapdeal:
503
        reason+="Selling Price is different."
15449 kshitij.so 504
    if data.commissionPercentage!= round(float(data.fixedMarginPercentage)/1.14,2):
11098 kshitij.so 505
        reason+="Commission is different."
15449 kshitij.so 506
    if round(data.courierCost*1.14)!=round(data.logisticCostSnapdeal+data.woodenPackagingCost):
11098 kshitij.so 507
        reason+="Courier Cost is different-Check Weight."
508
    return reason
509
 
510
def syncCourierCost(courierCostToSync):
511
    global oldPricing
512
    for item in courierCostToSync:
513
        sdItem = SnapdealItem.get_by(item_id=item.itemId)
514
        mpItem = MarketplaceItems.get_by(itemId=item.itemId, source=OrderSource.SNAPDEAL)
515
        oldMpItem = copy.deepcopy(mpItem)
516
        temp = []
517
        temp.append(item)
518
        temp.append(oldMpItem)
519
        addHistory(sdItem)
15449 kshitij.so 520
        sdItem.courierCostMarketplace = round((item.logisticCostSnapdeal+item.woodenPackagingCost)/1.14)
11098 kshitij.so 521
        sdItem.transferPrice = getNewTp(mpItem,item)
522
        sdItem.serviceTax = getNewServiceTax(mpItem,sdItem,item)
15449 kshitij.so 523
        mpItem.courierCostMarketplace = round((item.logisticCostSnapdeal+item.woodenPackagingCost)/1.14)
11098 kshitij.so 524
        mpItem.currentTp = getNewTp(mpItem,item)
525
        mpItem.minimumPossibleSp = getNewLowestPossibleSp(mpItem,sdItem,item)
526
        temp.append(mpItem)
527
        oldPricing.append(temp)
528
    session.commit()
529
 
530
def addHistory(item):
531
    itemHistory = MarketPlaceUpdateHistory()
532
    itemHistory.item_id = item.item_id
533
    itemHistory.source = OrderSource.SNAPDEAL
534
    itemHistory.exceptionPrice = item.exceptionPrice
535
    itemHistory.warehouseId = item.warehouseId
536
    itemHistory.isListedOnSource = item.isListedOnSnapdeal
537
    itemHistory.transferPrice = item.transferPrice
538
    itemHistory.sellingPrice = item.sellingPrice
539
    itemHistory.courierCost = item.courierCost
540
    itemHistory.commission = item.commission
541
    itemHistory.serviceTax = item.serviceTax
542
    itemHistory.suppressPriceFeed = item.suppressPriceFeed
543
    itemHistory.suppressInventoryFeed = item.suppressInventoryFeed
544
    itemHistory.updatedOn = item.updatedOn
545
    itemHistory.maxNlc = item.maxNlc
546
    itemHistory.skuAtSource = item.skuAtSnapdeal
547
    itemHistory.marketPlaceSerialNumber = item.supc
548
    itemHistory.priceUpdatedBy = item.priceUpdatedBy
549
    itemHistory.courierCostMarketplace = item.courierCostMarketplace
10414 kshitij.so 550
 
551
 
11098 kshitij.so 552
 
553
def getNewTp(mpItem,data):
15449 kshitij.so 554
    ourTp = mpItem.currentSp- mpItem.currentSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-((data.logisticCostSnapdeal+data.woodenPackagingCost)/1.14+mpItem.closingFee)*(1+(mpItem.serviceTax/100))-(max(20,(mpItem.pgFee/100)*mpItem.currentSp)*(1+(mpItem.serviceTax/100)));
11098 kshitij.so 555
    return round(ourTp,2)
556
 
557
def getNewServiceTax(mpItem,sdItem,data):
15449 kshitij.so 558
    return round(mpItem.serviceTax/100*(sdItem.commission+(data.logisticCostSnapdeal+data.woodenPackagingCost)/1.14),2)
11098 kshitij.so 559
 
560
def getNewLowestPossibleSp(mpItem,sdItem,data):
561
    if (mpItem.pgFee/100)*mpItem.currentSp>=20:
15449 kshitij.so 562
        lowestPossibleSp = (sdItem.maxNlc+(((data.logisticCostSnapdeal+data.woodenPackagingCost)/1.14)+mpItem.closingFee)*(1+(mpItem.serviceTax/100))*(1+(mpItem.vat/100))+(mpItem.packagingCost+mpItem.otherCost)*(1+(mpItem.vat)/100))/(1-(mpItem.commission/100+mpItem.emiFee/100+mpItem.pgFee/100)*(1+(mpItem.serviceTax/100))*(1+(mpItem.vat)/100)-(mpItem.returnProvision/100)*(1+(mpItem.vat)/100));
11098 kshitij.so 563
    else:
15449 kshitij.so 564
        lowestPossibleSp = (sdItem.maxNlc+(((data.logisticCostSnapdeal+data.woodenPackagingCost)/1.14)+mpItem.closingFee+20)*(1+(mpItem.serviceTax/100))*(1+(mpItem.vat/100))+(mpItem.packagingCost+mpItem.otherCost)*(1+(mpItem.vat)/100))/(1-(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))*(1+(mpItem.vat)/100)-(mpItem.returnProvision/100)*(1+(mpItem.vat)/100));
11098 kshitij.so 565
    return round(lowestPossibleSp,2)   
566
 
567
def sendCCSyncMail():
568
    if len(courierCostToSync) == 0:
569
        return 
570
    xstr = lambda s: s or ""
571
    message="""<html>
572
            <body>
573
            <h3>Courier cost synced</h3>
574
            <table border="1" style="width:100%;">
575
            <thead>
576
            <tr><th>Item Id</th>
577
            <th>Product Name</th>
578
            <th>Selling Price</th>
579
            <th>Old Transfer Price</th>
580
            <th>New Transfer Price</th>
581
            <th>Old Courier Cost</th>
582
            <th>New Courier Cost</th>
583
            <th>Old Margin</th>
584
            <th>New Margin</th>
585
            <th>Old Margin %</th>
586
            <th>New Margin %</th>
587
            </tr></thead>
588
            <tbody>"""
589
    for value in oldPricing:
590
        data = value[0]
591
        mpItemOld = value[1]
592
        mpItemNew = value[2]
593
        message+="""<tr>
594
        <td style="text-align:center">"""+str(data.itemId)+"""</td>
595
        <td style="text-align:center">"""+xstr(data.brand)+" "+xstr(data.modelName)+" "+xstr(data.modelNumber)+" "+xstr(data.color)+"""</td>
596
        <td style="text-align:center">"""+str(mpItemOld.currentSp)+"""</td>
597
        <td style="text-align:center">"""+str(mpItemOld.currentTp)+"""</td>
598
        <td style="text-align:center">"""+str(mpItemNew.currentTp)+"""</td>
599
        <td style="text-align:center">"""+str(mpItemOld.courierCostMarketplace)+"""</td>
600
        <td style="text-align:center">"""+str(mpItemNew.courierCostMarketplace)+"""</td>
601
        <td style="text-align:center">"""+str(round(mpItemOld.currentTp-mpItemOld.minimumPossibleTp))+"""</td>
602
        <td style="text-align:center">"""+str(round(mpItemNew.currentTp-mpItemNew.minimumPossibleTp))+"""</td>
603
        <td style="text-align:center">"""+str(round(((mpItemOld.currentTp-mpItemOld.minimumPossibleTp)/mpItemOld.currentSp)*100,2))+"""</td>
604
        <td style="text-align:center">"""+str(round(((mpItemNew.currentTp-mpItemNew.minimumPossibleTp)/mpItemNew.currentSp)*100,2))+"""</td>
605
        </tr>"""
606
    message+="""</tbody></table></body></html>"""
607
    print message
608
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
609
    mailServer.ehlo()
610
    mailServer.starttls()
611
    mailServer.ehlo()
612
 
613
    #recipients = ['kshitij.sood@saholic.com']
11117 kshitij.so 614
    recipients = ['rajneesh.arora@saholic.com','anikendra.das@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','sandeep.sachdeva@saholic.com']
11098 kshitij.so 615
    msg = MIMEMultipart()
616
    msg['Subject'] = "Snapdeal Courier Cost Synced" + ' - ' + str(datetime.now())
617
    msg['From'] = ""
618
    msg['To'] = ",".join(recipients)
619
    msg.preamble = "Snapdeal Courier Cost Synced" + ' - ' + str(datetime.now())
620
    html_msg = MIMEText(message, 'html')
621
    msg.attach(html_msg)
622
    try:
623
        mailServer.login("build@shop2020.in", "cafe@nes")
624
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
625
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
626
    except Exception as e:
627
        print e
628
        print "Unable to send Snapdeal Courier Cost mail.Lets try with local SMTP."
629
        smtpServer = smtplib.SMTP('localhost')
630
        smtpServer.set_debuglevel(1)
631
        sender = 'support@shop2020.in'
632
        try:
633
            smtpServer.sendmail(sender, recipients, msg.as_string())
634
            print "Successfully sent email"
635
        except:
636
            print "Error: unable to send email."
637
 
10401 amar.kumar 638
def main():
639
    print "Opening snapdeal seller login page"
15450 kshitij.so 640
    br = login("http://sellers.snapdeal.com/")
10401 amar.kumar 641
    exceptionList, fetchedItems = populateStuff(br)
642
    filteredData = filterData(fetchedItems)
643
    sendMail(filteredData,exceptionList)
10414 kshitij.so 644
    write_report(filteredData,exceptionList)
11098 kshitij.so 645
    syncCourierCost(courierCostToSync)
646
    sendCCSyncMail()
10401 amar.kumar 647
 
648
 
649
if __name__ == "__main__":
650
    main()
651
 
652