Subversion Repositories SmartDukaan

Rev

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