Subversion Repositories SmartDukaan

Rev

Rev 10292 | Rev 10294 | 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)
591
    sheet.write(0, 25, "Competition Basis ", heading_xf)
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)
630
        sheet.write(sheet_iterator, 25, snapdealPricing.competitionBasis)
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:
636
            proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
10289 kshitij.so 637
            proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
9949 kshitij.so 638
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 639
        sheet.write(sheet_iterator, 26, round(proposed_tp,2))
640
        sheet.write(sheet_iterator, 27, round(proposed_sp,2))
641
        sheet.write(sheet_iterator, 28, round(target_nlc,2))
9949 kshitij.so 642
        sheet.write(sheet_iterator, 29, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
643
        sheet_iterator+=1
644
 
645
    sheet = wbk.add_sheet('Lowest')
646
 
647
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
648
 
649
    excel_integer_format = '0'
650
    integer_style = xlwt.XFStyle()
651
    integer_style.num_format_str = excel_integer_format
652
    xstr = lambda s: s or ""
653
 
654
    sheet.write(0, 0, "Item ID", heading_xf)
655
    sheet.write(0, 1, "Category", heading_xf)
656
    sheet.write(0, 2, "Product Group.", heading_xf)
657
    sheet.write(0, 3, "SUPC", heading_xf)
658
    sheet.write(0, 4, "Brand", heading_xf)
659
    sheet.write(0, 5, "Product Name", heading_xf)
660
    sheet.write(0, 6, "Weight", heading_xf)
661
    sheet.write(0, 7, "Courier Cost", heading_xf)
662
    sheet.write(0, 8, "Risky", heading_xf)
663
    sheet.write(0, 9, "Our SP", heading_xf)
664
    sheet.write(0, 11, "Our TP", heading_xf)
665
    sheet.write(0, 10, "Our Offer Price", heading_xf)
666
    sheet.write(0, 12, "Our Rank", heading_xf)
667
    sheet.write(0, 13, "Lowest Seller", heading_xf)
668
    sheet.write(0, 14, "Second Lowest Seller", heading_xf)
669
    sheet.write(0, 15, "Second Lowest Price", heading_xf)
670
    sheet.write(0, 16, "Second Lowest Offer Price", heading_xf)
671
    sheet.write(0, 17, "Second Lowest Seller TP", heading_xf)
672
    sheet.write(0, 18, "Our Snapdeal Inventory", heading_xf)
673
    sheet.write(0, 19, "Our Net Availability",heading_xf)
674
    sheet.write(0, 20, "Last Five Day Sale", heading_xf)
675
    sheet.write(0, 21, "Average Sale", heading_xf)
676
    sheet.write(0, 22, "Second Lowest Seller Inventory", heading_xf)
677
    sheet.write(0, 23, "Our NLC", heading_xf)
678
    sheet.write(0, 24, "Competition Basis", heading_xf)
679
    sheet.write(0, 25, "Target TP", heading_xf)
680
    sheet.write(0, 26, "Target SP", heading_xf)
681
    sheet.write(0, 27, "MARGIN INCREASED POTENTIAL", heading_xf)
682
 
683
    sheet_iterator = 1
684
    for item in buyBoxItems:
685
        snapdealDetails = item[0]
686
        snapdealItemInfo = item[1]
687
        snapdealPricing = item[2]
688
        mpItem = item[3]
689
        sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
690
        sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
691
        sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
692
        sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
693
        sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
694
        sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
695
        sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
696
        sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
697
        sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
698
        sheet.write(sheet_iterator, 9, snapdealPricing.ourSp)
699
        sheet.write(sheet_iterator, 10, snapdealDetails.ourOfferPrice)
700
        sheet.write(sheet_iterator, 11, snapdealPricing.ourTp)
701
        sheet.write(sheet_iterator, 12, snapdealDetails.rank)
702
        sheet.write(sheet_iterator, 13, snapdealDetails.lowestSellerName)
703
        sheet.write(sheet_iterator, 14, snapdealDetails.secondLowestSellerName)
704
        sheet.write(sheet_iterator, 15, snapdealDetails.secondLowestSellerSp)
705
        sheet.write(sheet_iterator, 16, snapdealDetails.secondLowestSellerOfferPrice)
706
        sheet.write(sheet_iterator, 17, snapdealPricing.secondLowestSellerTp)
707
        sheet.write(sheet_iterator, 18, snapdealDetails.ourInventory)
708
        if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
709
            sheet.write(sheet_iterator, 19, 'Info not available')
710
        else:
711
            sheet.write(sheet_iterator, 19, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
712
        sheet.write(sheet_iterator, 20, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
713
        sheet.write(sheet_iterator, 21, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
714
        sheet.write(sheet_iterator, 22, snapdealDetails.secondLowestSellerInventory)
715
        sheet.write(sheet_iterator, 23, snapdealItemInfo.nlc)
716
        sheet.write(sheet_iterator, 24, snapdealPricing.competitionBasis)
717
        if (snapdealPricing.competitionBasis=='SP'):
718
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)), snapdealPricing.lowestPossibleSp)
719
            proposed_tp = getTargetTp(proposed_sp,mpItem)
720
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
721
        else:
722
            proposed_tp  = max(snapdealPricing.secondLowestSellerTp - max((20, snapdealPricing.secondLowestSellerTp*0.002)), snapdealPricing.lowestPossibleTp)
10289 kshitij.so 723
            proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
9949 kshitij.so 724
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 725
        sheet.write(sheet_iterator, 25, round(proposed_tp,2))
726
        sheet.write(sheet_iterator, 26, round(proposed_sp,2))
727
        sheet.write(sheet_iterator, 27, round((proposed_tp - snapdealPricing.ourTp),2))
9949 kshitij.so 728
        sheet_iterator+=1
729
 
730
    sheet = wbk.add_sheet('Can Compete-With Inventory')
731
 
732
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
733
 
734
    excel_integer_format = '0'
735
    integer_style = xlwt.XFStyle()
736
    integer_style.num_format_str = excel_integer_format
737
    xstr = lambda s: s or ""
738
 
739
    sheet.write(0, 0, "Item ID", heading_xf)
740
    sheet.write(0, 1, "Category", heading_xf)
741
    sheet.write(0, 2, "Product Group.", heading_xf)
742
    sheet.write(0, 3, "SUPC", heading_xf)
743
    sheet.write(0, 4, "Brand", heading_xf)
744
    sheet.write(0, 5, "Product Name", heading_xf)
745
    sheet.write(0, 6, "Weight", heading_xf)
746
    sheet.write(0, 7, "Courier Cost", heading_xf)
747
    sheet.write(0, 8, "Risky", heading_xf)
748
    sheet.write(0, 9, "Our SP", heading_xf)
749
    sheet.write(0, 11, "Our TP", heading_xf)
750
    sheet.write(0, 10, "Our Offer Price", heading_xf)
751
    sheet.write(0, 12, "Our Rank", heading_xf)
752
    sheet.write(0, 13, "Lowest Seller", heading_xf)
753
    sheet.write(0, 14, "Lowest SP", heading_xf)
754
    sheet.write(0, 15, "Lowest TP", heading_xf)
755
    sheet.write(0, 16, "Lowest Offer Price", heading_xf)
756
    sheet.write(0, 17, "Inventory of Top Vendors", heading_xf)
757
    sheet.write(0, 18, "Our Snapdeal Inventory", heading_xf)
758
    sheet.write(0, 19, "Our Net Availability",heading_xf)
759
    sheet.write(0, 20, "Last Five Day Sale", heading_xf)
760
    sheet.write(0, 21, "Average Sale", heading_xf)
761
    sheet.write(0, 22, "Our NLC", heading_xf)
762
    sheet.write(0, 23, "Lowest Possible TP", heading_xf)
763
    sheet.write(0, 24, "Lowest Possible SP", heading_xf)
764
    sheet.write(0, 25, "Competition Basis ", heading_xf)
765
    sheet.write(0, 26, "Target TP", heading_xf)
766
    sheet.write(0, 27, "Target SP", heading_xf)  
767
    sheet.write(0, 28, "Sales Potential", heading_xf)
768
 
769
    sheet_iterator = 1
770
    for item in competitive:
771
        snapdealDetails = item[0]
772
        snapdealItemInfo = item[1]
773
        snapdealPricing = item[2]
774
        mpItem = item[3]
775
        sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
776
        sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
777
        sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
778
        sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
779
        sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
780
        sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
781
        sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
782
        sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
783
        sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
784
        sheet.write(sheet_iterator, 9, snapdealPricing.ourSp)
785
        sheet.write(sheet_iterator, 10, snapdealDetails.ourOfferPrice)
786
        sheet.write(sheet_iterator, 11, snapdealPricing.ourTp)
787
        sheet.write(sheet_iterator, 12, snapdealDetails.rank)
788
        sheet.write(sheet_iterator, 13, snapdealDetails.lowestSellerName)
789
        sheet.write(sheet_iterator, 14, snapdealDetails.lowestSp)
790
        sheet.write(sheet_iterator, 15, snapdealPricing.lowestTp)
791
        sheet.write(sheet_iterator, 16, snapdealDetails.lowestOfferPrice)
792
        sheet.write(sheet_iterator, 17, snapdealDetails.otherInventory)
793
        sheet.write(sheet_iterator, 18, snapdealDetails.ourInventory)
794
        if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
795
            sheet.write(sheet_iterator, 19, 'Info not available')
796
        else:
797
            sheet.write(sheet_iterator, 19, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
798
        sheet.write(sheet_iterator, 20, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
799
        sheet.write(sheet_iterator, 21, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
800
        sheet.write(sheet_iterator, 22, snapdealItemInfo.nlc)
801
        sheet.write(sheet_iterator, 23, snapdealPricing.lowestPossibleTp)
802
        sheet.write(sheet_iterator, 24, snapdealPricing.lowestPossibleSp)
803
        sheet.write(sheet_iterator, 25, snapdealPricing.competitionBasis)
804
        if (snapdealPricing.competitionBasis=='SP'):
805
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
806
            proposed_tp = getTargetTp(proposed_sp,mpItem)
807
        else:
808
            proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
10289 kshitij.so 809
            proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
9954 kshitij.so 810
        sheet.write(sheet_iterator, 26, round(proposed_tp,2))
811
        sheet.write(sheet_iterator, 27, round(proposed_sp,2))
9949 kshitij.so 812
        sheet.write(sheet_iterator, 28, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
813
        sheet_iterator+=1
814
 
815
    sheet = wbk.add_sheet('Negative Margin')
816
 
817
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
818
 
819
    excel_integer_format = '0'
820
    integer_style = xlwt.XFStyle()
821
    integer_style.num_format_str = excel_integer_format
822
    xstr = lambda s: s or ""
823
 
824
    sheet.write(0, 0, "Item ID", heading_xf)
825
    sheet.write(0, 1, "Category", heading_xf)
826
    sheet.write(0, 2, "Product Group.", heading_xf)
827
    sheet.write(0, 3, "SUPC", heading_xf)
828
    sheet.write(0, 4, "Brand", heading_xf)
829
    sheet.write(0, 5, "Product Name", heading_xf)
830
    sheet.write(0, 6, "Weight", heading_xf)
831
    sheet.write(0, 7, "Courier Cost", heading_xf)
832
    sheet.write(0, 8, "Risky", heading_xf)
833
    sheet.write(0, 9, "Our SP", heading_xf)
834
    sheet.write(0, 11, "Our TP", heading_xf)
835
    sheet.write(0, 12, "Lowest Possible TP", heading_xf)
836
    sheet.write(0, 10, "Our Offer Price", heading_xf)
837
    sheet.write(0, 13, "Our Rank", heading_xf)
838
    sheet.write(0, 14, "Our Snapdeal Inventory", heading_xf)
839
    sheet.write(0, 15, "Net Availability", heading_xf)
840
    sheet.write(0, 16, "Last Five Day Sale", heading_xf)
841
    sheet.write(0, 17, "Average Sale", heading_xf)
842
    sheet.write(0, 18, "Our NLC", heading_xf)
843
    sheet.write(0, 19, "Margin", heading_xf)
844
 
845
    sheet_iterator=1
846
    for item in negativeMargin:
847
        snapdealDetails = item[0]
848
        snapdealItemInfo = item[1]
849
        snapdealPricing = item[2]
850
        sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
851
        sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
852
        sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
853
        sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
854
        sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
855
        sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
856
        sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
857
        sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
858
        sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
859
        sheet.write(sheet_iterator, 9, snapdealPricing.ourSp)
860
        sheet.write(sheet_iterator, 10, snapdealDetails.ourOfferPrice)
861
        sheet.write(sheet_iterator, 11, snapdealPricing.ourTp)
862
        sheet.write(sheet_iterator, 12, snapdealPricing.lowestPossibleTp)
863
        sheet.write(sheet_iterator, 13, snapdealDetails.rank)
864
        sheet.write(sheet_iterator, 14, snapdealDetails.ourInventory)
865
        if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
866
            sheet.write(sheet_iterator, 15, 'Info not available')
867
        else:
868
            sheet.write(sheet_iterator, 15, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
869
        sheet.write(sheet_iterator, 16, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
870
        sheet.write(sheet_iterator, 17, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
871
        sheet.write(sheet_iterator, 18, snapdealItemInfo.nlc)
9954 kshitij.so 872
        sheet.write(sheet_iterator, 19, round((snapdealPricing.ourTp - snapdealPricing.lowestPossibleTp),2))
9949 kshitij.so 873
        sheet_iterator+=1
874
 
875
    sheet = wbk.add_sheet('Exception Item List')
876
 
877
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
878
 
879
    excel_integer_format = '0'
880
    integer_style = xlwt.XFStyle()
881
    integer_style.num_format_str = excel_integer_format
882
    xstr = lambda s: s or ""
883
 
884
    sheet.write(0, 0, "Item ID", heading_xf)
885
    sheet.write(0, 1, "Brand", heading_xf)
886
    sheet.write(0, 2, "Product Name", heading_xf)
887
    sheet.write(0, 3, "Reason", heading_xf)
888
    sheet_iterator=1
889
    for item in exceptionList:
890
        sheet.write(sheet_iterator, 0, item.item_id)
891
        sheet.write(sheet_iterator, 1, item.brand)
892
        sheet.write(sheet_iterator, 2, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
893
        sheet.write(sheet_iterator, 3, "Unable to fetch info from Snapdeal")
894
        sheet_iterator+=1
895
 
896
    sheet = wbk.add_sheet('Can Compete-No Inv')
897
 
898
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
899
 
900
    excel_integer_format = '0'
901
    integer_style = xlwt.XFStyle()
902
    integer_style.num_format_str = excel_integer_format
903
    xstr = lambda s: s or ""
904
 
905
    sheet.write(0, 0, "Item ID", heading_xf)
906
    sheet.write(0, 1, "Category", heading_xf)
907
    sheet.write(0, 2, "Product Group.", heading_xf)
908
    sheet.write(0, 3, "SUPC", heading_xf)
909
    sheet.write(0, 4, "Brand", heading_xf)
910
    sheet.write(0, 5, "Product Name", heading_xf)
911
    sheet.write(0, 6, "Weight", heading_xf)
912
    sheet.write(0, 7, "Courier Cost", heading_xf)
913
    sheet.write(0, 8, "Risky", heading_xf)
914
    sheet.write(0, 9, "Our SP", heading_xf)
915
    sheet.write(0, 11, "Our TP", heading_xf)
916
    sheet.write(0, 10, "Our Offer Price", heading_xf)
917
    sheet.write(0, 12, "Our Rank", heading_xf)
918
    sheet.write(0, 13, "Lowest Seller", heading_xf)
919
    sheet.write(0, 14, "Lowest SP", heading_xf)
920
    sheet.write(0, 15, "Lowest TP", heading_xf)
921
    sheet.write(0, 16, "Lowest Offer Price", heading_xf)
922
    sheet.write(0, 17, "Inventory of Top Vendors", heading_xf)
923
    sheet.write(0, 18, "Our Snapdeal Inventory", heading_xf)
924
    sheet.write(0, 19, "Our Net Availability",heading_xf)
925
    sheet.write(0, 20, "Last Five Day Sale", heading_xf)
926
    sheet.write(0, 21, "Average Sale", heading_xf)
927
    sheet.write(0, 22, "Our NLC", heading_xf)
928
    sheet.write(0, 23, "Lowest Possible TP", heading_xf)
929
    sheet.write(0, 24, "Lowest Possible SP", heading_xf)
930
    sheet.write(0, 25, "Competition Basis ", heading_xf)
931
    sheet.write(0, 26, "Target TP", heading_xf)
932
    sheet.write(0, 27, "Target SP", heading_xf)  
933
    sheet.write(0, 28, "Target NLC", heading_xf)
934
    sheet.write(0, 29, "Sales Potential", heading_xf)
935
 
936
    sheet_iterator = 1
937
    for item in competitiveNoInventory:
938
        snapdealDetails = item[0]
939
        snapdealItemInfo = item[1]
940
        snapdealPricing = item[2]
941
        mpItem = item[3]
942
        if ((not inventoryMap.has_key(snapdealItemInfo.item_id)) or getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id))<=0):
943
            sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
944
            sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
945
            sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
946
            sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
947
            sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
948
            sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
949
            sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
950
            sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
951
            sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
952
            sheet.write(sheet_iterator, 9, snapdealPricing.ourSp)
953
            sheet.write(sheet_iterator, 10, snapdealDetails.ourOfferPrice)
954
            sheet.write(sheet_iterator, 11, snapdealPricing.ourTp)
955
            sheet.write(sheet_iterator, 12, snapdealDetails.rank)
956
            sheet.write(sheet_iterator, 13, snapdealDetails.lowestSellerName)
957
            sheet.write(sheet_iterator, 14, snapdealDetails.lowestSp)
958
            sheet.write(sheet_iterator, 15, snapdealPricing.lowestTp)
959
            sheet.write(sheet_iterator, 16, snapdealDetails.lowestOfferPrice)
960
            sheet.write(sheet_iterator, 17, snapdealDetails.otherInventory)
961
            sheet.write(sheet_iterator, 18, snapdealDetails.ourInventory)
962
            if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
963
                sheet.write(sheet_iterator, 19, 'Info not available')
964
            else:
965
                sheet.write(sheet_iterator, 19, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
966
            sheet.write(sheet_iterator, 20, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
967
            sheet.write(sheet_iterator, 21, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
968
            sheet.write(sheet_iterator, 22, snapdealItemInfo.nlc)
969
            sheet.write(sheet_iterator, 23, snapdealPricing.lowestPossibleTp)
970
            sheet.write(sheet_iterator, 24, snapdealPricing.lowestPossibleSp)
971
            sheet.write(sheet_iterator, 25, snapdealPricing.competitionBasis)
972
            if (snapdealPricing.competitionBasis=='SP'):
973
                proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
974
                proposed_tp = getTargetTp(proposed_sp,mpItem)
975
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
976
            else:
977
                proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
10289 kshitij.so 978
                proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
9949 kshitij.so 979
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 980
            sheet.write(sheet_iterator, 26, round(proposed_tp,2))
981
            sheet.write(sheet_iterator, 27, round(proposed_sp,2))
982
            sheet.write(sheet_iterator, 28, round(target_nlc,2))
9949 kshitij.so 983
            sheet.write(sheet_iterator, 29, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
984
            sheet_iterator+=1
985
 
986
    sheet = wbk.add_sheet('Can Compete-No Inv On SD')
987
 
988
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
989
 
990
    excel_integer_format = '0'
991
    integer_style = xlwt.XFStyle()
992
    integer_style.num_format_str = excel_integer_format
993
    xstr = lambda s: s or ""
994
 
995
    sheet.write(0, 0, "Item ID", heading_xf)
996
    sheet.write(0, 1, "Category", heading_xf)
997
    sheet.write(0, 2, "Product Group.", heading_xf)
998
    sheet.write(0, 3, "SUPC", heading_xf)
999
    sheet.write(0, 4, "Brand", heading_xf)
1000
    sheet.write(0, 5, "Product Name", heading_xf)
1001
    sheet.write(0, 6, "Weight", heading_xf)
1002
    sheet.write(0, 7, "Courier Cost", heading_xf)
1003
    sheet.write(0, 8, "Risky", heading_xf)
1004
    sheet.write(0, 9, "Our SP", heading_xf)
1005
    sheet.write(0, 11, "Our TP", heading_xf)
1006
    sheet.write(0, 10, "Our Offer Price", heading_xf)
1007
    sheet.write(0, 12, "Our Rank", heading_xf)
1008
    sheet.write(0, 13, "Lowest Seller", heading_xf)
1009
    sheet.write(0, 14, "Lowest SP", heading_xf)
1010
    sheet.write(0, 15, "Lowest TP", heading_xf)
1011
    sheet.write(0, 16, "Lowest Offer Price", heading_xf)
1012
    sheet.write(0, 17, "Inventory of Top Vendors", heading_xf)
1013
    sheet.write(0, 18, "Our Snapdeal Inventory", heading_xf)
1014
    sheet.write(0, 19, "Our Net Availability",heading_xf)
1015
    sheet.write(0, 20, "Last Five Day Sale", heading_xf)
1016
    sheet.write(0, 21, "Average Sale", heading_xf)
1017
    sheet.write(0, 22, "Our NLC", heading_xf)
1018
    sheet.write(0, 23, "Lowest Possible TP", heading_xf)
1019
    sheet.write(0, 24, "Lowest Possible SP", heading_xf)
1020
    sheet.write(0, 25, "Competition Basis ", heading_xf)
1021
    sheet.write(0, 26, "Target TP", heading_xf)
1022
    sheet.write(0, 27, "Target SP", heading_xf)  
1023
    sheet.write(0, 28, "Target NLC", heading_xf)
1024
    sheet.write(0, 29, "Sales Potential", heading_xf)
1025
 
1026
    sheet_iterator = 1
1027
    for item in competitiveNoInventory:
1028
        snapdealDetails = item[0]
1029
        snapdealItemInfo = item[1]
1030
        snapdealPricing = item[2]
1031
        mpItem = item[3]
1032
        if (inventoryMap.has_key(snapdealItemInfo.item_id) and getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id))>0):
1033
            sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
1034
            sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
1035
            sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
1036
            sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
1037
            sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
1038
            sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
1039
            sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
1040
            sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
1041
            sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
1042
            sheet.write(sheet_iterator, 9, snapdealPricing.ourSp)
1043
            sheet.write(sheet_iterator, 10, snapdealDetails.ourOfferPrice)
1044
            sheet.write(sheet_iterator, 11, snapdealPricing.ourTp)
1045
            sheet.write(sheet_iterator, 12, snapdealDetails.rank)
1046
            sheet.write(sheet_iterator, 13, snapdealDetails.lowestSellerName)
1047
            sheet.write(sheet_iterator, 14, snapdealDetails.lowestSp)
1048
            sheet.write(sheet_iterator, 15, snapdealPricing.lowestTp)
1049
            sheet.write(sheet_iterator, 16, snapdealDetails.lowestOfferPrice)
1050
            sheet.write(sheet_iterator, 17, snapdealDetails.otherInventory)
1051
            sheet.write(sheet_iterator, 18, snapdealDetails.ourInventory)
1052
            if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
1053
                sheet.write(sheet_iterator, 19, 'Info not available')
1054
            else:
1055
                sheet.write(sheet_iterator, 19, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
1056
            sheet.write(sheet_iterator, 20, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
1057
            sheet.write(sheet_iterator, 21, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
1058
            sheet.write(sheet_iterator, 22, snapdealItemInfo.nlc)
1059
            sheet.write(sheet_iterator, 23, snapdealPricing.lowestPossibleTp)
1060
            sheet.write(sheet_iterator, 24, snapdealPricing.lowestPossibleSp)
1061
            sheet.write(sheet_iterator, 25, snapdealPricing.competitionBasis)
1062
            if (snapdealPricing.competitionBasis=='SP'):
1063
                proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
1064
                proposed_tp = getTargetTp(proposed_sp,mpItem)
1065
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
1066
            else:
1067
                proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
10289 kshitij.so 1068
                proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
9949 kshitij.so 1069
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1070
            sheet.write(sheet_iterator, 26, round(proposed_tp,2))
1071
            sheet.write(sheet_iterator, 27, round(proposed_sp,2))
1072
            sheet.write(sheet_iterator, 28, round(target_nlc,2))
9949 kshitij.so 1073
            sheet.write(sheet_iterator, 29, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
1074
            sheet_iterator+=1
9953 kshitij.so 1075
 
1076
    if (runType=='FULL'):    
1077
        sheet = wbk.add_sheet('Auto Favorites')
1078
 
1079
        heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1080
 
1081
        excel_integer_format = '0'
1082
        integer_style = xlwt.XFStyle()
1083
        integer_style.num_format_str = excel_integer_format
1084
        xstr = lambda s: s or ""
1085
 
1086
        sheet.write(0, 0, "Item ID", heading_xf)
1087
        sheet.write(0, 1, "Brand", heading_xf)
1088
        sheet.write(0, 2, "Product Name", heading_xf)
1089
        sheet.write(0, 3, "Auto Favourite", heading_xf)
1090
        sheet.write(0, 4, "Reason", heading_xf)
1091
 
1092
        sheet_iterator=1
1093
        for autoFav in nowAutoFav:
1094
            itemId = autoFav[0]
1095
            reason = autoFav[1]
1096
            it = Item.query.filter_by(id=itemId).one()
1097
            sheet.write(sheet_iterator, 0, itemId)
1098
            sheet.write(sheet_iterator, 1, it.brand)
1099
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1100
            sheet.write(sheet_iterator, 3, "True")
1101
            sheet.write(sheet_iterator, 4, reason)
1102
            sheet_iterator+=1
1103
        for prevFav in previousAutoFav:
1104
            it = Item.query.filter_by(id=prevFav).one()
1105
            sheet.write(sheet_iterator, 0, prevFav)
1106
            sheet.write(sheet_iterator, 1, it.brand)
1107
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1108
            sheet.write(sheet_iterator, 3, "False")
1109
            sheet_iterator+=1
9949 kshitij.so 1110
 
1111
 
1112
    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()
1113
    sheet = wbk.add_sheet('Auto Inc and Dec')
1114
 
1115
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1116
 
1117
    excel_integer_format = '0'
1118
    integer_style = xlwt.XFStyle()
1119
    integer_style.num_format_str = excel_integer_format
1120
    xstr = lambda s: s or ""
1121
 
1122
    sheet.write(0, 0, "Item ID", heading_xf)
1123
    sheet.write(0, 1, "Brand", heading_xf)
1124
    sheet.write(0, 2, "Product Name", heading_xf)
1125
    sheet.write(0, 3, "Decision", heading_xf)
1126
    sheet.write(0, 4, "Reason", heading_xf)
9954 kshitij.so 1127
    sheet.write(0, 5, "Old Selling Price", heading_xf)
1128
    sheet.write(0, 6, "Selling Price Updated",heading_xf)
9949 kshitij.so 1129
 
1130
    sheet_iterator=1
1131
    for autoPricingItem in autoPricingItems:
1132
        mpHistory = autoPricingItem[0]
1133
        item = autoPricingItem[1]
9954 kshitij.so 1134
        it = Item.query.filter_by(id=item.id).one()
9949 kshitij.so 1135
        sheet.write(sheet_iterator, 0, item.id)
1136
        sheet.write(sheet_iterator, 1, it.brand)
1137
        sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1138
        sheet.write(sheet_iterator, 3, Decision._VALUES_TO_NAMES.get(mpHistory.decision))
1139
        sheet.write(sheet_iterator, 4, mpHistory.reason)
1140
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_DECREMENT_SUCCESS":
9954 kshitij.so 1141
            sheet.write(sheet_iterator, 5, mpHistory.ourSellingPrice)
1142
            sheet.write(sheet_iterator, 6, math.ceil(mpHistory.proposedSellingPrice))
9949 kshitij.so 1143
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_INCREMENT_SUCCESS":
9954 kshitij.so 1144
            sheet.write(sheet_iterator, 5, mpHistory.ourSellingPrice)
1145
            sheet.write(sheet_iterator, 6, math.ceil(mpHistory.ourSellingPrice+max(10,.01*mpHistory.ourSellingPrice)))
9949 kshitij.so 1146
        sheet_iterator+=1
1147
 
9953 kshitij.so 1148
    filename = "/tmp/snapdeal-report-"+runType+" " + str(timestamp) + ".xls"
9949 kshitij.so 1149
    wbk.save(filename)
10207 kshitij.so 1150
    try:
10293 kshitij.so 1151
        #EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["kshitij.sood@saholic.com"], " Snapdeal Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], [""], [])
1152
        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 1153
    except Exception as e:
1154
        print e
10219 kshitij.so 1155
        print "Unable to send report.Trying with local SMTP"
1156
        smtpServer = smtplib.SMTP('localhost')
1157
        smtpServer.set_debuglevel(1)
1158
        sender = 'support@shop2020.in'
10293 kshitij.so 1159
        #recipients = ['kshitij.sood@saholic.com']
10219 kshitij.so 1160
        msg = MIMEMultipart()
1161
        msg['Subject'] = "Snapdeal Auto Pricing" + ' - ' + str(datetime.now())
1162
        msg['From'] = sender
10293 kshitij.so 1163
        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 1164
        msg['To'] = ",".join(recipients)
10219 kshitij.so 1165
        fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
1166
        fileMsg.set_payload(file(filename).read())
1167
        email.encoders.encode_base64(fileMsg)
1168
        fileMsg.add_header('Content-Disposition','attachment;filename=snapdeal.xls')
1169
        msg.attach(fileMsg)
1170
        try:
1171
            smtpServer.sendmail(sender, recipients, msg.as_string())
1172
            print "Successfully sent email"
1173
        except:
1174
            print "Error: unable to send email."
9881 kshitij.so 1175
 
10219 kshitij.so 1176
 
9881 kshitij.so 1177
def commitExceptionList(exceptionList,timestamp):
9949 kshitij.so 1178
    exceptionItems=[]
9881 kshitij.so 1179
    for item in exceptionList:
1180
        mpHistory = MarketPlaceHistory()
1181
        mpHistory.item_id =item.item_id
1182
        mpHistory.source = OrderSource.SNAPDEAL 
1183
        mpHistory.competitiveCategory = CompetitionCategory.EXCEPTION
1184
        mpHistory.risky = item.risky
1185
        mpHistory.timestamp = timestamp
9949 kshitij.so 1186
        mpHistory.run = RunType._NAMES_TO_VALUES.get(item.runType)
1187
        exceptionItems.append(mpHistory)
9881 kshitij.so 1188
    session.commit()
9949 kshitij.so 1189
    return exceptionItems
9881 kshitij.so 1190
 
1191
def commitNegativeMargin(negativeMargin,timestamp):
9949 kshitij.so 1192
    negativeMarginItems = []
9881 kshitij.so 1193
    for item in negativeMargin:
1194
        snapdealDetails = item[0]
1195
        snapdealItemInfo = item[1]
1196
        snapdealPricing = item[2]
1197
        mpHistory = MarketPlaceHistory()
1198
        mpHistory.item_id = snapdealItemInfo.item_id
1199
        mpHistory.source = OrderSource.SNAPDEAL
1200
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1201
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1202
        mpHistory.ourTp = snapdealPricing.ourTp
9919 kshitij.so 1203
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
9881 kshitij.so 1204
        mpHistory.ourNlc = snapdealItemInfo.nlc
1205
        mpHistory.ourInventory = snapdealDetails.ourInventory
1206
        mpHistory.otherInventory = snapdealDetails.otherInventory
1207
        mpHistory.ourRank = snapdealDetails.rank
9919 kshitij.so 1208
        mpHistory.risky = snapdealItemInfo.risky
1209
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp  
9881 kshitij.so 1210
        mpHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
1211
        mpHistory.totalSeller = snapdealDetails.totalSeller
9949 kshitij.so 1212
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[2]
9881 kshitij.so 1213
        mpHistory.timestamp = timestamp
9949 kshitij.so 1214
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1215
        negativeMarginItems.append(mpHistory) 
9881 kshitij.so 1216
    session.commit()
9949 kshitij.so 1217
    return negativeMarginItems
9881 kshitij.so 1218
 
1219
def commitCompetitive(competitive,timestamp):
9949 kshitij.so 1220
    competitiveItems = []
9881 kshitij.so 1221
    for item in competitive:
1222
        snapdealDetails = item[0]
1223
        snapdealItemInfo = item[1]
1224
        snapdealPricing = item[2]
1225
        mpItem = item[3]
1226
        mpHistory = MarketPlaceHistory()
1227
        mpHistory.item_id = snapdealItemInfo.item_id
1228
        mpHistory.source = OrderSource.SNAPDEAL
1229
        mpHistory.lowestTp = snapdealPricing.lowestTp
1230
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1231
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1232
        mpHistory.ourInventory = snapdealDetails.ourInventory
1233
        mpHistory.otherInventory = snapdealDetails.otherInventory
1234
        mpHistory.ourRank = snapdealDetails.rank
1235
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1236
        mpHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
1237
        mpHistory.risky = snapdealItemInfo.risky
1238
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1239
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1240
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1241
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1242
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1243
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1244
        mpHistory.ourTp = snapdealPricing.ourTp
1245
        mpHistory.ourNlc = snapdealItemInfo.nlc
1246
        if (snapdealPricing.competitionBasis=='SP'):
1247
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
1248
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9954 kshitij.so 1249
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1250
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1251
        else:
1252
            proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
10289 kshitij.so 1253
            proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
9954 kshitij.so 1254
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1255
            mpHistory.proposedTp = round(proposed_tp,2)
9919 kshitij.so 1256
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1257
        mpHistory.totalSeller = snapdealDetails.totalSeller
9949 kshitij.so 1258
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[2]
9881 kshitij.so 1259
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
1260
        mpHistory.timestamp = timestamp
9949 kshitij.so 1261
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1262
        competitiveItems.append(mpHistory) 
9881 kshitij.so 1263
    session.commit()
9949 kshitij.so 1264
    return competitiveItems
9881 kshitij.so 1265
 
1266
def commitCompetitiveNoInventory(competitiveNoInventory,timestamp):
9949 kshitij.so 1267
    competitiveNoInventoryItems = []
9881 kshitij.so 1268
    for item in competitiveNoInventory:
1269
        snapdealDetails = item[0]
1270
        snapdealItemInfo = item[1]
1271
        snapdealPricing = item[2]
1272
        mpItem = item[3]
1273
        mpHistory = MarketPlaceHistory()
1274
        mpHistory.item_id = snapdealItemInfo.item_id
1275
        mpHistory.source = OrderSource.SNAPDEAL
1276
        mpHistory.lowestTp = snapdealPricing.lowestTp
1277
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1278
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1279
        mpHistory.ourInventory = snapdealDetails.ourInventory
1280
        mpHistory.otherInventory = snapdealDetails.otherInventory
1281
        mpHistory.ourRank = snapdealDetails.rank
1282
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1283
        mpHistory.competitiveCategory = CompetitionCategory.COMPETITIVE_NO_INVENTORY
1284
        mpHistory.risky = snapdealItemInfo.risky
1285
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1286
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1287
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1288
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1289
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1290
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1291
        mpHistory.ourTp = snapdealPricing.ourTp
1292
        mpHistory.ourNlc = snapdealItemInfo.nlc
1293
        if (snapdealPricing.competitionBasis=='SP'):
1294
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
1295
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9954 kshitij.so 1296
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1297
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1298
        else:
1299
            proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
10289 kshitij.so 1300
            proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
9954 kshitij.so 1301
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1302
            mpHistory.proposedTp = round(proposed_tp,2)
9919 kshitij.so 1303
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1304
        mpHistory.totalSeller = snapdealDetails.totalSeller
9949 kshitij.so 1305
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[2]
9881 kshitij.so 1306
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
1307
        mpHistory.timestamp = timestamp
9949 kshitij.so 1308
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1309
        competitiveNoInventoryItems.append(mpHistory)
9881 kshitij.so 1310
    session.commit()
9949 kshitij.so 1311
    return competitiveNoInventoryItems
9881 kshitij.so 1312
 
1313
def commitCantCompete(cantCompete,timestamp):
9949 kshitij.so 1314
    cantComepeteItems = []
9881 kshitij.so 1315
    for item in cantCompete:
1316
        snapdealDetails = item[0]
1317
        snapdealItemInfo = item[1]
1318
        snapdealPricing = item[2]
1319
        mpItem = item[3]
1320
        mpHistory = MarketPlaceHistory()
1321
        mpHistory.item_id = snapdealItemInfo.item_id
1322
        mpHistory.source = OrderSource.SNAPDEAL
1323
        mpHistory.lowestTp = snapdealPricing.lowestTp
1324
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1325
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1326
        mpHistory.ourInventory = snapdealDetails.ourInventory
1327
        mpHistory.otherInventory = snapdealDetails.otherInventory
1328
        mpHistory.ourRank = snapdealDetails.rank
1329
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1330
        mpHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
1331
        mpHistory.risky = snapdealItemInfo.risky
1332
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1333
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1334
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1335
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1336
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1337
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1338
        mpHistory.ourTp = snapdealPricing.ourTp
1339
        mpHistory.ourNlc = snapdealItemInfo.nlc
1340
        if (snapdealPricing.competitionBasis=='SP'):
1341
            proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
1342
            proposed_tp = getTargetTp(proposed_sp,mpItem)
1343
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1344
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1345
            mpHistory.proposedTp = round(proposed_tp,2)
1346
            mpHistory.targetNlc = round(target_nlc,2)
9881 kshitij.so 1347
        else:
1348
            proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
10289 kshitij.so 1349
            proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
9881 kshitij.so 1350
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1351
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1352
            mpHistory.proposedTp = round(proposed_tp,2)
1353
            mpHistory.targetNlc = round(target_nlc,2)
9919 kshitij.so 1354
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1355
        mpHistory.totalSeller = snapdealDetails.totalSeller
9949 kshitij.so 1356
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[2]
9881 kshitij.so 1357
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
1358
        mpHistory.timestamp = timestamp
9949 kshitij.so 1359
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1360
        cantComepeteItems.append(mpHistory)
9881 kshitij.so 1361
    session.commit()
9949 kshitij.so 1362
    return cantComepeteItems
9881 kshitij.so 1363
 
1364
def commitBuyBox(buyBoxItems,timestamp):
9949 kshitij.so 1365
    buyBoxList = []
9881 kshitij.so 1366
    for item in buyBoxItems:
1367
        snapdealDetails = item[0]
1368
        snapdealItemInfo = item[1]
1369
        snapdealPricing = item[2]
1370
        mpItem = item[3]
1371
        mpHistory = MarketPlaceHistory()
1372
        mpHistory.item_id = snapdealItemInfo.item_id
1373
        mpHistory.source = OrderSource.SNAPDEAL
1374
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1375
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1376
        mpHistory.ourInventory = snapdealDetails.ourInventory
1377
        mpHistory.secondLowestInventory = snapdealDetails.secondLowestSellerInventory
1378
        mpHistory.ourRank = snapdealDetails.rank
1379
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1380
        mpHistory.competitiveCategory = CompetitionCategory.BUY_BOX
1381
        mpHistory.risky = snapdealItemInfo.risky
1382
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1383
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1384
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1385
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1386
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1387
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1388
        mpHistory.ourTp = snapdealPricing.ourTp
1389
        mpHistory.ourNlc = snapdealItemInfo.nlc
1390
        mpHistory.secondLowestSellerName = snapdealDetails.secondLowestSellerName
1391
        mpHistory.secondLowestSellerCode = snapdealDetails.secondLowestSellerCode
9885 kshitij.so 1392
        mpHistory.secondLowestSellingPrice = snapdealDetails.secondLowestSellerSp
9888 kshitij.so 1393
        mpHistory.secondLowestOfferPrice = snapdealDetails.secondLowestSellerOfferPrice
9881 kshitij.so 1394
        mpHistory.secondLowestTp = snapdealPricing.secondLowestSellerTp
1395
        if (snapdealPricing.competitionBasis=='SP'):
1396
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)), snapdealPricing.lowestPossibleSp)
1397
            proposed_tp = getTargetTp(proposed_sp,mpItem)
1398
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1399
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1400
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1401
            #mpHistory.targetNlc = target_nlc
1402
        else:
1403
            proposed_tp  = max(snapdealPricing.secondLowestSellerTp - max((20, snapdealPricing.secondLowestSellerTp*0.002)), snapdealPricing.lowestPossibleTp)
10289 kshitij.so 1404
            proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
9881 kshitij.so 1405
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1406
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1407
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1408
            #mpHistory.targetNlc = target_nlc
9919 kshitij.so 1409
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1410
        mpHistory.marginIncreasedPotential = proposed_tp - snapdealPricing.ourTp
1411
        mpHistory.totalSeller = snapdealDetails.totalSeller
9949 kshitij.so 1412
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[2]
9881 kshitij.so 1413
        mpHistory.timestamp = timestamp
9949 kshitij.so 1414
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1415
        buyBoxList.append(mpHistory)
9881 kshitij.so 1416
    session.commit()
9949 kshitij.so 1417
    return buyBoxList 
10219 kshitij.so 1418
 
9990 kshitij.so 1419
def sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease):
1420
    xstr = lambda s: s or ""
1421
    catalog_client = CatalogClient().get_client()
1422
    inventory_client = InventoryClient().get_client()
1423
    message="""<html>
1424
            <body>
1425
            <h3>Auto Decrease Items</h3>
1426
            <table border="1" style="width:100%;">
1427
            <thead>
1428
            <tr><th>Item Id</th>
1429
            <th>Product Name</th>
1430
            <th>Old Price</th>
1431
            <th>New Price</th>
1432
            <th>Old Margin</th>
1433
            <th>New Margin</th>
1434
            <th>Snapdeal Inventory</th>
1435
            </tr></thead>
1436
            <tbody>"""
1437
    for item in successfulAutoDecrease:
1438
        it = Item.query.filter_by(id=item.item_id).one()
1439
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1440
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1441
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1442
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, item.proposedSellingPrice)
1443
        newMargin = round(getNewOurTp(mpItem,item.proposedSellingPrice) - getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,item.proposedSellingPrice))  
1444
        message+="""<tr>
1445
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
1446
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
1447
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
1448
                <td style="text-align:center">"""+str(math.ceil(item.proposedSellingPrice))+"""</td>
1449
                <td style="text-align:center">"""+str(round(item.margin))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
1450
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/item.proposedSellingPrice)*100,1))+"%)"+"""</td>
1451
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
1452
                </tr>"""
1453
    message+="""</tbody></table><h3>Auto Increase Items</h3><table border="1" style="width:100%;">
1454
            <thead>
1455
            <tr><th>Item Id</th>
1456
            <th>Product Name</th>
1457
            <th>Old Price</th>
1458
            <th>New Price</th>
1459
            <th>Old Margin</th>
1460
            <th>New Margin</th>
1461
            <th>Snapdeal Inventory</th>
1462
            </tr></thead>
1463
            <tbody>"""
1464
    for item in successfulAutoIncrease:
1465
        it = Item.query.filter_by(id=item.item_id).one()
1466
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1467
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1468
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1469
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
1470
        newMargin = round(getNewOurTp(mpItem,item.ourSellingPrice+max(10,.01*item.ourSellingPrice)) - getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))  
1471
        message+="""<tr>
1472
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
1473
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
1474
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
1475
                <td style="text-align:center">"""+str(math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))+"""</td>
1476
                <td style="text-align:center">"""+str(round((item.margin),1))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
1477
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))*100,1))+"%)"+"""</td>
1478
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
1479
                </tr>"""
