Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
9881 kshitij.so 1
from elixir import *
9990 kshitij.so 2
from sqlalchemy.sql import or_ ,func, asc
9881 kshitij.so 3
from shop2020.config.client.ConfigClient import ConfigClient
4
from shop2020.model.v1.catalog.impl import DataService
5
from shop2020.model.v1.catalog.impl.DataService import SnapdealItem, MarketplaceItems, Item, \
10289 kshitij.so 6
Category, SourcePercentageMaster, MarketPlaceHistory, MarketPlaceUpdateHistory, MarketPlaceItemPrice, \
7
SourceCategoryPercentage, SourceItemPercentage
9881 kshitij.so 8
from shop2020.thriftpy.model.v1.order.ttypes import OrderSource
9897 kshitij.so 9
from shop2020.thriftpy.model.v1.catalog.ttypes import CompetitionCategory, CompetitionBasis, SalesPotential,\
9949 kshitij.so 10
Decision, RunType
9881 kshitij.so 11
from shop2020.clients.CatalogClient import CatalogClient
12
from shop2020.clients.InventoryClient import InventoryClient
13
import urllib2
14
import time
9949 kshitij.so 15
from datetime import date, datetime, timedelta
16
from shop2020.utils import EmailAttachmentSender
17
from shop2020.utils.EmailAttachmentSender import get_attachment_part
18
import math
9881 kshitij.so 19
import simplejson as json
9949 kshitij.so 20
import xlwt
21
import optparse
9881 kshitij.so 22
import sys
9954 kshitij.so 23
import smtplib
24
from email.mime.text import MIMEText
10221 kshitij.so 25
import email
9954 kshitij.so 26
from email.mime.multipart import MIMEMultipart
10219 kshitij.so 27
import email.encoders
10280 kshitij.so 28
import mechanize
29
import cookielib
9881 kshitij.so 30
 
9954 kshitij.so 31
 
9881 kshitij.so 32
config_client = ConfigClient()
33
host = config_client.get_property('staging_hostname')
10280 kshitij.so 34
syncPrice=config_client.get_property('sync_price_on_marketplace')
35
 
36
 
9881 kshitij.so 37
DataService.initialize(db_hostname=host)
9897 kshitij.so 38
import logging
39
lgr = logging.getLogger()
40
lgr.setLevel(logging.DEBUG)
41
fh = logging.FileHandler('snapdeal-history.log')
42
fh.setLevel(logging.INFO)
43
frmt = logging.Formatter('%(asctime)s - %(name)s - %(message)s')
44
fh.setFormatter(frmt)
45
lgr.addHandler(fh)
9881 kshitij.so 46
 
9949 kshitij.so 47
inventoryMap = {}
48
itemSaleMap = {}
49
 
9881 kshitij.so 50
class __Exception:
51
    SERVER_SIDE=1
52
 
53
 
54
class __SnapdealDetails:
55
    def __init__(self, ourSp, ourInventory, otherInventory, rank, lowestSellerName, lowestSellerCode,lowestSp,secondLowestSellerName, secondLowestSellerCode,secondLowestSellerSp,secondLowestSellerInventory,lowestOfferPrice,secondLowestSellerOfferPrice,ourOfferPrice, totalSeller):
56
        self.ourSp = ourSp
57
        self.ourOfferPrice = ourOfferPrice
58
        self.ourInventory = ourInventory
59
        self.otherInventory = otherInventory
60
        self.rank = rank
61
        self.lowestSellerName = lowestSellerName
62
        self.lowestSellerCode = lowestSellerCode 
63
        self.lowestSp = lowestSp
64
        self.lowestOfferPrice = lowestOfferPrice
65
        self.secondLowestSellerName = secondLowestSellerName
66
        self.secondLowestSellerCode = secondLowestSellerCode
67
        self.secondLowestSellerSp = secondLowestSellerSp
68
        self.secondLowestSellerOfferPrice = secondLowestSellerOfferPrice
69
        self.secondLowestSellerInventory = secondLowestSellerInventory
70
        self.totalSeller = totalSeller
71
 
72
class __SnapdealItemInfo:
73
 
10289 kshitij.so 74
    def __init__(self, supc, nlc, courierCost, item_id, product_group, brand, model_name, model_number, color, weight, parent_category, risky, warehouseId, vatRate, runType, parent_category_name, sourcePercentage):
9881 kshitij.so 75
        self.supc = supc
76
        self.nlc = nlc
77
        self.courierCost = courierCost
78
        self.item_id = item_id
79
        self.product_group = product_group
80
        self.brand = brand
81
        self.model_name = model_name
82
        self.model_number = model_number
83
        self.color = color
84
        self.weight = weight
85
        self.parent_category = parent_category
86
        self.risky = risky
87
        self.warehouseId = warehouseId
88
        self.vatRate = vatRate
9949 kshitij.so 89
        self.runType = runType
90
        self.parent_category_name = parent_category_name
10289 kshitij.so 91
        self.sourcePercentage = sourcePercentage 
9881 kshitij.so 92
 
93
class __SnapdealPricing:
94
 
95
    def __init__(self, ourSp, ourTp, lowestTp, lowestPossibleTp, competitionBasis, secondLowestSellerTp, lowestPossibleSp):
96
        self.ourTp = ourTp
97
        self.lowestTp = lowestTp
98
        self.lowestPossibleTp = lowestPossibleTp
99
        self.competitionBasis = competitionBasis
100
        self.ourSp = ourSp
101
        self.secondLowestSellerTp = secondLowestSellerTp
102
        self.lowestPossibleSp = lowestPossibleSp
10280 kshitij.so 103
 
104
def getBrowserObject():
105
    br = mechanize.Browser(factory=mechanize.RobustFactory())
106
    cj = cookielib.LWPCookieJar()
107
    br.set_cookiejar(cj)
108
    br.set_handle_equiv(True)
109
    br.set_handle_redirect(True)
110
    br.set_handle_referer(True)
111
    br.set_handle_robots(False)
112
    br.set_debug_http(False)
113
    br.set_debug_redirects(False)
114
    br.set_debug_responses(False)
115
 
116
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
117
 
118
    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'),
119
                     ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
120
                     ('Accept-Encoding', 'gzip,deflate,sdch'),                  
121
                     ('Accept-Language', 'en-US,en;q=0.8'),                     
122
                     ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3')]
123
    return br
9881 kshitij.so 124
 
9897 kshitij.so 125
def fetchItemsForAutoDecrease(time):
9954 kshitij.so 126
    successfulAutoDecrease = []
9920 kshitij.so 127
    autoDecrementItems = session.query(MarketPlaceHistory).join((MarketplaceItems,MarketPlaceHistory.item_id==MarketplaceItems.itemId))\
128
    .filter(MarketPlaceHistory.timestamp==time).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.COMPETITIVE)\
129
    .filter(MarketplaceItems.source==OrderSource.SNAPDEAL).filter(MarketplaceItems.autoDecrement==True).all()
130
    #autoDecrementItems = MarketplaceItems.query.filter(MarketplaceItems.autoDecrement==True).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).all()
9897 kshitij.so 131
    inventory_client = InventoryClient().get_client()
9949 kshitij.so 132
    global inventoryMap
9897 kshitij.so 133
    inventoryMap = inventory_client.getInventorySnapshot(0)
134
    for autoDecrementItem in autoDecrementItems:
9920 kshitij.so 135
        #mpHistory = MarketPlaceHistory.get_by(source=OrderSource.SNAPDEAL,item_id=autoDecrementItem.itemId,timestamp=time)
136
        if not autoDecrementItem.competitiveCategory == CompetitionCategory.COMPETITIVE:
137
            markReasonForMpItem(autoDecrementItem,'Category is '+CompetitionCategory._VALUES_TO_NAMES.get(autoDecrementItem.competitiveCategory),Decision.AUTO_DECREMENT_FAILED)
9914 kshitij.so 138
            continue
9920 kshitij.so 139
        if not autoDecrementItem.risky:
140
            markReasonForMpItem(autoDecrementItem,'Item is not risky',Decision.AUTO_DECREMENT_FAILED)
9897 kshitij.so 141
            continue
10008 kshitij.so 142
        if math.ceil(autoDecrementItem.proposedSellingPrice) >= autoDecrementItem.ourSellingPrice:
143
            markReasonForMpItem(autoDecrementItem,'Proposed SP greater than or equal to current SP',Decision.AUTO_DECREMENT_FAILED)
9897 kshitij.so 144
            continue
9966 kshitij.so 145
        if autoDecrementItem.proposedSellingPrice < autoDecrementItem.lowestPossibleSp:
146
            markReasonForMpItem(autoDecrementItem,'Proposed SP less than lowest possible SP',Decision.AUTO_DECREMENT_FAILED)
147
            continue
9920 kshitij.so 148
        if autoDecrementItem.otherInventory < 3:
149
            markReasonForMpItem(autoDecrementItem,'Competition stock is not enough',Decision.AUTO_DECREMENT_FAILED)
9897 kshitij.so 150
            continue
9949 kshitij.so 151
        #oosStatus = inventory_client.getOosStatusesForXDaysForItem(autoDecrementItem.item_id,0,3)
152
        #count,sale,daysOfStock = 0,0,0
153
        #for obj in oosStatus:
154
        #    if not obj.is_oos:
155
        #        count+=1
156
        #        sale = sale+obj.num_orders
157
        #avgSalePerDay=0 if count==0 else (float(sale)/count)
9897 kshitij.so 158
        totalAvailability, totalReserved = 0,0
9920 kshitij.so 159
        if (not inventoryMap.has_key(autoDecrementItem.item_id)):
9949 kshitij.so 160
            markReasonForMpItem(autoDecrementItem,'Inventory info not available',Decision.AUTO_DECREMENT_FAILED)
9913 kshitij.so 161
            continue
9920 kshitij.so 162
        itemInventory=inventoryMap[autoDecrementItem.item_id]
9897 kshitij.so 163
        availableMap  = itemInventory.availability
164
        reserveMap = itemInventory.reserved
165
        for warehouse,availability in availableMap.iteritems():
166
            if warehouse==16:
167
                continue
168
            totalAvailability = totalAvailability+availability
169
        for warehouse,reserve in reserveMap.iteritems():
170
            if warehouse==16:
171
                continue
172
            totalReserved = totalReserved+reserve
173
        if (totalAvailability-totalReserved)<=0:
9949 kshitij.so 174
            markReasonForMpItem(autoDecrementItem,'Net availability is 0',Decision.AUTO_DECREMENT_FAILED)
9897 kshitij.so 175
            continue
9949 kshitij.so 176
        #if (avgSalePerDay==0):  #exclude
177
        #    markReasonForMpItem(autoDecrementItem,'Average sale per day is zero',Decision.AUTO_DECREMENT_FAILED)
178
        #    continue
179
        avgSalePerDay = (itemSaleMap.get(autoDecrementItem.item_id))[2]
180
        try:
181
            daysOfStock = (float(totalAvailability-totalReserved))/avgSalePerDay
182
        except ZeroDivisionError,e:
183
            lgr.info("Infinite days of stock for item "+str(autoDecrementItem.item_id))
184
            daysOfStock = float("inf")
9897 kshitij.so 185
        if daysOfStock<2:
9920 kshitij.so 186
            markReasonForMpItem(autoDecrementItem,'Our stock is not enough',Decision.AUTO_DECREMENT_FAILED)
9897 kshitij.so 187
            continue
188
 
9920 kshitij.so 189
        autoDecrementItem.competitorEnoughStock = True
190
        autoDecrementItem.ourEnoughStock = True
9949 kshitij.so 191
        #autoDecrementItem.avgSales = avgSalePerDay
9920 kshitij.so 192
        autoDecrementItem.decision = Decision.AUTO_DECREMENT_SUCCESS
193
        autoDecrementItem.reason = 'All conditions for auto decrement true'
9954 kshitij.so 194
        successfulAutoDecrease.append(autoDecrementItem)
9920 kshitij.so 195
        lgr.info("Auto decrement success for itemId "+str(autoDecrementItem.item_id)+" Days of stock "+str(daysOfStock)+" avg sales "+str(avgSalePerDay))
9897 kshitij.so 196
    session.commit()
9954 kshitij.so 197
    return successfulAutoDecrease
9897 kshitij.so 198
 
199
def fetchItemsForAutoIncrease(time):
9954 kshitij.so 200
    successfulAutoIncrease = []
9920 kshitij.so 201
    autoIncrementItems = session.query(MarketPlaceHistory).join((MarketplaceItems,MarketPlaceHistory.item_id==MarketplaceItems.itemId))\
202
    .filter(MarketPlaceHistory.timestamp==time).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.BUY_BOX)\
203
    .filter(MarketplaceItems.source==OrderSource.SNAPDEAL).filter(MarketplaceItems.autoIncrement==True).all()
204
    #autoIncrementItems = MarketplaceItems.query.filter(MarketplaceItems.autoIncrement==True).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).all()
9949 kshitij.so 205
    #inventory_client = InventoryClient().get_client()
9897 kshitij.so 206
    for autoIncrementItem in autoIncrementItems:
9920 kshitij.so 207
        #mpHistory = MarketPlaceHistory.get_by(source=OrderSource.SNAPDEAL,item_id=autoIncrementItem.itemId,timestamp=time)
208
        if not autoIncrementItem.competitiveCategory == CompetitionCategory.BUY_BOX:
209
            markReasonForMpItem(autoIncrementItem,'Category is '+CompetitionCategory._VALUES_TO_NAMES.get(autoIncrementItem.competitiveCategory),Decision.AUTO_INCREMENT_FAILED)
9897 kshitij.so 210
            continue
