Subversion Repositories SmartDukaan

Rev

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