1480
    message+="""</tbody></table></body></html>"""
1481
    print message
1482
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
1483
    mailServer.ehlo()
1484
    mailServer.starttls()
1485
    mailServer.ehlo()
1486
 
10293 kshitij.so 1487
    #recipients = ['kshitij.sood@saholic.com']
1488
    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 1489
    msg = MIMEMultipart()
1490
    msg['Subject'] = "Snapdeal Auto Pricing" + ' - ' + str(datetime.now())
1491
    msg['From'] = ""
10005 kshitij.so 1492
    msg['To'] = ",".join(recipients)
9990 kshitij.so 1493
    msg.preamble = "Snapdeal Auto Pricing" + ' - ' + str(datetime.now())
1494
    html_msg = MIMEText(message, 'html')
1495
    msg.attach(html_msg)
10207 kshitij.so 1496
    try:
1497
        mailServer.login("build@shop2020.in", "cafe@nes")
1498
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
1499
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
1500
    except Exception as e:
1501
        print e
10219 kshitij.so 1502
        print "Unable to send pricing mail.Lets try with local SMTP."
1503
        smtpServer = smtplib.SMTP('localhost')
1504
        smtpServer.set_debuglevel(1)
1505
        sender = 'support@shop2020.in'
1506
        try:
1507
            smtpServer.sendmail(sender, recipients, msg.as_string())