9920 kshitij.so 211
        if autoIncrementItem.totalSeller==1 and autoIncrementItem.ourRank==1:
212
            markReasonForMpItem(autoIncrementItem,'We are the only seller',Decision.AUTO_INCREMENT_FAILED)
9897 kshitij.so 213
            continue
9920 kshitij.so 214
        if autoIncrementItem.proposedSellingPrice <= autoIncrementItem.ourSellingPrice:
215
            markReasonForMpItem(autoIncrementItem,'Proposed SP less than current SP',Decision.AUTO_INCREMENT_FAILED)
9919 kshitij.so 216
            continue
9966 kshitij.so 217
        if autoIncrementItem.proposedSellingPrice >=10000 and autoIncrementItem.ourSellingPrice<10000:
218
            markReasonForMpItem(autoIncrementItem,'Proposed SP is greater than 10,000 and current sp is less than 10,000',Decision.AUTO_INCREMENT_FAILED)
219
            continue
220
        if getLastDaySale(autoIncrementItem.item_id)<=2:
221
            markReasonForMpItem(autoIncrementItem,'Last day sale is less than 3',Decision.AUTO_INCREMENT_FAILED)
222
            continue
9990 kshitij.so 223
        antecedentPrice = session.query(MarketPlaceHistory.ourSellingPrice).filter(MarketPlaceHistory.item_id==autoIncrementItem.item_id).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.timestamp>time-timedelta(days=1)).order_by(asc(MarketPlaceHistory.timestamp)).first()
224
        if antecedentPrice is not None:
225
            if float(math.ceil(autoIncrementItem.ourSellingPrice+max(10,.01*autoIncrementItem.ourSellingPrice))-math.ceil(antecedentPrice[0]+max(10,.01*antecedentPrice[0])))/math.ceil(antecedentPrice[0]+max(10,.01*antecedentPrice[0]))>.02:
226
                markReasonForMpItem(autoIncrementItem,'Maximum price increase in last 24 hours should be 2%',Decision.AUTO_INCREMENT_FAILED)
227
                continue
228
        mpItem = MarketplaceItems.get_by(itemId=autoIncrementItem.item_id,source=OrderSource.SNAPDEAL)
229
        if mpItem.maximumSellingPrice is not None and mpItem.maximumSellingPrice > 0:
230
            if autoIncrementItem.ourSellingPrice+max(10,.01*autoIncrementItem.ourSellingPrice) > mpItem.maximumSellingPrice:
231
                markReasonForMpItem(autoIncrementItem,'Price cannot exceed Maximum Selling Price',Decision.AUTO_INCREMENT_FAILED)
232
                continue
9949 kshitij.so 233
        #oosStatus = inventory_client.getOosStatusesForXDaysForItem(autoIncrementItem.item_id,0,3)
234
        #count,sale,daysOfStock = 0,0,0
235
        #for obj in oosStatus:
236
        #    if not obj.is_oos:
237
        #        count+=1
238
        #        sale = sale+obj.num_orders
239
        #avgSalePerDay=0 if count==0 else (float(sale)/count)
9897 kshitij.so 240
        totalAvailability, totalReserved = 0,0
9920 kshitij.so 241
        if (not inventoryMap.has_key(autoIncrementItem.item_id)):
9949 kshitij.so 242
            markReasonForMpItem(autoIncrementItem,'Inventory info not available',Decision.AUTO_INCREMENT_FAILED)
9913 kshitij.so 243
            continue
9920 kshitij.so 244
        itemInventory=inventoryMap[autoIncrementItem.item_id]
9897 kshitij.so 245
        availableMap  = itemInventory.availability
246
        reserveMap = itemInventory.reserved
247
        for warehouse,availability in availableMap.iteritems():
248
            if warehouse==16:
249
                continue
250
            totalAvailability = totalAvailability+availability
251
        for warehouse,reserve in reserveMap.iteritems():
252
            if warehouse==16:
253
                continue
254
            totalReserved = totalReserved+reserve
9949 kshitij.so 255
        #if (totalAvailability-totalReserved)<=0:
256
        #    markReasonForMpItem(autoIncrementItem,'Our stock is 0',Decision.AUTO_INCREMENT_FAILED)
257
        #    continue
258
        avgSalePerDay = (itemSaleMap.get(autoIncrementItem.item_id))[2]
9912 kshitij.so 259
        if (avgSalePerDay==0):
9920 kshitij.so 260
            markReasonForMpItem(autoIncrementItem,'Average sale per day is zero',Decision.AUTO_INCREMENT_FAILED)
9912 kshitij.so 261
            continue
9897 kshitij.so 262
        daysOfStock = (float(totalAvailability-totalReserved))/avgSalePerDay
263
        if daysOfStock>5:
9920 kshitij.so 264
            markReasonForMpItem(autoIncrementItem,'Our stock is enough',Decision.AUTO_INCREMENT_FAILED)
9897 kshitij.so 265
            continue
266
 
9920 kshitij.so 267
        autoIncrementItem.ourEnoughStock = False
9949 kshitij.so 268
        #autoIncrementItem.avgSales = avgSalePerDay
9920 kshitij.so 269
        autoIncrementItem.decision = Decision.AUTO_INCREMENT_SUCCESS
270
        autoIncrementItem.reason = 'All conditions for auto increment true'
9954 kshitij.so 271
        successfulAutoIncrease.append(autoIncrementItem)
9920 kshitij.so 272
        lgr.info("Auto increment success for itemId "+str(autoIncrementItem.item_id)+" Days of stock "+str(daysOfStock)+" avg sales "+str(avgSalePerDay))
9897 kshitij.so 273
    session.commit()
9954 kshitij.so 274
    return successfulAutoIncrease
9897 kshitij.so 275
 
9949 kshitij.so 276
def calculateAverageSale(oosStatus):
277
    count,sale = 0,0
278
    for obj in oosStatus:
279
        if not obj.is_oos:
280
            count+=1
281
            sale = sale+obj.num_orders
282
    avgSalePerDay=0 if count==0 else (float(sale)/count)
9954 kshitij.so 283
    return round(avgSalePerDay,2)
9949 kshitij.so 284
 
10271 kshitij.so 285
def calculateTotalSale(oosStatus):
286
    sale = 0
287
    for obj in oosStatus:
288
        if not obj.is_oos:
289
            sale = sale+obj.num_orders
290
    return sale
291
 
9949 kshitij.so 292
def getNetAvailability(itemInventory):
293
    totalAvailability, totalReserved = 0,0
294
    availableMap  = itemInventory.availability
295
    reserveMap = itemInventory.reserved
296
    for warehouse,availability in availableMap.iteritems():
297
        if warehouse==16:
298
            continue
299
        totalAvailability = totalAvailability+availability
300
    for warehouse,reserve in reserveMap.iteritems():
301
        if warehouse==16:
302
            continue
303
        totalReserved = totalReserved+reserve
304
    return totalAvailability - totalReserved
305
 
306
def getOosString(oosStatus):
307
    lastNdaySale=""
308
    for obj in oosStatus:
309
        if obj.is_oos:
310
            lastNdaySale += "X-"
311
        else:
312
            lastNdaySale += str(obj.num_orders) + "-"
9954 kshitij.so 313
    return lastNdaySale[:-1]
9949 kshitij.so 314
 
9966 kshitij.so 315
def getLastDaySale(itemId):
316
    return (itemSaleMap.get(itemId))[4]
317
 
9949 kshitij.so 318
def markAutoFavourite():
319
    previouslyAutoFav = []
320
    nowAutoFav = []
321
    marketplaceItems = session.query(MarketplaceItems).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).all()
322
    fromDate = datetime.now()-timedelta(days = 3, hours=datetime.now().hour, minutes=datetime.now().minute, seconds=datetime.now().second)
323
    toDate = datetime.now()-timedelta(days = 0, hours=datetime.now().hour, minutes=datetime.now().minute, seconds=datetime.now().second)
9954 kshitij.so 324
    items = session.query(MarketPlaceHistory.item_id,func.max(MarketPlaceHistory.timestamp)).group_by(MarketPlaceHistory.item_id).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.timestamp.between (fromDate,toDate)).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.BUY_BOX).all()
10271 kshitij.so 325
    toUpdate = [key for key, value in itemSaleMap.items() if value[5] >= 1]
9949 kshitij.so 326
    buyBoxLast3days = []
327
    for item in items:
328
        buyBoxLast3days.append(item[0])
329
    for marketplaceItem in marketplaceItems:
330
        reason = ""
331
        toMark = False
332
        if marketplaceItem.itemId in toUpdate:
333
            toMark = True
10271 kshitij.so 334
            reason+="Total sale is greater than 1 for last five days (Snapdeal)."
9949 kshitij.so 335
        if marketplaceItem.itemId in buyBoxLast3days:
336
            toMark = True
337
            reason+="Item is present in buy box in last 3 days"
338
        if not marketplaceItem.autoFavourite:
339
            print "Item is not under auto favourite"
340
        if toMark:
341
            temp=[]
342
            temp.append(marketplaceItem.itemId)
343
            temp.append(reason)
344
            nowAutoFav.append(temp)
345
        if (not toMark) and marketplaceItem.autoFavourite:
346
            previouslyAutoFav.append(marketplaceItem.itemId)
347
        marketplaceItem.autoFavourite = toMark
348
    session.commit()
349
    return previouslyAutoFav, nowAutoFav
9897 kshitij.so 350
 
9949 kshitij.so 351
 
352
 
9897 kshitij.so 353
def markReasonForMpItem(mpHistory,reason,decision):
354
    mpHistory.decision = decision
355
    mpHistory.reason = reason
356
 
9881 kshitij.so 357
def fetchDetails(supc_code):
358
    url="http://www.snapdeal.com/json/gvbps?supc=%s&catId=91"%(supc_code)
359
    print url
360
    time.sleep(1)
361
    req = urllib2.Request(url)
362
    response = urllib2.urlopen(req)
363
    json_input = response.read()
364
    vendorInfo = json.loads(json_input)
365
    rank ,otherInventory ,ourInventory, ourOfferPrice, ourSp, iterator, secondLowestSellerSp, secondLowestSellerInventory, \
366
    lowestOfferPrice,  secondLowestSellerOfferPrice = (0,)*10
367
    lowestSellerName , lowestSellerCode, secondLowestSellerName, secondLowestSellerCode=('',)*4
368
    for vendor in vendorInfo:
369
        if iterator == 0:
370
            lowestSellerName = vendor['vendorDisplayName']
371
            lowestSellerCode = vendor['vendorCode']
372
            try:
373
                lowestSp = vendor['sellingPriceBefIntCashBack']
374
            except:
375
                lowestSp = vendor['sellingPrice']
376
            lowestOfferPrice = vendor['sellingPrice']
377
 
378
        if iterator ==1:
379
            secondLowestSellerName = vendor['vendorDisplayName']
380
            secondLowestSellerCode =vendor['vendorCode']
381
            try:
382
                secondLowestSellerSp = vendor['sellingPriceBefIntCashBack']
383
            except:
384
                secondLowestSellerSp = vendor['sellingPrice'] 
385
            secondLowestSellerOfferPrice = vendor['sellingPrice'] 
386
            secondLowestSellerInventory = vendor['buyableInventory']
387
 
388
        if vendor['vendorDisplayName'] == 'MobilesnMore':
389
            ourInventory = vendor['buyableInventory']
390
            try:
391
                ourSp = vendor['sellingPriceBefIntCashBack']
392
            except:
393
                ourSp = vendor['sellingPrice']
394
            ourOfferPrice = vendor['sellingPrice']
395
            rank = iterator +1
396
        else:
397
            if rank==0:
398
                otherInventory = otherInventory +vendor['buyableInventory']
399
        iterator+=1
400
    snapdealDetails = __SnapdealDetails(ourSp,ourInventory,otherInventory,rank,lowestSellerName, lowestSellerCode,lowestSp,secondLowestSellerName,secondLowestSellerCode,secondLowestSellerSp,secondLowestSellerInventory,lowestOfferPrice,secondLowestSellerOfferPrice,ourOfferPrice,len(vendorInfo))
401
    return snapdealDetails        
402
 
403
 
10289 kshitij.so 404
def populateStuff(runType,time):
9881 kshitij.so 405
    itemInfo = []
9949 kshitij.so 406
    if runType=='FAVOURITE':
