Subversion Repositories SmartDukaan

Rev

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