1508
            print "Successfully sent email"
1509
        except:
1510
            print "Error: unable to send email."
1511
 
9990 kshitij.so 1512
 
1513
def commitPricing(successfulAutoDecrease,successfulAutoIncrease,timestamp):
1514
    catalog_client = CatalogClient().get_client()
1515
    inventory_client = InventoryClient().get_client()
1516
    for item in successfulAutoDecrease:
1517
        it = Item.query.filter_by(id=item.item_id).one()
1518
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1519
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1520
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1521
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, item.proposedSellingPrice)
1522
        addHistory(sdItem)
1523
        sdItem.transferPrice = getNewOurTp(mpItem,item.proposedSellingPrice)
1524
        sdItem.sellingPrice = math.ceil(item.proposedSellingPrice)
10293 kshitij.so 1525
        if ((mpItem.pgFee/100)*sdItem.sellingPrice)>=20:
1526
            sdItem.commission = round((mpItem.commission/100+mpItem.pgFee/100)*(sdItem.sellingPrice),2)
1527
        else:
1528
            sdItem.commission = round((mpItem.commission/100)*(sdItem.sellingPrice),2)+20
9990 kshitij.so 1529
        sdItem.serviceTax = round((mpItem.serviceTax/100)*(sdItem.commission+sdItem.courierCost),2)