407
        items = session.query(SnapdealItem).join((MarketplaceItems,SnapdealItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).\
408
        filter(or_(MarketplaceItems.autoFavourite==True, MarketplaceItems.manualFavourite==True)).all()
409
    else:
410
        items = session.query(SnapdealItem).all()
10289 kshitij.so 411
    #spm = SourcePercentageMaster.get_by(source=OrderSource.SNAPDEAL)
412
 
9881 kshitij.so 413
    for snapdeal_item in items:
414
        it = Item.query.filter_by(id=snapdeal_item.item_id).one()
415
        category = Category.query.filter_by(id=it.category).one()
9949 kshitij.so 416
        parent_category = Category.query.filter_by(id=category.parent_category_id).first()
10290 kshitij.so 417
        sip = SourceItemPercentage.query.filter(SourceItemPercentage.item_id==it.id).filter(SourceItemPercentage.source==OrderSource.SNAPDEAL).filter(SourceItemPercentage.startDate<=time).filter(SourceItemPercentage.expiryDate>=time).first()
10289 kshitij.so 418
        sourcePercentage = None
419
        if sip is not None:
420
            sourcePercentage = sip
421
        else:
422
            scp = SourceCategoryPercentage.query.filter(SourceCategoryPercentage.category_id==it.category).filter(SourceCategoryPercentage.source==OrderSource.SNAPDEAL).filter(SourceCategoryPercentage.startDate<=time).filter(SourceCategoryPercentage.expiryDate>=time).first()
423
            if scp is not None:
424
                sourcePercentage = scp
425
            else:
426
                spm = SourcePercentageMaster.get_by(source=OrderSource.SNAPDEAL)
427
                sourcePercentage = spm
428
        snapdealItemInfo = __SnapdealItemInfo(snapdeal_item.supc, snapdeal_item.maxNlc,snapdeal_item.courierCost, it.id, it.product_group, it.brand, it.model_name, it.model_number, it.color, it.weight, category.parent_category_id, it.risky, snapdeal_item.warehouseId, None, runType, parent_category.display_name,sourcePercentage)
9881 kshitij.so 429
        itemInfo.append(snapdealItemInfo)
10289 kshitij.so 430
    return itemInfo
9881 kshitij.so 431
 
432
 
10289 kshitij.so 433
def decideCategory(itemInfo):
9949 kshitij.so 434
    global itemSaleMap
9881 kshitij.so 435
    cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin = [],[],[],[],[],[]
436
    catalog_client = CatalogClient().get_client()
437
    inventory_client = InventoryClient().get_client()
438
 
439
    for val in itemInfo:
10291 kshitij.so 440
        spm = val.sourcePercentage
9881 kshitij.so 441
        try:
442
            snapdealDetails = fetchDetails(val.supc)
443
        except:
444
            exceptionItems.append(val)
445
            continue
446
        mpItem = MarketplaceItems.get_by(itemId=val.item_id,source=OrderSource.SNAPDEAL)
447
        warehouse = inventory_client.getWarehouse(val.warehouseId)
9949 kshitij.so 448
 
449
        itemSaleList = []
450
        oosForAllSources = inventory_client.getOosStatusesForXDaysForItem(val.item_id, 0, 3)
451
        oosForSnapdeal = inventory_client.getOosStatusesForXDaysForItem(val.item_id, OrderSource.SNAPDEAL, 5)
9966 kshitij.so 452
        oosForSnapdealLastDay = inventory_client.getOosStatusesForXDaysForItem(val.item_id, OrderSource.SNAPDEAL, 1)
9949 kshitij.so 453
        itemSaleList.append(oosForAllSources)
454
        itemSaleList.append(oosForSnapdeal)
455
        itemSaleList.append(calculateAverageSale(oosForAllSources))
456
        itemSaleList.append(calculateAverageSale(oosForSnapdeal))
9966 kshitij.so 457
        itemSaleList.append(calculateAverageSale(oosForSnapdealLastDay))
10271 kshitij.so 458
        itemSaleList.append(calculateTotalSale(oosForSnapdeal))
9949 kshitij.so 459
        itemSaleMap[val.item_id]=itemSaleList
460
 
9881 kshitij.so 461
        if snapdealDetails.rank==0:
462
            snapdealDetails.ourSp = mpItem.currentSp
463
            snapdealDetails.ourOfferPrice = mpItem.currentSp
464
            ourSp = mpItem.currentSp
465
        else:
466
            ourSp = snapdealDetails.ourSp
467
        vatRate = catalog_client.getVatPercentageForItem(val.item_id, warehouse.stateId, snapdealDetails.ourSp)
468
        val.vatRate = vatRate
469
        if (snapdealDetails.rank==1):
470
            temp=[]
471
            temp.append(snapdealDetails)
472
            temp.append(val)
473
            if (snapdealDetails.secondLowestSellerOfferPrice == snapdealDetails.secondLowestSellerSp) and snapdealDetails.ourOfferPrice==snapdealDetails.ourSp:
474
                competitionBasis = 'SP'
475
            else:
476
                competitionBasis = 'TP'
477
            secondLowestTp=0 if snapdealDetails.totalSeller==1 else getOtherTp(snapdealDetails,val,spm)
478
            snapdealPricing = __SnapdealPricing(snapdealDetails.ourSp,getOurTp(snapdealDetails,val,spm,mpItem),None,getLowestPossibleTp(snapdealDetails,val,spm,mpItem),competitionBasis,secondLowestTp,getLowestPossibleSp(snapdealDetails,val,spm,mpItem))
479
            temp.append(snapdealPricing)
480
            temp.append(mpItem)
481
            buyBoxItems.append(temp)
482
            continue
483
 
484
 
485
        lowestTp = getOtherTp(snapdealDetails,val,spm)
486
        ourTp = getOurTp(snapdealDetails,val,spm,mpItem)
487
        lowestPossibleTp = getLowestPossibleTp(snapdealDetails,val,spm,mpItem)
488
        lowestPossibleSp = getLowestPossibleSp(snapdealDetails,val,spm,mpItem)
489
 
490
        if (ourTp<lowestPossibleTp):
491
            temp=[]
492
            temp.append(snapdealDetails)
493
            temp.append(val)
494
            snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,None,None)
495
            temp.append(snapdealPricing)
496
            negativeMargin.append(temp)
497
            continue
498
 
499
        if (snapdealDetails.lowestOfferPrice == snapdealDetails.lowestSp) and snapdealDetails.ourOfferPrice == snapdealDetails.ourSp:
500
            competitionBasis ='SP'
501
        else:
502
            competitionBasis ='TP'
503
 
504
        if competitionBasis=='SP':
505
            if snapdealDetails.lowestSp > lowestPossibleSp and snapdealDetails.ourInventory!=0:
506
                temp=[]
507
                temp.append(snapdealDetails)
508
                temp.append(val)
509
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'SP',None,lowestPossibleSp)
510
                temp.append(snapdealPricing)
511
                temp.append(mpItem)
512
                competitive.append(temp)
513
                continue
514
        else:
515
            if lowestTp > lowestPossibleTp and snapdealDetails.ourInventory!=0:
516
                temp=[]
517
                temp.append(snapdealDetails)
518
                temp.append(val)
519
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'TP',None,lowestPossibleSp)
520
                temp.append(snapdealPricing)
521
                temp.append(mpItem)
522
                competitive.append(temp)
523
                continue
524
 
525
        if competitionBasis=='SP':
526
            if snapdealDetails.lowestSp > lowestPossibleSp and snapdealDetails.ourInventory==0:
527
                temp=[]
528
                temp.append(snapdealDetails)
529
                temp.append(val)
530
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'SP',None,lowestPossibleSp)
531
                temp.append(snapdealPricing)
532
                temp.append(mpItem)
533
                competitiveNoInventory.append(temp)
534
                continue
535
        else:
536
            if lowestTp > lowestPossibleTp and snapdealDetails.ourInventory==0:
537
                temp=[]
538
                temp.append(snapdealDetails)
539
                temp.append(val)
540
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'TP',None,lowestPossibleSp)
541
                temp.append(snapdealPricing)
542
                temp.append(mpItem)
543
                competitiveNoInventory.append(temp)
544
                continue
545
 
546
        temp=[]
547
        temp.append(snapdealDetails)
548
        temp.append(val)
549
        snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,competitionBasis,None,lowestPossibleSp)
550
        temp.append(snapdealPricing)
551
        temp.append(mpItem)
552
        cantCompete.append(temp)
553
 
9949 kshitij.so 554
    return cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin
555
 
9953 kshitij.so 556
def writeReport(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionList, negativeMargin, previousAutoFav, nowAutoFav,timestamp,runType):
9949 kshitij.so 557
    wbk = xlwt.Workbook()
558
    sheet = wbk.add_sheet('Can\'t Compete')
559
    xstr = lambda s: s or ""
560
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
561
 
562
    excel_integer_format = '0'
563
    integer_style = xlwt.XFStyle()
564
    integer_style.num_format_str = excel_integer_format
565
 
566
    sheet.write(0, 0, "Item ID", heading_xf)
567
    sheet.write(0, 1, "Category", heading_xf)
568
    sheet.write(0, 2, "Product Group.", heading_xf)
569
    sheet.write(0, 3, "SUPC", heading_xf)
570
    sheet.write(0, 4, "Brand", heading_xf)
571
    sheet.write(0, 5, "Product Name", heading_xf)
572
    sheet.write(0, 6, "Weight", heading_xf)
573
    sheet.write(0, 7, "Courier Cost", heading_xf)
574
    sheet.write(0, 8, "Risky", heading_xf)
575
    sheet.write(0, 9, "Our SP", heading_xf)
576
    sheet.write(0, 11, "Our TP", heading_xf)
577
    sheet.write(0, 10, "Our Offer Price", heading_xf)
578
    sheet.write(0, 12, "Our Rank", heading_xf)
579
    sheet.write(0, 13, "Lowest Seller", heading_xf)
580
    sheet.write(0, 14, "Lowest SP", heading_xf)
581
    sheet.write(0, 15, "Lowest TP", heading_xf)
582
    sheet.write(0, 16, "Lowest Offer Price", heading_xf)
583
    sheet.write(0, 17, "Inventory of Top Vendors", heading_xf)
584
    sheet.write(0, 18, "Our Snapdeal Inventory", heading_xf)
585
    sheet.write(0, 19, "Our Net Availability",heading_xf)
586
    sheet.write(0, 20, "Last Five Day Sale", heading_xf)
587
    sheet.write(0, 21, "Average Sale", heading_xf)
588
    sheet.write(0, 22, "Our NLC", heading_xf)
589
    sheet.write(0, 23, "Lowest Possible TP", heading_xf)
590
    sheet.write(0, 24, "Lowest Possible SP", heading_xf)
10381 manish.sha 591
    sheet.write(0, 25, "Subsidy Difference", heading_xf)
9949 kshitij.so 592
    sheet.write(0, 26, "Target TP", heading_xf)
593
    sheet.write(0, 27, "Target SP", heading_xf)  
594
    sheet.write(0, 28, "Target NLC", heading_xf)
595
    sheet.write(0, 29, "Sales Potential", heading_xf)
596
    sheet_iterator = 1
597
    for item in cantCompete:
598
        snapdealDetails = item[0]
599
        snapdealItemInfo = item[1]
600
        snapdealPricing = item[2]
601
        mpItem = item[3]
602
        sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
603
        sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
604
        sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
605
        sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
606
        sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
607
        sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
608
        sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
609
        sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
610
        sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
611
        sheet.write(sheet_iterator, 9, snapdealPricing.ourSp)
612
        sheet.write(sheet_iterator, 10, snapdealDetails.ourOfferPrice)
613
        sheet.write(sheet_iterator, 11, snapdealPricing.ourTp)
614
        sheet.write(sheet_iterator, 12, snapdealDetails.rank)
615
        sheet.write(sheet_iterator, 13, snapdealDetails.lowestSellerName)
616
        sheet.write(sheet_iterator, 14, snapdealDetails.lowestSp)
617
        sheet.write(sheet_iterator, 15, snapdealPricing.lowestTp)
618
        sheet.write(sheet_iterator, 16, snapdealDetails.lowestOfferPrice)
619
        sheet.write(sheet_iterator, 17, snapdealDetails.otherInventory)
620
        sheet.write(sheet_iterator, 18, snapdealDetails.ourInventory)
621
        if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
622
            sheet.write(sheet_iterator, 19, 'Info not available')
623
        else:
