Subversion Repositories SmartDukaan

Rev

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