1530
        sdItem.updatedOn = timestamp
1531
        sdItem.priceUpdatedBy = 'SYSTEM'
1532
        mpItem.currentSp = sdItem.sellingPrice
1533
        mpItem.currentTp = sdItem.transferPrice
1534
        mpItem.minimumPossibleTp = getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,item.proposedSellingPrice) 
1535
        mpItem.minimumPossibleSp = getNewLowestPossibleSp(mpItem,item.ourNlc,vatRate)
1536
        markStatusForMarketplaceItems(sdItem,mpItem)
1537
    session.commit()
1538
    for item in successfulAutoIncrease:
1539
        it = Item.query.filter_by(id=item.item_id).one()
1540
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1541
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1542
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1543
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
1544
        addHistory(sdItem)
1545
        sdItem.transferPrice = getNewOurTp(mpItem,item.ourSellingPrice+max(10,.01*item.ourSellingPrice))
1546
        sdItem.sellingPrice = math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice))
10293 kshitij.so 1547
        if ((mpItem.pgFee/100)*sdItem.sellingPrice)>=20:
1548
            sdItem.commission = round((mpItem.commission/100+mpItem.pgFee/100)*(sdItem.sellingPrice),2)
1549
        else:
1550
            sdItem.commission = round((mpItem.commission/100)*(sdItem.sellingPrice),2)+20