624
            sheet.write(sheet_iterator, 19, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
625
        sheet.write(sheet_iterator, 20, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
626
        sheet.write(sheet_iterator, 21, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
627
        sheet.write(sheet_iterator, 22, snapdealItemInfo.nlc)
628
        sheet.write(sheet_iterator, 23, snapdealPricing.lowestPossibleTp)
629
        sheet.write(sheet_iterator, 24, snapdealPricing.lowestPossibleSp)
10381 manish.sha 630
        sheet.write(sheet_iterator, 25, getSubsidyDiff(snapdealDetails))
9949 kshitij.so 631
        if (snapdealPricing.competitionBasis=='SP'):
632
            proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
633
            proposed_tp = getTargetTp(proposed_sp,mpItem)
634
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
635
        else:
10381 manish.sha 636
            #proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
637
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
638
            proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001) - getSubsidyDiff(snapdealDetails)
639
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9949 kshitij.so 640
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 641
        sheet.write(sheet_iterator, 26, round(proposed_tp,2))
642
        sheet.write(sheet_iterator, 27, round(proposed_sp,2))
643
        sheet.write(sheet_iterator, 28, round(target_nlc,2))
9949 kshitij.so 644
        sheet.write(sheet_iterator, 29, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
645
        sheet_iterator+=1
646
 
647
    sheet = wbk.add_sheet('Lowest')
648
 
649
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
650
 
651
    excel_integer_format = '0'
652
    integer_style = xlwt.XFStyle()
653
    integer_style.num_format_str = excel_integer_format
654
    xstr = lambda s: s or ""
655
 
656
    sheet.write(0, 0, "Item ID", heading_xf)
657
    sheet.write(0, 1, "Category", heading_xf)
658
    sheet.write(0, 2, "Product Group.", heading_xf)
659
    sheet.write(0, 3, "SUPC", heading_xf)
660
    sheet.write(0, 4, "Brand", heading_xf)
661
    sheet.write(0, 5, "Product Name", heading_xf)
662
    sheet.write(0, 6, "Weight", heading_xf)
663
    sheet.write(0, 7, "Courier Cost", heading_xf)
664
    sheet.write(0, 8, "Risky", heading_xf)
665
    sheet.write(0, 9, "Our SP", heading_xf)
666
    sheet.write(0, 11, "Our TP", heading_xf)
667
    sheet.write(0, 10, "Our Offer Price", heading_xf)
668
    sheet.write(0, 12, "Our Rank", heading_xf)
669
    sheet.write(0, 13, "Lowest Seller", heading_xf)
670
    sheet.write(0, 14, "Second Lowest Seller", heading_xf)
671
    sheet.write(0, 15, "Second Lowest Price", heading_xf)
672
    sheet.write(0, 16, "Second Lowest Offer Price", heading_xf)
673
    sheet.write(0, 17, "Second Lowest Seller TP", heading_xf)
674
    sheet.write(0, 18, "Our Snapdeal Inventory", heading_xf)
675
    sheet.write(0, 19, "Our Net Availability",heading_xf)
676
    sheet.write(0, 20, "Last Five Day Sale", heading_xf)
677
    sheet.write(0, 21, "Average Sale", heading_xf)
678
    sheet.write(0, 22, "Second Lowest Seller Inventory", heading_xf)
679
    sheet.write(0, 23, "Our NLC", heading_xf)
10381 manish.sha 680
    sheet.write(0, 24, "Subsidy Difference", heading_xf)
9949 kshitij.so 681
    sheet.write(0, 25, "Target TP", heading_xf)
682
    sheet.write(0, 26, "Target SP", heading_xf)
683
    sheet.write(0, 27, "MARGIN INCREASED POTENTIAL", heading_xf)
684
 
685
    sheet_iterator = 1
686
    for item in buyBoxItems:
687
        snapdealDetails = item[0]
688
        snapdealItemInfo = item[1]
689
        snapdealPricing = item[2]
690
        mpItem = item[3]
691
        sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
692
        sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
693
        sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
694
        sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
695
        sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
696
        sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
697
        sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
698
        sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
699
        sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
700
        sheet.write(sheet_iterator, 9, snapdealPricing.ourSp)
701
        sheet.write(sheet_iterator, 10, snapdealDetails.ourOfferPrice)
702
        sheet.write(sheet_iterator, 11, snapdealPricing.ourTp)
703
        sheet.write(sheet_iterator, 12, snapdealDetails.rank)
704
        sheet.write(sheet_iterator, 13, snapdealDetails.lowestSellerName)
705
        sheet.write(sheet_iterator, 14, snapdealDetails.secondLowestSellerName)
706
        sheet.write(sheet_iterator, 15, snapdealDetails.secondLowestSellerSp)
707
        sheet.write(sheet_iterator, 16, snapdealDetails.secondLowestSellerOfferPrice)
708
        sheet.write(sheet_iterator, 17, snapdealPricing.secondLowestSellerTp)
709
        sheet.write(sheet_iterator, 18, snapdealDetails.ourInventory)
710
        if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
711
            sheet.write(sheet_iterator, 19, 'Info not available')
712
        else:
713
            sheet.write(sheet_iterator, 19, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
714
        sheet.write(sheet_iterator, 20, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
715
        sheet.write(sheet_iterator, 21, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
716
        sheet.write(sheet_iterator, 22, snapdealDetails.secondLowestSellerInventory)
717
        sheet.write(sheet_iterator, 23, snapdealItemInfo.nlc)
10381 manish.sha 718
        sheet.write(sheet_iterator, 24, getSubsidyDiff(snapdealDetails))
9949 kshitij.so 719
        if (snapdealPricing.competitionBasis=='SP'):
720
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)), snapdealPricing.lowestPossibleSp)
721
            proposed_tp = getTargetTp(proposed_sp,mpItem)
722
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
723
        else:
10381 manish.sha 724
            #proposed_tp  = max(snapdealPricing.secondLowestSellerTp - max((20, snapdealPricing.secondLowestSellerTp*0.002)), snapdealPricing.lowestPossibleTp)
725
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
726
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)) -getSubsidyDiff(snapdealDetails), snapdealPricing.lowestPossibleSp)
727
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9949 kshitij.so 728
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 729
        sheet.write(sheet_iterator, 25, round(proposed_tp,2))
730
        sheet.write(sheet_iterator, 26, round(proposed_sp,2))
731
        sheet.write(sheet_iterator, 27, round((proposed_tp - snapdealPricing.ourTp),2))
9949 kshitij.so 732
        sheet_iterator+=1
733
 
734
    sheet = wbk.add_sheet('Can Compete-With Inventory')
735
 
736
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
737
 
738
    excel_integer_format = '0'
739
    integer_style = xlwt.XFStyle()
740
    integer_style.num_format_str = excel_integer_format
741
    xstr = lambda s: s or ""
742
 
743
    sheet.write(0, 0, "Item ID", heading_xf)
744
    sheet.write(0, 1, "Category", heading_xf)
745
    sheet.write(0, 2, "Product Group.", heading_xf)
746
    sheet.write(0, 3, "SUPC", heading_xf)
747
    sheet.write(0, 4, "Brand", heading_xf)
748
    sheet.write(0, 5, "Product Name", heading_xf)
749
    sheet.write(0, 6, "Weight", heading_xf)
750
    sheet.write(0, 7, "Courier Cost", heading_xf)
751
    sheet.write(0, 8, "Risky", heading_xf)
752
    sheet.write(0, 9, "Our SP", heading_xf)
753
    sheet.write(0, 11, "Our TP", heading_xf)
754
    sheet.write(0, 10, "Our Offer Price", heading_xf)
755
    sheet.write(0, 12, "Our Rank", heading_xf)
756
    sheet.write(0, 13, "Lowest Seller", heading_xf)
757
    sheet.write(0, 14, "Lowest SP", heading_xf)
758
    sheet.write(0, 15, "Lowest TP", heading_xf)
759
    sheet.write(0, 16, "Lowest Offer Price", heading_xf)
760
    sheet.write(0, 17, "Inventory of Top Vendors", heading_xf)
761
    sheet.write(0, 18, "Our Snapdeal Inventory", heading_xf)
762
    sheet.write(0, 19, "Our Net Availability",heading_xf)
763
    sheet.write(0, 20, "Last Five Day Sale", heading_xf)
764
    sheet.write(0, 21, "Average Sale", heading_xf)
765
    sheet.write(0, 22, "Our NLC", heading_xf)
766
    sheet.write(0, 23, "Lowest Possible TP", heading_xf)
767
    sheet.write(0, 24, "Lowest Possible SP", heading_xf)
10381 manish.sha 768
    sheet.write(0, 25, "Subsidy Difference", heading_xf)
9949 kshitij.so 769
    sheet.write(0, 26, "Target TP", heading_xf)
770
    sheet.write(0, 27, "Target SP", heading_xf)  
771
    sheet.write(0, 28, "Sales Potential", heading_xf)
772
 
773
    sheet_iterator = 1
774
    for item in competitive:
775
        snapdealDetails = item[0]
776
        snapdealItemInfo = item[1]
777
        snapdealPricing = item[2]
778
        mpItem = item[3]
779
        sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
780
        sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
781
        sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
782
        sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
783
        sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
784
        sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
785
        sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
786
        sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
787
        sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
788
        sheet.write(sheet_iterator, 9, snapdealPricing.ourSp)
789
        sheet.write(sheet_iterator, 10, snapdealDetails.ourOfferPrice)
790
        sheet.write(sheet_iterator, 11, snapdealPricing.ourTp)
791
        sheet.write(sheet_iterator, 12, snapdealDetails.rank)
792
        sheet.write(sheet_iterator, 13, snapdealDetails.lowestSellerName)
793
        sheet.write(sheet_iterator, 14, snapdealDetails.lowestSp)
794
        sheet.write(sheet_iterator, 15, snapdealPricing.lowestTp)
795
        sheet.write(sheet_iterator, 16, snapdealDetails.lowestOfferPrice)
796
        sheet.write(sheet_iterator, 17, snapdealDetails.otherInventory)
797
        sheet.write(sheet_iterator, 18, snapdealDetails.ourInventory)
798
        if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
799
            sheet.write(sheet_iterator, 19, 'Info not available')
800
        else:
801
            sheet.write(sheet_iterator, 19, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
802
        sheet.write(sheet_iterator, 20, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
803
        sheet.write(sheet_iterator, 21, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
804
        sheet.write(sheet_iterator, 22, snapdealItemInfo.nlc)
805
        sheet.write(sheet_iterator, 23, snapdealPricing.lowestPossibleTp)
806
        sheet.write(sheet_iterator, 24, snapdealPricing.lowestPossibleSp)
10381 manish.sha 807
        sheet.write(sheet_iterator, 25, getSubsidyDiff(snapdealDetails))
9949 kshitij.so 808
        if (snapdealPricing.competitionBasis=='SP'):
809
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
810
            proposed_tp = getTargetTp(proposed_sp,mpItem)
811
        else:
10381 manish.sha 812
            #proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
813
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
814
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)) -getSubsidyDiff(snapdealDetails), snapdealPricing.lowestPossibleSp)
815
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9954 kshitij.so 816
        sheet.write(sheet_iterator, 26, round(proposed_tp,2))
817
        sheet.write(sheet_iterator, 27, round(proposed_sp,2))
