Subversion Repositories SmartDukaan

Rev

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

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