9990 kshitij.so 1551
        sdItem.serviceTax = round((mpItem.serviceTax/100)*(sdItem.commission+sdItem.courierCost),2)
1552
        sdItem.updatedOn = timestamp
1553
        sdItem.priceUpdatedBy = 'SYSTEM'
1554
        mpItem.currentSp = sdItem.sellingPrice
1555
        mpItem.currentTp = sdItem.transferPrice
1556
        mpItem.minimumPossibleTp = getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,sdItem.sellingPrice) 
1557
        mpItem.minimumPossibleSp = getNewLowestPossibleSp(mpItem,item.ourNlc,vatRate)
1558
        markStatusForMarketplaceItems(sdItem,mpItem)
1559
    session.commit()
1560
 
10280 kshitij.so 1561
def updatePricesOnSnapdeal(successfulAutoDecrease,successfulAutoIncrease):
10284 kshitij.so 1562
    if syncPrice=='false':
10280 kshitij.so 1563
        return
1564
    url = 'http://support.shop2020.in:8080/Support/reports'
1565
    br = getBrowserObject()
1566
    br.open(url)
1567
    br.open(url)
1568
    br.select_form(nr=0)
10286 kshitij.so 1569
    br.form['username'] = "manoj"
1570
    br.form['password'] = "man0j"