9949 kshitij.so 818
        sheet.write(sheet_iterator, 28, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
819
        sheet_iterator+=1
820
 
821
    sheet = wbk.add_sheet('Negative Margin')
822
 
823
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
824
 
825
    excel_integer_format = '0'
826
    integer_style = xlwt.XFStyle()
827
    integer_style.num_format_str = excel_integer_format
828
    xstr = lambda s: s or ""
829
 
830
    sheet.write(0, 0, "Item ID", heading_xf)
831
    sheet.write(0, 1, "Category", heading_xf)
832
    sheet.write(0, 2, "Product Group.", heading_xf)
833
    sheet.write(0, 3, "SUPC", heading_xf)
834
    sheet.write(0, 4, "Brand", heading_xf)
835
    sheet.write(0, 5, "Product Name", heading_xf)
836
    sheet.write(0, 6, "Weight", heading_xf)
837
    sheet.write(0, 7, "Courier Cost", heading_xf)
838
    sheet.write(0, 8, "Risky", heading_xf)
839
    sheet.write(0, 9, "Our SP", heading_xf)
840
    sheet.write(0, 11, "Our TP", heading_xf)
841
    sheet.write(0, 12, "Lowest Possible TP", heading_xf)
842
    sheet.write(0, 10, "Our Offer Price", heading_xf)
843
    sheet.write(0, 13, "Our Rank", heading_xf)
844
    sheet.write(0, 14, "Our Snapdeal Inventory", heading_xf)
845
    sheet.write(0, 15, "Net Availability", heading_xf)
846
    sheet.write(0, 16, "Last Five Day Sale", heading_xf)
847
    sheet.write(0, 17, "Average Sale", heading_xf)
848
    sheet.write(0, 18, "Our NLC", heading_xf)
849
    sheet.write(0, 19, "Margin", heading_xf)
850
 
851
    sheet_iterator=1
852
    for item in negativeMargin:
853
        snapdealDetails = item[0]
854
        snapdealItemInfo = item[1]
855
        snapdealPricing = item[2]
856
        sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
857
        sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
858
        sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
859
        sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
860
        sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
861
        sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
862
        sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
863
        sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
864
        sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
865
        sheet.write(sheet_iterator, 9, snapdealPricing.ourSp)
866
        sheet.write(sheet_iterator, 10, snapdealDetails.ourOfferPrice)
867
        sheet.write(sheet_iterator, 11, snapdealPricing.ourTp)
868
        sheet.write(sheet_iterator, 12, snapdealPricing.lowestPossibleTp)
869
        sheet.write(sheet_iterator, 13, snapdealDetails.rank)
870
        sheet.write(sheet_iterator, 14, snapdealDetails.ourInventory)
871
        if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
872
            sheet.write(sheet_iterator, 15, 'Info not available')
873
        else:
874
            sheet.write(sheet_iterator, 15, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
875
        sheet.write(sheet_iterator, 16, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
876
        sheet.write(sheet_iterator, 17, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
877
        sheet.write(sheet_iterator, 18, snapdealItemInfo.nlc)
9954 kshitij.so 878
        sheet.write(sheet_iterator, 19, round((snapdealPricing.ourTp - snapdealPricing.lowestPossibleTp),2))
9949 kshitij.so 879
        sheet_iterator+=1
880
 
881
    sheet = wbk.add_sheet('Exception Item List')
882
 
883
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
884
 
885
    excel_integer_format = '0'
886
    integer_style = xlwt.XFStyle()
887
    integer_style.num_format_str = excel_integer_format
888
    xstr = lambda s: s or ""
889
 
890
    sheet.write(0, 0, "Item ID", heading_xf)
891
    sheet.write(0, 1, "Brand", heading_xf)
892
    sheet.write(0, 2, "Product Name", heading_xf)
893
    sheet.write(0, 3, "Reason", heading_xf)
894
    sheet_iterator=1
895
    for item in exceptionList:
896
        sheet.write(sheet_iterator, 0, item.item_id)
897
        sheet.write(sheet_iterator, 1, item.brand)
898
        sheet.write(sheet_iterator, 2, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
899
        sheet.write(sheet_iterator, 3, "Unable to fetch info from Snapdeal")
900
        sheet_iterator+=1
901
 
902
    sheet = wbk.add_sheet('Can Compete-No Inv')
903
 
904
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
905
 
906
    excel_integer_format = '0'
907
    integer_style = xlwt.XFStyle()
908
    integer_style.num_format_str = excel_integer_format
909
    xstr = lambda s: s or ""
910
 
911
    sheet.write(0, 0, "Item ID", heading_xf)
912
    sheet.write(0, 1, "Category", heading_xf)
913
    sheet.write(0, 2, "Product Group.", heading_xf)
914
    sheet.write(0, 3, "SUPC", heading_xf)
915
    sheet.write(0, 4, "Brand", heading_xf)
916
    sheet.write(0, 5, "Product Name", heading_xf)
917
    sheet.write(0, 6, "Weight", heading_xf)
918
    sheet.write(0, 7, "Courier Cost", heading_xf)
919
    sheet.write(0, 8, "Risky", heading_xf)
920
    sheet.write(0, 9, "Our SP", heading_xf)
921
    sheet.write(0, 11, "Our TP", heading_xf)
922
    sheet.write(0, 10, "Our Offer Price", heading_xf)
923
    sheet.write(0, 12, "Our Rank", heading_xf)
924
    sheet.write(0, 13, "Lowest Seller", heading_xf)
925
    sheet.write(0, 14, "Lowest SP", heading_xf)
926
    sheet.write(0, 15, "Lowest TP", heading_xf)
927
    sheet.write(0, 16, "Lowest Offer Price", heading_xf)
928
    sheet.write(0, 17, "Inventory of Top Vendors", heading_xf)
929
    sheet.write(0, 18, "Our Snapdeal Inventory", heading_xf)
930
    sheet.write(0, 19, "Our Net Availability",heading_xf)
931
    sheet.write(0, 20, "Last Five Day Sale", heading_xf)
932
    sheet.write(0, 21, "Average Sale", heading_xf)
933
    sheet.write(0, 22, "Our NLC", heading_xf)
934
    sheet.write(0, 23, "Lowest Possible TP", heading_xf)
935
    sheet.write(0, 24, "Lowest Possible SP", heading_xf)
10381 manish.sha 936
    sheet.write(0, 25, "Subsidy Difference", heading_xf)
9949 kshitij.so 937
    sheet.write(0, 26, "Target TP", heading_xf)
938
    sheet.write(0, 27, "Target SP", heading_xf)  
939
    sheet.write(0, 28, "Target NLC", heading_xf)
940
    sheet.write(0, 29, "Sales Potential", heading_xf)
941
 
942
    sheet_iterator = 1
943
    for item in competitiveNoInventory:
944
        snapdealDetails = item[0]
945
        snapdealItemInfo = item[1]
946
        snapdealPricing = item[2]
947
        mpItem = item[3]
948
        if ((not inventoryMap.has_key(snapdealItemInfo.item_id)) or getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id))<=0):
949
            sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
950
            sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
951
            sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
952
            sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
953
            sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
954
            sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
955
            sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
956
            sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
957
            sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
958
            sheet.write(sheet_iterator, 9, snapdealPricing.ourSp)
959
            sheet.write(sheet_iterator, 10, snapdealDetails.ourOfferPrice)
960
            sheet.write(sheet_iterator, 11, snapdealPricing.ourTp)
961
            sheet.write(sheet_iterator, 12, snapdealDetails.rank)
962
            sheet.write(sheet_iterator, 13, snapdealDetails.lowestSellerName)
963
            sheet.write(sheet_iterator, 14, snapdealDetails.lowestSp)
964
            sheet.write(sheet_iterator, 15, snapdealPricing.lowestTp)
965
            sheet.write(sheet_iterator, 16, snapdealDetails.lowestOfferPrice)
966
            sheet.write(sheet_iterator, 17, snapdealDetails.otherInventory)
967
            sheet.write(sheet_iterator, 18, snapdealDetails.ourInventory)
968
            if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
969
                sheet.write(sheet_iterator, 19, 'Info not available')
970
            else:
971
                sheet.write(sheet_iterator, 19, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
972
            sheet.write(sheet_iterator, 20, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
973
            sheet.write(sheet_iterator, 21, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
974
            sheet.write(sheet_iterator, 22, snapdealItemInfo.nlc)
975
            sheet.write(sheet_iterator, 23, snapdealPricing.lowestPossibleTp)
976
            sheet.write(sheet_iterator, 24, snapdealPricing.lowestPossibleSp)
10381 manish.sha 977
            sheet.write(sheet_iterator, 25, getSubsidyDiff(snapdealDetails))
9949 kshitij.so 978
            if (snapdealPricing.competitionBasis=='SP'):
979
                proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
980
                proposed_tp = getTargetTp(proposed_sp,mpItem)
981
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
982
            else:
10381 manish.sha 983
                #proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
984
                #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
985
                proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001) -getSubsidyDiff(snapdealDetails)
986
                proposed_tp = getTargetTp(proposed_sp,mpItem)
9949 kshitij.so 987
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 988
            sheet.write(sheet_iterator, 26, round(proposed_tp,2))
989
            sheet.write(sheet_iterator, 27, round(proposed_sp,2))
990
            sheet.write(sheet_iterator, 28, round(target_nlc,2))
9949 kshitij.so 991
            sheet.write(sheet_iterator, 29, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
992
            sheet_iterator+=1
993
 
994
    sheet = wbk.add_sheet('Can Compete-No Inv On SD')
995
 
996
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
997
 
998
    excel_integer_format = '0'
999
    integer_style = xlwt.XFStyle()
1000
    integer_style.num_format_str = excel_integer_format
1001
    xstr = lambda s: s or ""
1002
 
1003
    sheet.write(0, 0, "Item ID", heading_xf)
1004
    sheet.write(0, 1, "Category", heading_xf)
1005
    sheet.write(0, 2, "Product Group.", heading_xf)
1006
    sheet.write(0, 3, "SUPC", heading_xf)
1007
    sheet.write(0, 4, "Brand", heading_xf)
1008
    sheet.write(0, 5, "Product Name", heading_xf)
1009
    sheet.write(0, 6, "Weight", heading_xf)
1010
    sheet.write(0, 7, "Courier Cost", heading_xf)
1011
    sheet.write(0, 8, "Risky", heading_xf)
1012
    sheet.write(0, 9, "Our SP", heading_xf)
1013
    sheet.write(0, 11, "Our TP", heading_xf)
1014
    sheet.write(0, 10, "Our Offer Price", heading_xf)
1015
    sheet.write(0, 12, "Our Rank", heading_xf)
1016
    sheet.write(0, 13, "Lowest Seller", heading_xf)
1017
    sheet.write(0, 14, "Lowest SP", heading_xf)
1018
    sheet.write(0, 15, "Lowest TP", heading_xf)
1019
    sheet.write(0, 16, "Lowest Offer Price", heading_xf)
1020
    sheet.write(0, 17, "Inventory of Top Vendors", heading_xf)
1021
    sheet.write(0, 18, "Our Snapdeal Inventory", heading_xf)
1022
    sheet.write(0, 19, "Our Net Availability",heading_xf)
1023
    sheet.write(0, 20, "Last Five Day Sale", heading_xf)
1024
    sheet.write(0, 21, "Average Sale", heading_xf)
1025
    sheet.write(0, 22, "Our NLC", heading_xf)
1026
    sheet.write(0, 23, "Lowest Possible TP", heading_xf)
1027
    sheet.write(0, 24, "Lowest Possible SP", heading_xf)
10381 manish.sha 1028
    sheet.write(0, 25, "Subsidy Difference", heading_xf)
9949 kshitij.so 1029
    sheet.write(0, 26, "Target TP", heading_xf)
1030
    sheet.write(0, 27, "Target SP", heading_xf)  
1031
    sheet.write(0, 28, "Target NLC", heading_xf)
1032
    sheet.write(0, 29, "Sales Potential", heading_xf)
1033
 
1034
    sheet_iterator = 1
1035
    for item in competitiveNoInventory:
1036
        snapdealDetails = item[0]
1037
        snapdealItemInfo = item[1]
1038
        snapdealPricing = item[2]
1039
        mpItem = item[3]
1040
        if (inventoryMap.has_key(snapdealItemInfo.item_id) and getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id))>0):
1041
            sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
1042
            sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
1043
            sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
1044
            sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
1045
            sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
1046
            sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
1047
            sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
1048
            sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
1049
            sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
1050
            sheet.write(sheet_iterator, 9, snapdealPricing.ourSp)
1051
            sheet.write(sheet_iterator, 10, snapdealDetails.ourOfferPrice)
1052
            sheet.write(sheet_iterator, 11, snapdealPricing.ourTp)
1053
            sheet.write(sheet_iterator, 12, snapdealDetails.rank)
1054
            sheet.write(sheet_iterator, 13, snapdealDetails.lowestSellerName)
1055
            sheet.write(sheet_iterator, 14, snapdealDetails.lowestSp)
1056
            sheet.write(sheet_iterator, 15, snapdealPricing.lowestTp)
1057
            sheet.write(sheet_iterator, 16, snapdealDetails.lowestOfferPrice)
1058
            sheet.write(sheet_iterator, 17, snapdealDetails.otherInventory)
1059
            sheet.write(sheet_iterator, 18, snapdealDetails.ourInventory)
1060
            if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
1061
                sheet.write(sheet_iterator, 19, 'Info not available')
1062
            else:
1063
                sheet.write(sheet_iterator, 19, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
1064
            sheet.write(sheet_iterator, 20, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
1065
            sheet.write(sheet_iterator, 21, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
1066
            sheet.write(sheet_iterator, 22, snapdealItemInfo.nlc)
1067
            sheet.write(sheet_iterator, 23, snapdealPricing.lowestPossibleTp)
1068
            sheet.write(sheet_iterator, 24, snapdealPricing.lowestPossibleSp)
10381 manish.sha 1069
            sheet.write(sheet_iterator, 25, getSubsidyDiff(snapdealDetails))
9949 kshitij.so 1070
            if (snapdealPricing.competitionBasis=='SP'):
1071
                proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
1072
                proposed_tp = getTargetTp(proposed_sp,mpItem)
1073
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
1074
            else:
10381 manish.sha 1075
                #proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
1076
                #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
1077
                proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001) -getSubsidyDiff(snapdealDetails)
1078
                proposed_tp = getTargetTp(proposed_sp,mpItem)
9949 kshitij.so 1079
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1080
            sheet.write(sheet_iterator, 26, round(proposed_tp,2))
1081
            sheet.write(sheet_iterator, 27, round(proposed_sp,2))
1082
            sheet.write(sheet_iterator, 28, round(target_nlc,2))
9949 kshitij.so 1083
            sheet.write(sheet_iterator, 29, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
1084
            sheet_iterator+=1
9953 kshitij.so 1085
 
1086
    if (runType=='FULL'):    
1087
        sheet = wbk.add_sheet('Auto Favorites')
1088
 
1089
        heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1090
 
1091
        excel_integer_format = '0'
1092
        integer_style = xlwt.XFStyle()
1093
        integer_style.num_format_str = excel_integer_format
1094
        xstr = lambda s: s or ""
1095
 
1096
        sheet.write(0, 0, "Item ID", heading_xf)
1097
        sheet.write(0, 1, "Brand", heading_xf)
1098
        sheet.write(0, 2, "Product Name", heading_xf)
1099
        sheet.write(0, 3, "Auto Favourite", heading_xf)
1100
        sheet.write(0, 4, "Reason", heading_xf)
1101
 
1102
        sheet_iterator=1
1103
        for autoFav in nowAutoFav:
1104
            itemId = autoFav[0]
1105
            reason = autoFav[1]
1106
            it = Item.query.filter_by(id=itemId).one()
1107
            sheet.write(sheet_iterator, 0, itemId)
1108
            sheet.write(sheet_iterator, 1, it.brand)
1109
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1110
            sheet.write(sheet_iterator, 3, "True")
1111
            sheet.write(sheet_iterator, 4, reason)
1112
            sheet_iterator+=1
1113
        for prevFav in previousAutoFav:
1114
            it = Item.query.filter_by(id=prevFav).one()
1115
            sheet.write(sheet_iterator, 0, prevFav)
1116
            sheet.write(sheet_iterator, 1, it.brand)
1117
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1118
            sheet.write(sheet_iterator, 3, "False")
1119
            sheet_iterator+=1
9949 kshitij.so 1120
 
1121
 
1122
    autoPricingItems = session.query(MarketPlaceHistory,Item).join((Item,MarketPlaceHistory.item_id==Item.id)).filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.decision.in_([1,2,3,4])).all()
1123
    sheet = wbk.add_sheet('Auto Inc and Dec')
1124
 
1125
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1126
 
1127
    excel_integer_format = '0'
1128
    integer_style = xlwt.XFStyle()
1129
    integer_style.num_format_str = excel_integer_format
1130
    xstr = lambda s: s or ""
1131
 
1132
    sheet.write(0, 0, "Item ID", heading_xf)
1133
    sheet.write(0, 1, "Brand", heading_xf)
1134
    sheet.write(0, 2, "Product Name", heading_xf)
1135
    sheet.write(0, 3, "Decision", heading_xf)
1136
    sheet.write(0, 4, "Reason", heading_xf)
9954 kshitij.so 1137
    sheet.write(0, 5, "Old Selling Price", heading_xf)
1138
    sheet.write(0, 6, "Selling Price Updated",heading_xf)
9949 kshitij.so 1139
 
1140
    sheet_iterator=1
1141
    for autoPricingItem in autoPricingItems:
1142
        mpHistory = autoPricingItem[0]
1143
        item = autoPricingItem[1]
9954 kshitij.so 1144
        it = Item.query.filter_by(id=item.id).one()
9949 kshitij.so 1145
        sheet.write(sheet_iterator, 0, item.id)
1146
        sheet.write(sheet_iterator, 1, it.brand)
1147
        sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1148
        sheet.write(sheet_iterator, 3, Decision._VALUES_TO_NAMES.get(mpHistory.decision))
1149
        sheet.write(sheet_iterator, 4, mpHistory.reason)
1150
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_DECREMENT_SUCCESS":
9954 kshitij.so 1151
            sheet.write(sheet_iterator, 5, mpHistory.ourSellingPrice)
1152
            sheet.write(sheet_iterator, 6, math.ceil(mpHistory.proposedSellingPrice))
9949 kshitij.so 1153
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_INCREMENT_SUCCESS":
9954 kshitij.so 1154
            sheet.write(sheet_iterator, 5, mpHistory.ourSellingPrice)
1155
            sheet.write(sheet_iterator, 6, math.ceil(mpHistory.ourSellingPrice+max(10,.01*mpHistory.ourSellingPrice)))
9949 kshitij.so 1156
        sheet_iterator+=1
1157
 
9953 kshitij.so 1158
    filename = "/tmp/snapdeal-report-"+runType+" " + str(timestamp) + ".xls"
9949 kshitij.so 1159
    wbk.save(filename)
10207 kshitij.so 1160
    try:
10293 kshitij.so 1161
        #EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["kshitij.sood@saholic.com"], " Snapdeal Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], [""], [])
1162
        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"], " Snapdeal Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], ["rajneesh.arora@saholic.com","rajveer.singh@saholic.com","vikram.raghav@saholic.com","kshitij.sood@saholic.com","chaitnaya.vats@saholic.com","khushal.bhatia@saholic.com"], [])
10207 kshitij.so 1163
    except Exception as e:
1164
        print e
10219 kshitij.so 1165
        print "Unable to send report.Trying with local SMTP"
1166
        smtpServer = smtplib.SMTP('localhost')
1167
        smtpServer.set_debuglevel(1)
1168
        sender = 'support@shop2020.in'
10293 kshitij.so 1169
        #recipients = ['kshitij.sood@saholic.com']
10219 kshitij.so 1170
        msg = MIMEMultipart()
1171
        msg['Subject'] = "Snapdeal Auto Pricing" + ' - ' + str(datetime.now())
1172
        msg['From'] = sender
10293 kshitij.so 1173
        recipients = ['rajneesh.arora@saholic.com','rajveer.singh@saholic.com','vikram.raghav@saholic.com','kshitij.sood@saholic.com','khushal.bhatia@saholic.com','chaitnaya.vats@saholic.com','chandan.kumar@saholic.com','manoj.kumar@saholic.com','yukti.jain@saholic.com','ankush.dhingra@saholic.com','manoj.pal@saholic.com']
10222 kshitij.so 1174
        msg['To'] = ",".join(recipients)
10219 kshitij.so 1175
        fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
1176
        fileMsg.set_payload(file(filename).read())
1177
        email.encoders.encode_base64(fileMsg)
1178
        fileMsg.add_header('Content-Disposition','attachment;filename=snapdeal.xls')
1179
        msg.attach(fileMsg)
1180
        try:
1181
            smtpServer.sendmail(sender, recipients, msg.as_string())
1182
            print "Successfully sent email"
1183
        except:
1184
            print "Error: unable to send email."
9881 kshitij.so 1185
 
10219 kshitij.so 1186
 
9881 kshitij.so 1187
def commitExceptionList(exceptionList,timestamp):
9949 kshitij.so 1188
    exceptionItems=[]
9881 kshitij.so 1189
    for item in exceptionList:
1190
        mpHistory = MarketPlaceHistory()
1191
        mpHistory.item_id =item.item_id
1192
        mpHistory.source = OrderSource.SNAPDEAL 
1193
        mpHistory.competitiveCategory = CompetitionCategory.EXCEPTION
1194
        mpHistory.risky = item.risky
1195
        mpHistory.timestamp = timestamp
9949 kshitij.so 1196
        mpHistory.run = RunType._NAMES_TO_VALUES.get(item.runType)
1197
        exceptionItems.append(mpHistory)
9881 kshitij.so 1198
    session.commit()
9949 kshitij.so 1199
    return exceptionItems
9881 kshitij.so 1200
 
1201
def commitNegativeMargin(negativeMargin,timestamp):
9949 kshitij.so 1202
    negativeMarginItems = []
9881 kshitij.so 1203
    for item in negativeMargin:
1204
        snapdealDetails = item[0]
1205
        snapdealItemInfo = item[1]
1206
        snapdealPricing = item[2]
1207
        mpHistory = MarketPlaceHistory()
1208
        mpHistory.item_id = snapdealItemInfo.item_id
1209
        mpHistory.source = OrderSource.SNAPDEAL
1210
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1211
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1212
        mpHistory.ourTp = snapdealPricing.ourTp
9919 kshitij.so 1213
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
9881 kshitij.so 1214
        mpHistory.ourNlc = snapdealItemInfo.nlc
1215
        mpHistory.ourInventory = snapdealDetails.ourInventory
1216
        mpHistory.otherInventory = snapdealDetails.otherInventory
1217
        mpHistory.ourRank = snapdealDetails.rank
9919 kshitij.so 1218
        mpHistory.risky = snapdealItemInfo.risky
1219
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp  
9881 kshitij.so 1220
        mpHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
1221
        mpHistory.totalSeller = snapdealDetails.totalSeller
9949 kshitij.so 1222
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[2]
9881 kshitij.so 1223
        mpHistory.timestamp = timestamp
9949 kshitij.so 1224
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1225
        negativeMarginItems.append(mpHistory) 
9881 kshitij.so 1226
    session.commit()
9949 kshitij.so 1227
    return negativeMarginItems
9881 kshitij.so 1228
 
1229
def commitCompetitive(competitive,timestamp):
9949 kshitij.so 1230
    competitiveItems = []
9881 kshitij.so 1231
    for item in competitive:
1232
        snapdealDetails = item[0]
1233
        snapdealItemInfo = item[1]
1234
        snapdealPricing = item[2]
1235
        mpItem = item[3]
1236
        mpHistory = MarketPlaceHistory()
1237
        mpHistory.item_id = snapdealItemInfo.item_id
1238
        mpHistory.source = OrderSource.SNAPDEAL
1239
        mpHistory.lowestTp = snapdealPricing.lowestTp
1240
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1241
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1242
        mpHistory.ourInventory = snapdealDetails.ourInventory
1243
        mpHistory.otherInventory = snapdealDetails.otherInventory
1244
        mpHistory.ourRank = snapdealDetails.rank
1245
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1246
        mpHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
1247
        mpHistory.risky = snapdealItemInfo.risky
1248
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1249
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1250
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1251
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1252
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1253
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1254
        mpHistory.ourTp = snapdealPricing.ourTp
1255
        mpHistory.ourNlc = snapdealItemInfo.nlc
1256
        if (snapdealPricing.competitionBasis=='SP'):
1257
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
1258
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9954 kshitij.so 1259
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1260
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1261
        else:
10381 manish.sha 1262
            #proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
1263
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
1264
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)) -getSubsidyDiff(snapdealDetails), snapdealPricing.lowestPossibleSp)
1265
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9954 kshitij.so 1266
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1267
            mpHistory.proposedTp = round(proposed_tp,2)
9919 kshitij.so 1268
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1269
        mpHistory.totalSeller = snapdealDetails.totalSeller
9949 kshitij.so 1270
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[2]
9881 kshitij.so 1271
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
1272
        mpHistory.timestamp = timestamp
9949 kshitij.so 1273
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1274
        competitiveItems.append(mpHistory) 
9881 kshitij.so 1275
    session.commit()
9949 kshitij.so 1276
    return competitiveItems
9881 kshitij.so 1277
 
1278
def commitCompetitiveNoInventory(competitiveNoInventory,timestamp):
9949 kshitij.so 1279
    competitiveNoInventoryItems = []
9881 kshitij.so 1280
    for item in competitiveNoInventory:
1281
        snapdealDetails = item[0]
1282
        snapdealItemInfo = item[1]
1283
        snapdealPricing = item[2]
1284
        mpItem = item[3]
1285
        mpHistory = MarketPlaceHistory()
1286
        mpHistory.item_id = snapdealItemInfo.item_id
1287
        mpHistory.source = OrderSource.SNAPDEAL
1288
        mpHistory.lowestTp = snapdealPricing.lowestTp
1289
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1290
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1291
        mpHistory.ourInventory = snapdealDetails.ourInventory
1292
        mpHistory.otherInventory = snapdealDetails.otherInventory
1293
        mpHistory.ourRank = snapdealDetails.rank
1294
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1295
        mpHistory.competitiveCategory = CompetitionCategory.COMPETITIVE_NO_INVENTORY
1296
        mpHistory.risky = snapdealItemInfo.risky
1297
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1298
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1299
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1300
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1301
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1302
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1303
        mpHistory.ourTp = snapdealPricing.ourTp
1304
        mpHistory.ourNlc = snapdealItemInfo.nlc
1305
        if (snapdealPricing.competitionBasis=='SP'):
1306
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
1307
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9954 kshitij.so 1308
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1309
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1310
        else:
10381 manish.sha 1311
            #proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
1312
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
1313
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)) -getSubsidyDiff(snapdealDetails), snapdealPricing.lowestPossibleSp)
1314
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9954 kshitij.so 1315
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1316
            mpHistory.proposedTp = round(proposed_tp,2)
9919 kshitij.so 1317
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1318
        mpHistory.totalSeller = snapdealDetails.totalSeller
9949 kshitij.so 1319
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[2]
9881 kshitij.so 1320
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
1321
        mpHistory.timestamp = timestamp
9949 kshitij.so 1322
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1323
        competitiveNoInventoryItems.append(mpHistory)
9881 kshitij.so 1324
    session.commit()
9949 kshitij.so 1325
    return competitiveNoInventoryItems
9881 kshitij.so 1326
 
1327
def commitCantCompete(cantCompete,timestamp):
9949 kshitij.so 1328
    cantComepeteItems = []
9881 kshitij.so 1329
    for item in cantCompete:
1330
        snapdealDetails = item[0]
1331
        snapdealItemInfo = item[1]
1332
        snapdealPricing = item[2]
1333
        mpItem = item[3]
1334
        mpHistory = MarketPlaceHistory()
1335
        mpHistory.item_id = snapdealItemInfo.item_id
1336
        mpHistory.source = OrderSource.SNAPDEAL
1337
        mpHistory.lowestTp = snapdealPricing.lowestTp
1338
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1339
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1340
        mpHistory.ourInventory = snapdealDetails.ourInventory
1341
        mpHistory.otherInventory = snapdealDetails.otherInventory
1342
        mpHistory.ourRank = snapdealDetails.rank
1343
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1344
        mpHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
1345
        mpHistory.risky = snapdealItemInfo.risky
1346
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1347
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1348
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1349
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1350
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1351
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1352
        mpHistory.ourTp = snapdealPricing.ourTp
1353
        mpHistory.ourNlc = snapdealItemInfo.nlc
1354
        if (snapdealPricing.competitionBasis=='SP'):
1355
            proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
1356
            proposed_tp = getTargetTp(proposed_sp,mpItem)
1357
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1358
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1359
            mpHistory.proposedTp = round(proposed_tp,2)
1360
            mpHistory.targetNlc = round(target_nlc,2)
9881 kshitij.so 1361
        else:
10381 manish.sha 1362
            #proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
1363
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
1364
            proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001) -getSubsidyDiff(snapdealDetails)
1365
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9881 kshitij.so 1366
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1367
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1368
            mpHistory.proposedTp = round(proposed_tp,2)
1369
            mpHistory.targetNlc = round(target_nlc,2)
9919 kshitij.so 1370
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1371
        mpHistory.totalSeller = snapdealDetails.totalSeller
9949 kshitij.so 1372
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[2]
9881 kshitij.so 1373
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
1374
        mpHistory.timestamp = timestamp
9949 kshitij.so 1375
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1376
        cantComepeteItems.append(mpHistory)
9881 kshitij.so 1377
    session.commit()
9949 kshitij.so 1378
    return cantComepeteItems
9881 kshitij.so 1379
 
1380
def commitBuyBox(buyBoxItems,timestamp):
9949 kshitij.so 1381
    buyBoxList = []
9881 kshitij.so 1382
    for item in buyBoxItems:
1383
        snapdealDetails = item[0]
1384
        snapdealItemInfo = item[1]
1385
        snapdealPricing = item[2]
1386
        mpItem = item[3]
1387
        mpHistory = MarketPlaceHistory()
1388
        mpHistory.item_id = snapdealItemInfo.item_id
1389
        mpHistory.source = OrderSource.SNAPDEAL
1390
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1391
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1392
        mpHistory.ourInventory = snapdealDetails.ourInventory
1393
        mpHistory.secondLowestInventory = snapdealDetails.secondLowestSellerInventory
1394
        mpHistory.ourRank = snapdealDetails.rank
1395
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1396
        mpHistory.competitiveCategory = CompetitionCategory.BUY_BOX
1397
        mpHistory.risky = snapdealItemInfo.risky
1398
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1399
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1400
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1401
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1402
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1403
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1404
        mpHistory.ourTp = snapdealPricing.ourTp
1405
        mpHistory.ourNlc = snapdealItemInfo.nlc
1406
        mpHistory.secondLowestSellerName = snapdealDetails.secondLowestSellerName
1407
        mpHistory.secondLowestSellerCode = snapdealDetails.secondLowestSellerCode
9885 kshitij.so 1408
        mpHistory.secondLowestSellingPrice = snapdealDetails.secondLowestSellerSp
9888 kshitij.so 1409
        mpHistory.secondLowestOfferPrice = snapdealDetails.secondLowestSellerOfferPrice
9881 kshitij.so 1410
        mpHistory.secondLowestTp = snapdealPricing.secondLowestSellerTp
1411
        if (snapdealPricing.competitionBasis=='SP'):
1412
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)), snapdealPricing.lowestPossibleSp)
1413
            proposed_tp = getTargetTp(proposed_sp,mpItem)
1414
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1415
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1416
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1417
            #mpHistory.targetNlc = target_nlc
1418
        else:
10381 manish.sha 1419
            #proposed_tp  = max(snapdealPricing.secondLowestSellerTp - max((20, snapdealPricing.secondLowestSellerTp*0.002)), snapdealPricing.lowestPossibleTp)