10280 kshitij.so 1571
    br.submit()
1572
    for item in successfulAutoDecrease:
1573
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1574
        sellingPrice =  str(math.ceil(item.proposedSellingPrice))
1575
        supc = sdItem.supc
10286 kshitij.so 1576
        updateUrl = 'http://support.shop2020.in:8080/Support/snapdeal-list!updateForAutoPricing?sellingPrice=%s&supc=%s&itemId=%s'%(sellingPrice,supc,str(item.item_id))
1577
        br.open(updateUrl)
10280 kshitij.so 1578
    for item in successfulAutoIncrease:
1579
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1580
        sellingPrice =  str(math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
1581
        supc = sdItem.supc
1582
        updateUrl = 'http://support.shop2020.in:8080/Support/snapdeal-list!updateForAutoPricing?sellingPrice=%s&supc=%s&itemId=%s'%(sellingPrice,supc,str(item.item_id))
1583
        br.open(updateUrl)
1584
 
1585
 
1586
 
9990 kshitij.so 1587
def addHistory(item):
10097 kshitij.so 1588
    itemHistory = MarketPlaceUpdateHistory()
9990 kshitij.so 1589
    itemHistory.item_id = item.item_id
10097 kshitij.so 1590
    itemHistory.source = OrderSource.SNAPDEAL
9990 kshitij.so 1591
    itemHistory.exceptionPrice = item.exceptionPrice
1592
    itemHistory.warehouseId = item.warehouseId
10097 kshitij.so 1593
    itemHistory.isListedOnSource = item.isListedOnSnapdeal
9990 kshitij.so 1594
    itemHistory.transferPrice = item.transferPrice
1595
    itemHistory.sellingPrice = item.sellingPrice
1596
    itemHistory.courierCost = item.courierCost
1597
    itemHistory.commission = item.commission
1598
    itemHistory.serviceTax = item.serviceTax
1599
    itemHistory.suppressPriceFeed = item.suppressPriceFeed
1600
    itemHistory.suppressInventoryFeed = item.suppressInventoryFeed
1601
    itemHistory.updatedOn = item.updatedOn
1602
    itemHistory.maxNlc = item.maxNlc
10097 kshitij.so 1603
    itemHistory.skuAtSource = item.skuAtSnapdeal
1604
    itemHistory.marketPlaceSerialNumber = item.supc
9990 kshitij.so 1605
    itemHistory.priceUpdatedBy = item.priceUpdatedBy
1606
 
1607
def markStatusForMarketplaceItems(snapdealItem,marketplaceItem):
1608
    markUpdatedItem = MarketPlaceItemPrice.query.filter(MarketPlaceItemPrice.item_id==snapdealItem.item_id).filter(MarketPlaceItemPrice.source==marketplaceItem.source).first()
1609
    if markUpdatedItem is None:
1610
        marketPlaceItemPrice = MarketPlaceItemPrice()
1611
        marketPlaceItemPrice.item_id = snapdealItem.item_id
1612
        marketPlaceItemPrice.source = marketplaceItem.source
1613
        marketPlaceItemPrice.lastUpdatedOn = snapdealItem.updatedOn
1614
        marketPlaceItemPrice.sellingPrice = snapdealItem.sellingPrice 
1615
        marketPlaceItemPrice.suppressPriceFeed = snapdealItem.suppressPriceFeed
1616
        marketPlaceItemPrice.isListedOnSource = snapdealItem.isListedOnSnapdeal
1617
    else:
1618
        if (markUpdatedItem.sellingPrice!=snapdealItem.sellingPrice or markUpdatedItem.suppressPriceFeed!=snapdealItem.suppressPriceFeed or markUpdatedItem.isListedOnSource!=snapdealItem.isListedOnSnapdeal):
1619
            markUpdatedItem.lastUpdatedOn = snapdealItem.updatedOn
1620
        markUpdatedItem.sellingPrice = snapdealItem.sellingPrice
1621
        markUpdatedItem.suppressPriceFeed = snapdealItem.suppressPriceFeed
1622
        markUpdatedItem.isListedOnSource = snapdealItem.isListedOnSnapdeal
10031 kshitij.so 1623
 
1624
def processLostBuyBoxItems(previousProcessingTimestamp,currentTimestamp):
1625
    previous_buy_box = session.query(MarketPlaceHistory.item_id).filter(MarketPlaceHistory.timestamp==previousProcessingTimestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.BUY_BOX).all()
1626
    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 1627
    lost_buy_box = list(set(list(zip(*previous_buy_box)[0]))&set(list(zip(*cant_compete)[0])))
10031 kshitij.so 1628
    if len(lost_buy_box)==0:
1629
        return
1630
    xstr = lambda s: s or ""
1631
    message="""<html>
1632
            <body>
1633
            <h3>Lost Buy Box</h3>
1634
            <table border="1" style="width:100%;">
1635
            <thead>
1636
            <tr><th>Item Id</th>
1637
            <th>Product Name</th>
1638
            <th>Current Price</th>
1639
            <th>Current TP</th>
1640
            <th>Current Margin</th>
1641
            <th>Competition TP</th>
1642
            <th>Lowest Possible TP</th>
1643
            <th>NLC</th>
1644
            <th>Target NLC</th>
1645
            <th>Snapdeal Inventory</th>
1646
            <th>Total Inventory</th>
1647
            <th>Sales History</th>
1648
            </tr></thead>
1649
            <tbody>"""
1650
    items = session.query(MarketPlaceHistory).filter(MarketPlaceHistory.timestamp==currentTimestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.item_id.in_(lost_buy_box)).all()
1651
    for item in items:
1652
        it = Item.query.filter_by(id=item.item_id).one()
1653
        netInventory=''
1654
        if not inventoryMap.has_key(item.item_id):
1655
            netInventory='Info Not Available'
1656
        else:
1657
            netInventory = str(getNetAvailability(inventoryMap.get(item.item_id)))
1658
        message+="""<tr>
1659
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
1660
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
1661
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
1662
                <td style="text-align:center">"""+str(item.ourTp)+"""</td>
1663
                <td style="text-align:center">"""+str(round(item.margin))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
1664
                <td style="text-align:center">"""+str(item.lowestTp)+"""</td>
1665
                <td style="text-align:center">"""+str(item.lowestPossibleTp)+"""</td>
1666
                <td style="text-align:center">"""+str(item.ourNlc)+"""</td>
1667
                <td style="text-align:center">"""+str(item.targetNlc)+"""</td>
1668
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
1669
                <td style="text-align:center">"""+netInventory+"""</td>
1670
                <td style="text-align:center">"""+getOosString((itemSaleMap.get(item.item_id))[1])+"""</td>
1671
                </tr>"""
1672
    message+="""</tbody></table></body></html>"""
1673
    print message
1674
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
1675
    mailServer.ehlo()
1676
    mailServer.starttls()
1677
    mailServer.ehlo()
1678
 
10033 kshitij.so 1679
    #recipients = ['kshitij.sood@saholic.com']
1680
    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 1681
    msg = MIMEMultipart()
1682
    msg['Subject'] = "Snapdeal Lost Buy Box" + ' - ' + str(datetime.now())
1683
    msg['From'] = ""
1684
    msg['To'] = ",".join(recipients)
1685
    msg.preamble = "Snapdeal Lost Buy Box" + ' - ' + str(datetime.now())
1686
    html_msg = MIMEText(message, 'html')
1687
    msg.attach(html_msg)
10207 kshitij.so 1688
    try:
1689
        mailServer.login("build@shop2020.in", "cafe@nes")
1690
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
1691
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
1692
    except Exception as e:
1693
        print e
10219 kshitij.so 1694
        print "Unable to send lost buy bix mail.Lets try local SMTP"
1695
        smtpServer = smtplib.SMTP('localhost')
1696
        smtpServer.set_debuglevel(1)
1697
        sender = 'support@shop2020.in'
1698
        try:
1699
            smtpServer.sendmail(sender, recipients, msg.as_string())
1700
            print "Successfully sent email"
1701
        except:
1702
            print "Error: unable to send email."
1703
 
10031 kshitij.so 1704
 
9881 kshitij.so 1705
 
1706
 
1707
def getOtherTp(snapdealDetails,val,spm):
1708
    if val.parent_category==10011:
1709
        commissionPercentage = spm.competitorCommissionAccessory
1710
    else:
1711
        commissionPercentage = spm.competitorCommissionOther
1712
    if snapdealDetails.rank==1:
10289 kshitij.so 1713
        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 1714
        return round(otherTp,2)
10289 kshitij.so 1715
    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 1716
    return round(otherTp,2)
9881 kshitij.so 1717
 
1718
def getLowestPossibleTp(snapdealDetails,val,spm,mpItem):
1719
    if snapdealDetails.rank==0:
1720
        return mpItem.minimumPossibleTp
1721
    vat = (snapdealDetails.ourSp/(1+(val.vatRate/100))-(val.nlc/(1+(val.vatRate/100))))*(val.vatRate/100);
1722
    inHouseCost = 15+vat+(mpItem.returnProvision/100)*snapdealDetails.ourSp+mpItem.otherCost;
1723
    lowest_possible_tp = val.nlc+inHouseCost;
9954 kshitij.so 1724
    return round(lowest_possible_tp,2)
9881 kshitij.so 1725
 
1726
def getOurTp(snapdealDetails,val,spm,mpItem):
1727
    if snapdealDetails.rank==0:
1728
        return mpItem.currentTp
10289 kshitij.so 1729
    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 1730
    return round(ourTp,2)
9966 kshitij.so 1731
 
1732
def getNewLowestPossibleTp(mpItem,nlc,vatRate,proposedSellingPrice):
1733
    vat = (proposedSellingPrice/(1+(vatRate/100))-(nlc/(1+(vatRate/100))))*(vatRate/100);
1734
    inHouseCost = 15+vat+(mpItem.returnProvision/100)*proposedSellingPrice+mpItem.otherCost;
1735
    lowest_possible_tp = nlc+inHouseCost;
1736
    return round(lowest_possible_tp,2)
1737
 
1738
def getNewOurTp(mpItem,proposedSellingPrice):
10289 kshitij.so 1739
    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 1740
    return round(ourTp,2)
9990 kshitij.so 1741
 
1742
def getNewLowestPossibleSp(mpItem,nlc,vatRate):
10289 kshitij.so 1743
    if (mpItem.pgFee/100)*mpItem.ourSp>=20:
1744
        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));
1745
    else:
1746
        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 1747
    return round(lowestPossibleSp,2)    
9881 kshitij.so 1748
 
1749
def getLowestPossibleSp(snapdealDetails,val,spm,mpItem):
1750
    if snapdealDetails.rank==0:
1751
        return mpItem.minimumPossibleSp
10289 kshitij.so 1752
    #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));
1753
    if (mpItem.pgFee/100)*snapdealDetails.ourSp>=20:
1754
        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))
1755
    else:
1756
        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 1757
    return round(lowestPossibleSp,2)    
9881 kshitij.so 1758
 
1759
def getTargetTp(targetSp,mpItem):
10289 kshitij.so 1760
    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 1761
    return round(targetTp,2)
9881 kshitij.so 1762
 
10289 kshitij.so 1763
def getTargetSp(targetTp,mpItem,ourSp):
10292 kshitij.so 1764
    if (ourSp*(mpItem.pgFee/100)) < 20:
10289 kshitij.so 1765
        targetSp = float(targetTp+(mpItem.courierCost+mpItem.closingFee+20)*(1+(mpItem.serviceTax/100)))/(1-((mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))))
1766
    else:
1767
        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 1768
    return round(targetSp,2)
9881 kshitij.so 1769
 
1770
def getSalesPotential(lowestOfferPrice,ourNlc):
1771
    if lowestOfferPrice - ourNlc < 0:
1772
        return 'HIGH'
9897 kshitij.so 1773
    elif (float(lowestOfferPrice - ourNlc))/lowestOfferPrice >=0 and (float(lowestOfferPrice - ourNlc))/lowestOfferPrice <=.02:
9881 kshitij.so 1774
        return 'MEDIUM'
1775
    else:
1776
        return 'LOW'  
1777
 
1778
def main():
9949 kshitij.so 1779
    parser = optparse.OptionParser()
1780
    parser.add_option("-t", "--type", dest="runType",
1781
                   default="FULL", type="string",
1782
                   help="Run type FULL or FAVOURITE")
1783
    (options, args) = parser.parse_args()
1784
    if options.runType not in ('FULL','FAVOURITE'):
1785
        print "Run type argument illegal."
1786
        sys.exit(1)
10289 kshitij.so 1787
    timestamp = datetime.now()
1788
    itemInfo= populateStuff(options.runType,timestamp)
9881 kshitij.so 1789
    cantCompete, buyBoxItems, competitive, \
10289 kshitij.so 1790
    competitiveNoInventory, exceptionList, negativeMargin = decideCategory(itemInfo)
10031 kshitij.so 1791
    previousProcessingTimestamp = session.query(func.max(MarketPlaceHistory.timestamp)).filter(MarketPlaceHistory.source==7).one()
9949 kshitij.so 1792
    exceptionItems = commitExceptionList(exceptionList,timestamp)
1793
    cantComepeteItems = commitCantCompete(cantCompete,timestamp)
1794
    buyBoxList = commitBuyBox(buyBoxItems,timestamp)
1795
    competitiveItems = commitCompetitive(competitive,timestamp)
1796
    competitiveNoInventoryItems = commitCompetitiveNoInventory(competitiveNoInventory,timestamp)
1797
    negativeMarginItems = commitNegativeMargin(negativeMargin,timestamp)
9954 kshitij.so 1798
    successfulAutoDecrease = fetchItemsForAutoDecrease(timestamp)
1799
    successfulAutoIncrease = fetchItemsForAutoIncrease(timestamp)
9949 kshitij.so 1800
    if options.runType=='FULL':
1801
        previousAutoFav, nowAutoFav = markAutoFavourite()
9954 kshitij.so 1802
    if options.runType=='FULL':
1803
        writeReport(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionList, negativeMargin, previousAutoFav, nowAutoFav,timestamp, options.runType)
1804
    else:
1805
        writeReport(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionList, negativeMargin, None, None, timestamp, options.runType)
10293 kshitij.so 1806
    commitPricing(successfulAutoDecrease,successfulAutoIncrease,timestamp)
9954 kshitij.so 1807
    sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease)
10031 kshitij.so 1808
    processLostBuyBoxItems(previousProcessingTimestamp[0],timestamp)
10293 kshitij.so 1809
    updatePricesOnSnapdeal(successfulAutoDecrease,successfulAutoIncrease)
9897 kshitij.so 1810
 
9881 kshitij.so 1811
if __name__ == '__main__':
1812
    main()