1420
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
1421
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)) -getSubsidyDiff(snapdealDetails), snapdealPricing.lowestPossibleSp)
1422
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9881 kshitij.so 1423
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1424
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1425
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1426
            #mpHistory.targetNlc = target_nlc
9919 kshitij.so 1427
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1428
        mpHistory.marginIncreasedPotential = proposed_tp - snapdealPricing.ourTp
1429
        mpHistory.totalSeller = snapdealDetails.totalSeller
9949 kshitij.so 1430
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[2]
9881 kshitij.so 1431
        mpHistory.timestamp = timestamp
9949 kshitij.so 1432
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1433
        buyBoxList.append(mpHistory)
9881 kshitij.so 1434
    session.commit()
9949 kshitij.so 1435
    return buyBoxList 
10219 kshitij.so 1436
 
9990 kshitij.so 1437
def sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease):
1438
    xstr = lambda s: s or ""
1439
    catalog_client = CatalogClient().get_client()
1440
    inventory_client = InventoryClient().get_client()
1441
    message="""<html>
1442
            <body>
1443
            <h3>Auto Decrease Items</h3>
1444
            <table border="1" style="width:100%;">
1445
            <thead>
1446
            <tr><th>Item Id</th>
1447
            <th>Product Name</th>
1448
            <th>Old Price</th>
1449
            <th>New Price</th>
1450
            <th>Old Margin</th>
1451
            <th>New Margin</th>
1452
            <th>Snapdeal Inventory</th>
1453
            </tr></thead>
1454
            <tbody>"""
1455
    for item in successfulAutoDecrease:
1456
        it = Item.query.filter_by(id=item.item_id).one()
1457
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1458
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1459
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1460
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, item.proposedSellingPrice)
1461
        newMargin = round(getNewOurTp(mpItem,item.proposedSellingPrice) - getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,item.proposedSellingPrice))  
1462
        message+="""<tr>
1463
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
1464
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
1465
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
1466
                <td style="text-align:center">"""+str(math.ceil(item.proposedSellingPrice))+"""</td>
1467
                <td style="text-align:center">"""+str(round(item.margin))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
1468
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/item.proposedSellingPrice)*100,1))+"%)"+"""</td>
1469
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
1470
                </tr>"""
1471
    message+="""</tbody></table><h3>Auto Increase Items</h3><table border="1" style="width:100%;">
1472
            <thead>
1473
            <tr><th>Item Id</th>
1474
            <th>Product Name</th>
1475
            <th>Old Price</th>
1476
            <th>New Price</th>
1477
            <th>Old Margin</th>
1478
            <th>New Margin</th>
1479
            <th>Snapdeal Inventory</th>
1480
            </tr></thead>
1481
            <tbody>"""
1482
    for item in successfulAutoIncrease:
1483
        it = Item.query.filter_by(id=item.item_id).one()
1484
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1485
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1486
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1487
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
1488
        newMargin = round(getNewOurTp(mpItem,item.ourSellingPrice+max(10,.01*item.ourSellingPrice)) - getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))  
1489
        message+="""<tr>
1490
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
1491
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
1492
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
1493
                <td style="text-align:center">"""+str(math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))+"""</td>
1494
                <td style="text-align:center">"""+str(round((item.margin),1))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
1495
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))*100,1))+"%)"+"""</td>
1496
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
1497
                </tr>"""
1498
    message+="""</tbody></table></body></html>"""
1499
    print message
1500
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
1501
    mailServer.ehlo()
1502
    mailServer.starttls()
1503
    mailServer.ehlo()
1504
 
10293 kshitij.so 1505
    #recipients = ['kshitij.sood@saholic.com']
1506
    recipients = ['rajneesh.arora@saholic.com','rajveer.singh@saholic.com','vikram.raghav@saholic.com','kshitij.sood@saholic.com','khushal.bhatia@saholic.com','chaitnaya.vats@saholic.com','chandan.kumar@saholic.com','manoj.kumar@saholic.com','yukti.jain@saholic.com','ankush.dhingra@saholic.com','manoj.pal@saholic.com']
9990 kshitij.so 1507
    msg = MIMEMultipart()
1508
    msg['Subject'] = "Snapdeal Auto Pricing" + ' - ' + str(datetime.now())
1509
    msg['From'] = ""
10005 kshitij.so 1510
    msg['To'] = ",".join(recipients)
9990 kshitij.so 1511
    msg.preamble = "Snapdeal Auto Pricing" + ' - ' + str(datetime.now())
1512
    html_msg = MIMEText(message, 'html')
1513
    msg.attach(html_msg)
10207 kshitij.so 1514
    try:
1515
        mailServer.login("build@shop2020.in", "cafe@nes")
1516
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
1517
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
1518
    except Exception as e:
1519
        print e
10219 kshitij.so 1520
        print "Unable to send pricing mail.Lets try with local SMTP."
1521
        smtpServer = smtplib.SMTP('localhost')
1522
        smtpServer.set_debuglevel(1)
1523
        sender = 'support@shop2020.in'
1524
        try:
1525
            smtpServer.sendmail(sender, recipients, msg.as_string())
1526
            print "Successfully sent email"
1527
        except:
1528
            print "Error: unable to send email."
1529
 
9990 kshitij.so 1530
 
1531
def commitPricing(successfulAutoDecrease,successfulAutoIncrease,timestamp):
1532
    catalog_client = CatalogClient().get_client()
1533
    inventory_client = InventoryClient().get_client()
1534
    for item in successfulAutoDecrease:
1535
        it = Item.query.filter_by(id=item.item_id).one()
1536
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1537
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1538
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1539
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, item.proposedSellingPrice)
1540
        addHistory(sdItem)
1541
        sdItem.transferPrice = getNewOurTp(mpItem,item.proposedSellingPrice)
1542
        sdItem.sellingPrice = math.ceil(item.proposedSellingPrice)
10293 kshitij.so 1543
        if ((mpItem.pgFee/100)*sdItem.sellingPrice)>=20:
1544
            sdItem.commission = round((mpItem.commission/100+mpItem.pgFee/100)*(sdItem.sellingPrice),2)
1545
        else:
1546
            sdItem.commission = round((mpItem.commission/100)*(sdItem.sellingPrice),2)+20
9990 kshitij.so 1547
        sdItem.serviceTax = round((mpItem.serviceTax/100)*(sdItem.commission+sdItem.courierCost),2)
1548
        sdItem.updatedOn = timestamp
1549
        sdItem.priceUpdatedBy = 'SYSTEM'
1550
        mpItem.currentSp = sdItem.sellingPrice
1551
        mpItem.currentTp = sdItem.transferPrice
1552
        mpItem.minimumPossibleTp = getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,item.proposedSellingPrice) 
1553
        mpItem.minimumPossibleSp = getNewLowestPossibleSp(mpItem,item.ourNlc,vatRate)
1554
        markStatusForMarketplaceItems(sdItem,mpItem)
1555
    session.commit()
1556
    for item in successfulAutoIncrease:
1557
        it = Item.query.filter_by(id=item.item_id).one()
1558
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1559
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1560
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1561
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
1562
        addHistory(sdItem)
1563
        sdItem.transferPrice = getNewOurTp(mpItem,item.ourSellingPrice+max(10,.01*item.ourSellingPrice))
1564
        sdItem.sellingPrice = math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice))
10293 kshitij.so 1565
        if ((mpItem.pgFee/100)*sdItem.sellingPrice)>=20:
1566
            sdItem.commission = round((mpItem.commission/100+mpItem.pgFee/100)*(sdItem.sellingPrice),2)
1567
        else:
1568
            sdItem.commission = round((mpItem.commission/100)*(sdItem.sellingPrice),2)+20
9990 kshitij.so 1569
        sdItem.serviceTax = round((mpItem.serviceTax/100)*(sdItem.commission+sdItem.courierCost),2)
1570
        sdItem.updatedOn = timestamp
1571
        sdItem.priceUpdatedBy = 'SYSTEM'
1572
        mpItem.currentSp = sdItem.sellingPrice
1573
        mpItem.currentTp = sdItem.transferPrice
1574
        mpItem.minimumPossibleTp = getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,sdItem.sellingPrice) 
1575
        mpItem.minimumPossibleSp = getNewLowestPossibleSp(mpItem,item.ourNlc,vatRate)
1576
        markStatusForMarketplaceItems(sdItem,mpItem)
1577
    session.commit()
1578
 
10280 kshitij.so 1579
def updatePricesOnSnapdeal(successfulAutoDecrease,successfulAutoIncrease):
10284 kshitij.so 1580
    if syncPrice=='false':
10280 kshitij.so 1581
        return
1582
    url = 'http://support.shop2020.in:8080/Support/reports'
1583
    br = getBrowserObject()
1584
    br.open(url)
1585
    br.open(url)
1586
    br.select_form(nr=0)
10286 kshitij.so 1587
    br.form['username'] = "manoj"
1588
    br.form['password'] = "man0j"
10280 kshitij.so 1589
    br.submit()
1590
    for item in successfulAutoDecrease:
1591
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1592
        sellingPrice =  str(math.ceil(item.proposedSellingPrice))
1593
        supc = sdItem.supc
10286 kshitij.so 1594
        updateUrl = 'http://support.shop2020.in:8080/Support/snapdeal-list!updateForAutoPricing?sellingPrice=%s&supc=%s&itemId=%s'%(sellingPrice,supc,str(item.item_id))
1595
        br.open(updateUrl)
10280 kshitij.so 1596
    for item in successfulAutoIncrease:
1597
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1598
        sellingPrice =  str(math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
1599
        supc = sdItem.supc
1600
        updateUrl = 'http://support.shop2020.in:8080/Support/snapdeal-list!updateForAutoPricing?sellingPrice=%s&supc=%s&itemId=%s'%(sellingPrice,supc,str(item.item_id))
1601
        br.open(updateUrl)
1602
 
1603
 
1604
 
9990 kshitij.so 1605
def addHistory(item):
10097 kshitij.so 1606
    itemHistory = MarketPlaceUpdateHistory()
9990 kshitij.so 1607
    itemHistory.item_id = item.item_id
10097 kshitij.so 1608
    itemHistory.source = OrderSource.SNAPDEAL
9990 kshitij.so 1609
    itemHistory.exceptionPrice = item.exceptionPrice
1610
    itemHistory.warehouseId = item.warehouseId
10097 kshitij.so 1611
    itemHistory.isListedOnSource = item.isListedOnSnapdeal
9990 kshitij.so 1612
    itemHistory.transferPrice = item.transferPrice
1613
    itemHistory.sellingPrice = item.sellingPrice
1614
    itemHistory.courierCost = item.courierCost
1615
    itemHistory.commission = item.commission
1616
    itemHistory.serviceTax = item.serviceTax
1617
    itemHistory.suppressPriceFeed = item.suppressPriceFeed
1618
    itemHistory.suppressInventoryFeed = item.suppressInventoryFeed
1619
    itemHistory.updatedOn = item.updatedOn
1620
    itemHistory.maxNlc = item.maxNlc
10097 kshitij.so 1621
    itemHistory.skuAtSource = item.skuAtSnapdeal
1622
    itemHistory.marketPlaceSerialNumber = item.supc
9990 kshitij.so 1623
    itemHistory.priceUpdatedBy = item.priceUpdatedBy
1624
 
1625
def markStatusForMarketplaceItems(snapdealItem,marketplaceItem):
1626
    markUpdatedItem = MarketPlaceItemPrice.query.filter(MarketPlaceItemPrice.item_id==snapdealItem.item_id).filter(MarketPlaceItemPrice.source==marketplaceItem.source).first()
1627
    if markUpdatedItem is None:
1628
        marketPlaceItemPrice = MarketPlaceItemPrice()
1629
        marketPlaceItemPrice.item_id = snapdealItem.item_id
1630
        marketPlaceItemPrice.source = marketplaceItem.source
1631
        marketPlaceItemPrice.lastUpdatedOn = snapdealItem.updatedOn
1632
        marketPlaceItemPrice.sellingPrice = snapdealItem.sellingPrice 
1633
        marketPlaceItemPrice.suppressPriceFeed = snapdealItem.suppressPriceFeed
1634
        marketPlaceItemPrice.isListedOnSource = snapdealItem.isListedOnSnapdeal
1635
    else:
1636
        if (markUpdatedItem.sellingPrice!=snapdealItem.sellingPrice or markUpdatedItem.suppressPriceFeed!=snapdealItem.suppressPriceFeed or markUpdatedItem.isListedOnSource!=snapdealItem.isListedOnSnapdeal):
1637
            markUpdatedItem.lastUpdatedOn = snapdealItem.updatedOn
1638
        markUpdatedItem.sellingPrice = snapdealItem.sellingPrice
1639
        markUpdatedItem.suppressPriceFeed = snapdealItem.suppressPriceFeed
1640
        markUpdatedItem.isListedOnSource = snapdealItem.isListedOnSnapdeal
10031 kshitij.so 1641
 
1642
def processLostBuyBoxItems(previousProcessingTimestamp,currentTimestamp):
1643
    previous_buy_box = session.query(MarketPlaceHistory.item_id).filter(MarketPlaceHistory.timestamp==previousProcessingTimestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.BUY_BOX).all()
1644
    cant_compete = session.query(MarketPlaceHistory.item_id).filter(MarketPlaceHistory.timestamp==currentTimestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.CANT_COMPETE).all()
10032 kshitij.so 1645
    lost_buy_box = list(set(list(zip(*previous_buy_box)[0]))&set(list(zip(*cant_compete)[0])))
10031 kshitij.so 1646
    if len(lost_buy_box)==0:
1647
        return
1648
    xstr = lambda s: s or ""
1649
    message="""<html>
1650
            <body>
1651
            <h3>Lost Buy Box</h3>
1652
            <table border="1" style="width:100%;">
1653
            <thead>
1654
            <tr><th>Item Id</th>
1655
            <th>Product Name</th>
1656
            <th>Current Price</th>
1657
            <th>Current TP</th>
1658
            <th>Current Margin</th>
1659
            <th>Competition TP</th>
1660
            <th>Lowest Possible TP</th>
1661
            <th>NLC</th>
1662
            <th>Target NLC</th>
1663
            <th>Snapdeal Inventory</th>
1664
            <th>Total Inventory</th>
1665
            <th>Sales History</th>
1666
            </tr></thead>
1667
            <tbody>"""
1668
    items = session.query(MarketPlaceHistory).filter(MarketPlaceHistory.timestamp==currentTimestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.item_id.in_(lost_buy_box)).all()
1669
    for item in items:
1670
        it = Item.query.filter_by(id=item.item_id).one()
1671
        netInventory=''
1672
        if not inventoryMap.has_key(item.item_id):
1673
            netInventory='Info Not Available'
1674
        else:
1675
            netInventory = str(getNetAvailability(inventoryMap.get(item.item_id)))
1676
        message+="""<tr>
1677
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
1678
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
1679
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
1680
                <td style="text-align:center">"""+str(item.ourTp)+"""</td>
1681
                <td style="text-align:center">"""+str(round(item.margin))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
1682
                <td style="text-align:center">"""+str(item.lowestTp)+"""</td>
1683
                <td style="text-align:center">"""+str(item.lowestPossibleTp)+"""</td>
1684
                <td style="text-align:center">"""+str(item.ourNlc)+"""</td>
1685
                <td style="text-align:center">"""+str(item.targetNlc)+"""</td>
1686
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
1687
                <td style="text-align:center">"""+netInventory+"""</td>
1688
                <td style="text-align:center">"""+getOosString((itemSaleMap.get(item.item_id))[1])+"""</td>
1689
                </tr>"""
1690
    message+="""</tbody></table></body></html>"""
1691
    print message
1692
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
1693
    mailServer.ehlo()
1694
    mailServer.starttls()
1695
    mailServer.ehlo()
1696
 
10033 kshitij.so 1697
    #recipients = ['kshitij.sood@saholic.com']
1698
    recipients = ['rajneesh.arora@saholic.com','rajveer.singh@saholic.com','vikram.raghav@saholic.com','kshitij.sood@saholic.com','khushal.bhatia@saholic.com','chaitnaya.vats@saholic.com','chandan.kumar@saholic.com','manoj.kumar@saholic.com','yukti.jain@saholic.com','ankush.dhingra@saholic.com','manoj.pal@saholic.com']
10031 kshitij.so 1699
    msg = MIMEMultipart()
1700
    msg['Subject'] = "Snapdeal Lost Buy Box" + ' - ' + str(datetime.now())
1701
    msg['From'] = ""
1702
    msg['To'] = ",".join(recipients)
1703
    msg.preamble = "Snapdeal Lost Buy Box" + ' - ' + str(datetime.now())
1704
    html_msg = MIMEText(message, 'html')
1705
    msg.attach(html_msg)
10207 kshitij.so 1706
    try:
1707
        mailServer.login("build@shop2020.in", "cafe@nes")
1708
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
1709
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
1710
    except Exception as e:
1711
        print e
10381 manish.sha 1712
        print "Unable to send lost buy box mail.Lets try local SMTP"
10219 kshitij.so 1713
        smtpServer = smtplib.SMTP('localhost')
1714
        smtpServer.set_debuglevel(1)
1715
        sender = 'support@shop2020.in'
1716
        try:
1717
            smtpServer.sendmail(sender, recipients, msg.as_string())
1718
            print "Successfully sent email"
1719
        except:
1720
            print "Error: unable to send email."
1721
 
10381 manish.sha 1722
def getSubsidyDiff(snapdealDetails):
1723
    ourSubsidy = snapdealDetails.ourSp - snapdealDetails.ourOfferPrice
1724
    if snapdealDetails.rank !=1:
1725
        competitionSubsidy = snapdealDetails.lowestSp - snapdealDetails.lowestOfferPrice
1726
    else:
1727
        competitionSubsidy = snapdealDetails.secondLowestSellerSp - snapdealDetails.secondLowestOfferPrice
1728
    return competitionSubsidy - ourSubsidy    
9881 kshitij.so 1729
 
1730
def getOtherTp(snapdealDetails,val,spm):
1731
    if val.parent_category==10011:
1732
        commissionPercentage = spm.competitorCommissionAccessory
1733
    else:
1734
        commissionPercentage = spm.competitorCommissionOther
1735
    if snapdealDetails.rank==1:
10289 kshitij.so 1736
        otherTp = snapdealDetails.secondLowestSellerSp- snapdealDetails.secondLowestSellerSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100))-(max(20,(spm.pgFee/100)*snapdealDetails.secondLowestSellerSp)*(1+(spm.serviceTax/100)));
9954 kshitij.so 1737
        return round(otherTp,2)
10289 kshitij.so 1738
    otherTp = snapdealDetails.lowestSp- snapdealDetails.lowestSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100))-(max(20,(spm.pgFee/100)*snapdealDetails.lowestSp)*(1+(spm.serviceTax/100)));
9954 kshitij.so 1739
    return round(otherTp,2)
9881 kshitij.so 1740
 
1741
def getLowestPossibleTp(snapdealDetails,val,spm,mpItem):
1742
    if snapdealDetails.rank==0:
1743
        return mpItem.minimumPossibleTp
1744
    vat = (snapdealDetails.ourSp/(1+(val.vatRate/100))-(val.nlc/(1+(val.vatRate/100))))*(val.vatRate/100);
1745
    inHouseCost = 15+vat+(mpItem.returnProvision/100)*snapdealDetails.ourSp+mpItem.otherCost;
1746
    lowest_possible_tp = val.nlc+inHouseCost;
9954 kshitij.so 1747
    return round(lowest_possible_tp,2)
9881 kshitij.so 1748
 
1749
def getOurTp(snapdealDetails,val,spm,mpItem):
1750
    if snapdealDetails.rank==0:
1751
        return mpItem.currentTp
10289 kshitij.so 1752
    ourTp = snapdealDetails.ourSp- snapdealDetails.ourSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(val.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))-(max(20,(spm.pgFee/100)*snapdealDetails.ourSp)*(1+(spm.serviceTax/100)));
9954 kshitij.so 1753
    return round(ourTp,2)
9966 kshitij.so 1754
 
1755
def getNewLowestPossibleTp(mpItem,nlc,vatRate,proposedSellingPrice):
1756
    vat = (proposedSellingPrice/(1+(vatRate/100))-(nlc/(1+(vatRate/100))))*(vatRate/100);
1757
    inHouseCost = 15+vat+(mpItem.returnProvision/100)*proposedSellingPrice+mpItem.otherCost;
1758
    lowest_possible_tp = nlc+inHouseCost;
1759
    return round(lowest_possible_tp,2)
1760
 
1761
def getNewOurTp(mpItem,proposedSellingPrice):
10289 kshitij.so 1762
    ourTp = proposedSellingPrice- proposedSellingPrice*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))-(max(20,(mpItem.pgFee/100)*proposedSellingPrice)*(1+(mpItem.serviceTax/100)));
9966 kshitij.so 1763
    return round(ourTp,2)
9990 kshitij.so 1764
 
1765
def getNewLowestPossibleSp(mpItem,nlc,vatRate):
10294 kshitij.so 1766
    if (mpItem.pgFee/100)*mpItem.currentSp>=20:
10289 kshitij.so 1767
        lowestPossibleSp = (nlc+(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))*(1+(vatRate/100))+(15+mpItem.otherCost)*(1+(vatRate)/100))/(1-(mpItem.commission/100+mpItem.emiFee/100+mpItem.pgFee/100)*(1+(mpItem.serviceTax/100))*(1+(vatRate)/100)-(mpItem.returnProvision/100)*(1+(vatRate)/100));
1768
    else:
1769
        lowestPossibleSp = (nlc+(mpItem.courierCost+mpItem.closingFee+20)*(1+(mpItem.serviceTax/100))*(1+(vatRate/100))+(15+mpItem.otherCost)*(1+(vatRate)/100))/(1-(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))*(1+(vatRate)/100)-(mpItem.returnProvision/100)*(1+(vatRate)/100));
9990 kshitij.so 1770
    return round(lowestPossibleSp,2)    
9881 kshitij.so 1771
 
1772
def getLowestPossibleSp(snapdealDetails,val,spm,mpItem):
1773
    if snapdealDetails.rank==0:
1774
        return mpItem.minimumPossibleSp
10289 kshitij.so 1775
    #lowestPossibleSp = (val.nlc+(val.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))*(1+(val.vatRate/100))+(15+mpItem.otherCost)*(1+(val.vatRate)/100))/(1-(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))*(1+(val.vatRate)/100)-(mpItem.returnProvision/100)*(1+(val.vatRate)/100));
1776
    if (mpItem.pgFee/100)*snapdealDetails.ourSp>=20:
1777
        lowestPossibleSp = (val.nlc+(val.courierCost+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))
1778
    else:
1779
        lowestPossibleSp = (val.nlc+(val.courierCost+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))
9954 kshitij.so 1780
    return round(lowestPossibleSp,2)    
9881 kshitij.so 1781
 
1782
def getTargetTp(targetSp,mpItem):
10289 kshitij.so 1783
    targetTp = targetSp- targetSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))-(max(20,(mpItem.pgFee/100)*targetSp)*(1+(mpItem.serviceTax/100)))
9954 kshitij.so 1784
    return round(targetTp,2)
9881 kshitij.so 1785
 
10289 kshitij.so 1786
def getTargetSp(targetTp,mpItem,ourSp):
10292 kshitij.so 1787
    if (ourSp*(mpItem.pgFee/100)) < 20:
10289 kshitij.so 1788
        targetSp = float(targetTp+(mpItem.courierCost+mpItem.closingFee+20)*(1+(mpItem.serviceTax/100)))/(1-((mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))))
1789
    else:
1790
        targetSp = float(targetTp+(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100)))/(1-((mpItem.commission/100+mpItem.emiFee/100+mpItem.pgFee/100)*(1+(mpItem.serviceTax/100))))
9954 kshitij.so 1791
    return round(targetSp,2)
9881 kshitij.so 1792
 
1793
def getSalesPotential(lowestOfferPrice,ourNlc):
1794
    if lowestOfferPrice - ourNlc < 0:
1795
        return 'HIGH'
9897 kshitij.so 1796
    elif (float(lowestOfferPrice - ourNlc))/lowestOfferPrice >=0 and (float(lowestOfferPrice - ourNlc))/lowestOfferPrice <=.02:
9881 kshitij.so 1797
        return 'MEDIUM'
1798
    else:
1799
        return 'LOW'  
1800
 
1801
def main():
9949 kshitij.so 1802
    parser = optparse.OptionParser()
1803
    parser.add_option("-t", "--type", dest="runType",
1804
                   default="FULL", type="string",
1805
                   help="Run type FULL or FAVOURITE")
1806
    (options, args) = parser.parse_args()
1807
    if options.runType not in ('FULL','FAVOURITE'):
1808
        print "Run type argument illegal."
1809
        sys.exit(1)
10289 kshitij.so 1810
    timestamp = datetime.now()
1811
    itemInfo= populateStuff(options.runType,timestamp)
9881 kshitij.so 1812
    cantCompete, buyBoxItems, competitive, \
10289 kshitij.so 1813
    competitiveNoInventory, exceptionList, negativeMargin = decideCategory(itemInfo)
10031 kshitij.so 1814
    previousProcessingTimestamp = session.query(func.max(MarketPlaceHistory.timestamp)).filter(MarketPlaceHistory.source==7).one()
9949 kshitij.so 1815
    exceptionItems = commitExceptionList(exceptionList,timestamp)
1816
    cantComepeteItems = commitCantCompete(cantCompete,timestamp)
1817
    buyBoxList = commitBuyBox(buyBoxItems,timestamp)
1818
    competitiveItems = commitCompetitive(competitive,timestamp)
1819
    competitiveNoInventoryItems = commitCompetitiveNoInventory(competitiveNoInventory,timestamp)
1820
    negativeMarginItems = commitNegativeMargin(negativeMargin,timestamp)
9954 kshitij.so 1821
    successfulAutoDecrease = fetchItemsForAutoDecrease(timestamp)
1822
    successfulAutoIncrease = fetchItemsForAutoIncrease(timestamp)
9949 kshitij.so 1823
    if options.runType=='FULL':
1824
        previousAutoFav, nowAutoFav = markAutoFavourite()
9954 kshitij.so 1825
    if options.runType=='FULL':
1826
        writeReport(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionList, negativeMargin, previousAutoFav, nowAutoFav,timestamp, options.runType)
1827
    else:
1828
        writeReport(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionList, negativeMargin, None, None, timestamp, options.runType)
10293 kshitij.so 1829
    commitPricing(successfulAutoDecrease,successfulAutoIncrease,timestamp)
9954 kshitij.so 1830
    sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease)
10031 kshitij.so 1831
    processLostBuyBoxItems(previousProcessingTimestamp[0],timestamp)
10293 kshitij.so 1832
    updatePricesOnSnapdeal(successfulAutoDecrease,successfulAutoIncrease)
9897 kshitij.so 1833
 
9881 kshitij.so 1834
if __name__ == '__main__':
1835
    main()