Subversion Repositories SmartDukaan

Rev

Rev 12337 | Rev 12343 | 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, \
12133 kshitij.so 7
SourceCategoryPercentage, SourceItemPercentage, SourceReturnPercentage
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
11753 kshitij.so 139
#        if not autoDecrementItem.risky:
140
#            markReasonForMpItem(autoDecrementItem,'Item is not risky',Decision.AUTO_DECREMENT_FAILED)
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
12318 kshitij.so 159
        if autoDecrementItem.risky:
160
            if ((not inventoryMap.has_key(autoDecrementItem.item_id)) and autoDecrementItem.risky):
161
                markReasonForMpItem(autoDecrementItem,'Inventory info not available',Decision.AUTO_DECREMENT_FAILED)
9897 kshitij.so 162
                continue
12318 kshitij.so 163
            itemInventory=inventoryMap[autoDecrementItem.item_id]
164
            availableMap  = itemInventory.availability
165
            reserveMap = itemInventory.reserved
166
            for warehouse,availability in availableMap.iteritems():
167
                if warehouse==16 or warehouse==1771:
168
                    continue
169
                totalAvailability = totalAvailability+availability
170
            for warehouse,reserve in reserveMap.iteritems():
171
                if warehouse==16 or warehouse==1771:
172
                    continue
173
                totalReserved = totalReserved+reserve
174
            if (totalAvailability-totalReserved)<=0:
175
                markReasonForMpItem(autoDecrementItem,'Net availability is 0',Decision.AUTO_DECREMENT_FAILED)
9897 kshitij.so 176
                continue
12318 kshitij.so 177
            #if (avgSalePerDay==0):  #exclude
178
            #    markReasonForMpItem(autoDecrementItem,'Average sale per day is zero',Decision.AUTO_DECREMENT_FAILED)
179
            #    continue
180
            avgSalePerDay = (itemSaleMap.get(autoDecrementItem.item_id))[2]
181
            try:
182
                daysOfStock = (float(totalAvailability-totalReserved))/avgSalePerDay
183
            except ZeroDivisionError,e:
184
                lgr.info("Infinite days of stock for item "+str(autoDecrementItem.item_id))
185
                daysOfStock = float("inf")
186
            if daysOfStock<2 and autoDecrementItem.risky:
187
                markReasonForMpItem(autoDecrementItem,'Our stock is not enough',Decision.AUTO_DECREMENT_FAILED)
188
                continue
9897 kshitij.so 189
 
9920 kshitij.so 190
        autoDecrementItem.competitorEnoughStock = True
191
        autoDecrementItem.ourEnoughStock = True
9949 kshitij.so 192
        #autoDecrementItem.avgSales = avgSalePerDay
9920 kshitij.so 193
        autoDecrementItem.decision = Decision.AUTO_DECREMENT_SUCCESS
194
        autoDecrementItem.reason = 'All conditions for auto decrement true'
9954 kshitij.so 195
        successfulAutoDecrease.append(autoDecrementItem)
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
12318 kshitij.so 239
            avgSalePerDay = (itemSaleMap.get(autoIncrementItem.item_id))[2]
240
            if (avgSalePerDay==0):
241
                markReasonForMpItem(autoIncrementItem,'Average sale per day is zero',Decision.AUTO_INCREMENT_FAILED)
242
                continue
9949 kshitij.so 243
        #oosStatus = inventory_client.getOosStatusesForXDaysForItem(autoIncrementItem.item_id,0,3)
244
        #count,sale,daysOfStock = 0,0,0
245
        #for obj in oosStatus:
246
        #    if not obj.is_oos:
247
        #        count+=1
248
        #        sale = sale+obj.num_orders
249
        #avgSalePerDay=0 if count==0 else (float(sale)/count)
9897 kshitij.so 250
        totalAvailability, totalReserved = 0,0
12318 kshitij.so 251
        if autoIncrementItem.risky:
252
            if ((not inventoryMap.has_key(autoIncrementItem.item_id)) and autoIncrementItem.risky):
253
                markReasonForMpItem(autoIncrementItem,'Inventory info not available',Decision.AUTO_INCREMENT_FAILED)
9897 kshitij.so 254
                continue
12318 kshitij.so 255
            itemInventory=inventoryMap[autoIncrementItem.item_id]
256
            availableMap  = itemInventory.availability
257
            reserveMap = itemInventory.reserved
258
            for warehouse,availability in availableMap.iteritems():
259
                if warehouse==16 or warehouse==1771:
260
                    continue
261
                totalAvailability = totalAvailability+availability
262
            for warehouse,reserve in reserveMap.iteritems():
263
                if warehouse==16 or warehouse==1771:
264
                    continue
265
                totalReserved = totalReserved+reserve
266
            #if (totalAvailability-totalReserved)<=0:
267
            #    markReasonForMpItem(autoIncrementItem,'Our stock is 0',Decision.AUTO_INCREMENT_FAILED)
268
            #    continue
269
            daysOfStock = (float(totalAvailability-totalReserved))/avgSalePerDay
270
            if daysOfStock>5:
271
                markReasonForMpItem(autoIncrementItem,'Our stock is enough',Decision.AUTO_INCREMENT_FAILED)
9897 kshitij.so 272
                continue
273
 
9920 kshitij.so 274
        autoIncrementItem.ourEnoughStock = False
9949 kshitij.so 275
        #autoIncrementItem.avgSales = avgSalePerDay
9920 kshitij.so 276
        autoIncrementItem.decision = Decision.AUTO_INCREMENT_SUCCESS
277
        autoIncrementItem.reason = 'All conditions for auto increment true'
9954 kshitij.so 278
        successfulAutoIncrease.append(autoIncrementItem)
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():
12318 kshitij.so 303
        if warehouse==16 or warehouse==1771:
9949 kshitij.so 304
            continue
305
        totalAvailability = totalAvailability+availability
306
    for warehouse,reserve in reserveMap.iteritems():
12318 kshitij.so 307
        if warehouse==16 or warehouse==1771:
9949 kshitij.so 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):
11824 kshitij.so 364
    url="http://www.snapdeal.com/acors/json/gvbps?supc=%s&catId=91&sort=sellingPrice"%(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()
12133 kshitij.so 423
        srm = SourceReturnPercentage.get_by(source=OrderSource.SNAPDEAL,brand=it.brand,category_id=it.category)
10290 kshitij.so 424
        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 425
        sourcePercentage = None
426
        if sip is not None:
427
            sourcePercentage = sip
12136 kshitij.so 428
            sourcePercentage.returnProvision = srm.returnProvision
10289 kshitij.so 429
        else:
430
            scp = SourceCategoryPercentage.query.filter(SourceCategoryPercentage.category_id==it.category).filter(SourceCategoryPercentage.source==OrderSource.SNAPDEAL).filter(SourceCategoryPercentage.startDate<=time).filter(SourceCategoryPercentage.expiryDate>=time).first()
431
            if scp is not None:
432
                sourcePercentage = scp
12136 kshitij.so 433
                sourcePercentage.returnProvision = srm.returnProvision
10289 kshitij.so 434
            else:
435
                spm = SourcePercentageMaster.get_by(source=OrderSource.SNAPDEAL)
436
                sourcePercentage = spm
12136 kshitij.so 437
                sourcePercentage.returnProvision = srm.returnProvision
11099 kshitij.so 438
        snapdealItemInfo = __SnapdealItemInfo(snapdeal_item.supc, snapdeal_item.maxNlc,snapdeal_item.courierCostMarketplace, 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 439
        itemInfo.append(snapdealItemInfo)
12147 kshitij.so 440
    session.close()
10289 kshitij.so 441
    return itemInfo
9881 kshitij.so 442
 
443
 
10289 kshitij.so 444
def decideCategory(itemInfo):
9949 kshitij.so 445
    global itemSaleMap
9881 kshitij.so 446
    cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin = [],[],[],[],[],[]
447
    catalog_client = CatalogClient().get_client()
448
    inventory_client = InventoryClient().get_client()
449
 
450
    for val in itemInfo:
10291 kshitij.so 451
        spm = val.sourcePercentage
9881 kshitij.so 452
        try:
453
            snapdealDetails = fetchDetails(val.supc)
454
        except:
455
            exceptionItems.append(val)
456
            continue
457
        mpItem = MarketplaceItems.get_by(itemId=val.item_id,source=OrderSource.SNAPDEAL)
458
        warehouse = inventory_client.getWarehouse(val.warehouseId)
9949 kshitij.so 459
 
460
        itemSaleList = []
461
        oosForAllSources = inventory_client.getOosStatusesForXDaysForItem(val.item_id, 0, 3)
462
        oosForSnapdeal = inventory_client.getOosStatusesForXDaysForItem(val.item_id, OrderSource.SNAPDEAL, 5)
9966 kshitij.so 463
        oosForSnapdealLastDay = inventory_client.getOosStatusesForXDaysForItem(val.item_id, OrderSource.SNAPDEAL, 1)
9949 kshitij.so 464
        itemSaleList.append(oosForAllSources)
465
        itemSaleList.append(oosForSnapdeal)
466
        itemSaleList.append(calculateAverageSale(oosForAllSources))
467
        itemSaleList.append(calculateAverageSale(oosForSnapdeal))
9966 kshitij.so 468
        itemSaleList.append(calculateAverageSale(oosForSnapdealLastDay))
10271 kshitij.so 469
        itemSaleList.append(calculateTotalSale(oosForSnapdeal))
9949 kshitij.so 470
        itemSaleMap[val.item_id]=itemSaleList
471
 
9881 kshitij.so 472
        if snapdealDetails.rank==0:
473
            snapdealDetails.ourSp = mpItem.currentSp
474
            snapdealDetails.ourOfferPrice = mpItem.currentSp
475
            ourSp = mpItem.currentSp
476
        else:
477
            ourSp = snapdealDetails.ourSp
478
        vatRate = catalog_client.getVatPercentageForItem(val.item_id, warehouse.stateId, snapdealDetails.ourSp)
479
        val.vatRate = vatRate
480
        if (snapdealDetails.rank==1):
481
            temp=[]
482
            temp.append(snapdealDetails)
483
            temp.append(val)
484
            if (snapdealDetails.secondLowestSellerOfferPrice == snapdealDetails.secondLowestSellerSp) and snapdealDetails.ourOfferPrice==snapdealDetails.ourSp:
485
                competitionBasis = 'SP'
486
            else:
487
                competitionBasis = 'TP'
488
            secondLowestTp=0 if snapdealDetails.totalSeller==1 else getOtherTp(snapdealDetails,val,spm)
489
            snapdealPricing = __SnapdealPricing(snapdealDetails.ourSp,getOurTp(snapdealDetails,val,spm,mpItem),None,getLowestPossibleTp(snapdealDetails,val,spm,mpItem),competitionBasis,secondLowestTp,getLowestPossibleSp(snapdealDetails,val,spm,mpItem))
490
            temp.append(snapdealPricing)
491
            temp.append(mpItem)
492
            buyBoxItems.append(temp)
493
            continue
494
 
495
 
496
        lowestTp = getOtherTp(snapdealDetails,val,spm)
497
        ourTp = getOurTp(snapdealDetails,val,spm,mpItem)
498
        lowestPossibleTp = getLowestPossibleTp(snapdealDetails,val,spm,mpItem)
499
        lowestPossibleSp = getLowestPossibleSp(snapdealDetails,val,spm,mpItem)
500
 
501
        if (ourTp<lowestPossibleTp):
502
            temp=[]
503
            temp.append(snapdealDetails)
504
            temp.append(val)
12156 kshitij.so 505
            snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,None,getLowestPossibleSp(snapdealDetails,val,spm,mpItem))
9881 kshitij.so 506
            temp.append(snapdealPricing)
507
            negativeMargin.append(temp)
508
            continue
509
 
510
        if (snapdealDetails.lowestOfferPrice == snapdealDetails.lowestSp) and snapdealDetails.ourOfferPrice == snapdealDetails.ourSp:
511
            competitionBasis ='SP'
512
        else:
513
            competitionBasis ='TP'
514
 
515
        if competitionBasis=='SP':
516
            if snapdealDetails.lowestSp > lowestPossibleSp and snapdealDetails.ourInventory!=0:
517
                temp=[]
518
                temp.append(snapdealDetails)
519
                temp.append(val)
520
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'SP',None,lowestPossibleSp)
521
                temp.append(snapdealPricing)
522
                temp.append(mpItem)
523
                competitive.append(temp)
524
                continue
525
        else:
10759 kshitij.so 526
            if (snapdealDetails.lowestSp-getSubsidyDiff(snapdealDetails) > lowestPossibleSp) and snapdealDetails.ourInventory!=0:
527
            #if lowestTp > lowestPossibleTp and snapdealDetails.ourInventory!=0:
9881 kshitij.so 528
                temp=[]
529
                temp.append(snapdealDetails)
530
                temp.append(val)
531
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'TP',None,lowestPossibleSp)
532
                temp.append(snapdealPricing)
533
                temp.append(mpItem)
534
                competitive.append(temp)
535
                continue
536
 
537
        if competitionBasis=='SP':
538
            if snapdealDetails.lowestSp > lowestPossibleSp and snapdealDetails.ourInventory==0:
539
                temp=[]
540
                temp.append(snapdealDetails)
541
                temp.append(val)
542
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'SP',None,lowestPossibleSp)
543
                temp.append(snapdealPricing)
544
                temp.append(mpItem)
545
                competitiveNoInventory.append(temp)
546
                continue
547
        else:
10760 kshitij.so 548
            if (snapdealDetails.lowestSp-getSubsidyDiff(snapdealDetails) > lowestPossibleSp) and snapdealDetails.ourInventory==0:
10473 kshitij.so 549
            #lowest sp - subs diff < lowest pos sp 
10759 kshitij.so 550
            #if lowestTp > lowestPossibleTp and snapdealDetails.ourInventory==0:
9881 kshitij.so 551
                temp=[]
552
                temp.append(snapdealDetails)
553
                temp.append(val)
554
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'TP',None,lowestPossibleSp)
555
                temp.append(snapdealPricing)
556
                temp.append(mpItem)
557
                competitiveNoInventory.append(temp)
558
                continue
559
 
560
        temp=[]
561
        temp.append(snapdealDetails)
562
        temp.append(val)
563
        snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,competitionBasis,None,lowestPossibleSp)
564
        temp.append(snapdealPricing)
565
        temp.append(mpItem)
566
        cantCompete.append(temp)
567
 
9949 kshitij.so 568
    return cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin
569
 
9953 kshitij.so 570
def writeReport(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionList, negativeMargin, previousAutoFav, nowAutoFav,timestamp,runType):
9949 kshitij.so 571
    wbk = xlwt.Workbook()
572
    sheet = wbk.add_sheet('Can\'t Compete')
573
    xstr = lambda s: s or ""
574
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
575
 
576
    excel_integer_format = '0'
577
    integer_style = xlwt.XFStyle()
578
    integer_style.num_format_str = excel_integer_format
579
 
580
    sheet.write(0, 0, "Item ID", heading_xf)
581
    sheet.write(0, 1, "Category", heading_xf)
582
    sheet.write(0, 2, "Product Group.", heading_xf)
583
    sheet.write(0, 3, "SUPC", heading_xf)
584
    sheet.write(0, 4, "Brand", heading_xf)
585
    sheet.write(0, 5, "Product Name", heading_xf)
586
    sheet.write(0, 6, "Weight", heading_xf)
587
    sheet.write(0, 7, "Courier Cost", heading_xf)
588
    sheet.write(0, 8, "Risky", heading_xf)
11780 kshitij.so 589
    sheet.write(0, 9, "Commission Rate", heading_xf)
590
    sheet.write(0, 10, "Return Provision", heading_xf)
591
    sheet.write(0, 11, "Our SP", heading_xf)
592
    sheet.write(0, 13, "Our TP", heading_xf)
593
    sheet.write(0, 12, "Our Offer Price", heading_xf)
594
    sheet.write(0, 14, "Our Rank", heading_xf)
595
    sheet.write(0, 15, "Lowest Seller", heading_xf)
596
    sheet.write(0, 16, "Lowest SP", heading_xf)
597
    sheet.write(0, 17, "Lowest TP", heading_xf)
598
    sheet.write(0, 18, "Lowest Offer Price", heading_xf)
599
    sheet.write(0, 19, "Inventory of Top Vendors", heading_xf)
600
    sheet.write(0, 20, "Our Snapdeal Inventory", heading_xf)
601
    sheet.write(0, 21, "Our Net Availability",heading_xf)
602
    sheet.write(0, 22, "Last Five Day Sale", heading_xf)
603
    sheet.write(0, 23, "Average Sale", heading_xf)
604
    sheet.write(0, 24, "Our NLC", heading_xf)
605
    sheet.write(0, 25, "Lowest Possible TP", heading_xf)
606
    sheet.write(0, 26, "Lowest Possible SP", heading_xf)
607
    sheet.write(0, 27, "Subsidy Difference", heading_xf)
608
    sheet.write(0, 28, "Target TP", heading_xf)
609
    sheet.write(0, 29, "Target SP", heading_xf)  
610
    sheet.write(0, 30, "Target NLC", heading_xf)
611
    sheet.write(0, 31, "Sales Potential", heading_xf)
9949 kshitij.so 612
    sheet_iterator = 1
613
    for item in cantCompete:
614
        snapdealDetails = item[0]
615
        snapdealItemInfo = item[1]
616
        snapdealPricing = item[2]
617
        mpItem = item[3]
11780 kshitij.so 618
        spmObj = snapdealItemInfo.sourcePercentage
9949 kshitij.so 619
        sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
620
        sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
621
        sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
622
        sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
623
        sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
624
        sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
625
        sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
626
        sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
627
        sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
11780 kshitij.so 628
        sheet.write(sheet_iterator, 9, spmObj.commission)
629
        sheet.write(sheet_iterator, 10, spmObj.returnProvision)
630
        sheet.write(sheet_iterator, 11, snapdealPricing.ourSp)
631
        sheet.write(sheet_iterator, 12, snapdealDetails.ourOfferPrice)
632
        sheet.write(sheet_iterator, 13, snapdealPricing.ourTp)
633
        sheet.write(sheet_iterator, 14, snapdealDetails.rank)
634
        sheet.write(sheet_iterator, 15, snapdealDetails.lowestSellerName)
635
        sheet.write(sheet_iterator, 16, snapdealDetails.lowestSp)
636
        sheet.write(sheet_iterator, 17, snapdealPricing.lowestTp)
637
        sheet.write(sheet_iterator, 18, snapdealDetails.lowestOfferPrice)
638
        sheet.write(sheet_iterator, 19, snapdealDetails.otherInventory)
639
        sheet.write(sheet_iterator, 20, snapdealDetails.ourInventory)
9949 kshitij.so 640
        if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
11780 kshitij.so 641
            sheet.write(sheet_iterator, 21, 'Info not available')
9949 kshitij.so 642
        else:
11780 kshitij.so 643
            sheet.write(sheet_iterator, 21, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
644
        sheet.write(sheet_iterator, 22, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
645
        sheet.write(sheet_iterator, 23, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
646
        sheet.write(sheet_iterator, 24, snapdealItemInfo.nlc)
647
        sheet.write(sheet_iterator, 25, snapdealPricing.lowestPossibleTp)
648
        sheet.write(sheet_iterator, 26, snapdealPricing.lowestPossibleSp)
649
        sheet.write(sheet_iterator, 27, getSubsidyDiff(snapdealDetails))
9949 kshitij.so 650
        if (snapdealPricing.competitionBasis=='SP'):
651
            proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
652
            proposed_tp = getTargetTp(proposed_sp,mpItem)
653
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
654
        else:
10381 manish.sha 655
            #proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
656
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
657
            proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001) - getSubsidyDiff(snapdealDetails)
658
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9949 kshitij.so 659
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
11780 kshitij.so 660
        sheet.write(sheet_iterator, 28, round(proposed_tp,2))
661
        sheet.write(sheet_iterator, 29, round(proposed_sp,2))
662
        sheet.write(sheet_iterator, 30, round(target_nlc,2))
663
        sheet.write(sheet_iterator, 31, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
9949 kshitij.so 664
        sheet_iterator+=1
665
 
666
    sheet = wbk.add_sheet('Lowest')
667
 
668
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
669
 
670
    excel_integer_format = '0'
671
    integer_style = xlwt.XFStyle()
672
    integer_style.num_format_str = excel_integer_format
673
    xstr = lambda s: s or ""
674
 
675
    sheet.write(0, 0, "Item ID", heading_xf)
676
    sheet.write(0, 1, "Category", heading_xf)
677
    sheet.write(0, 2, "Product Group.", heading_xf)
678
    sheet.write(0, 3, "SUPC", heading_xf)
679
    sheet.write(0, 4, "Brand", heading_xf)
680
    sheet.write(0, 5, "Product Name", heading_xf)
681
    sheet.write(0, 6, "Weight", heading_xf)
682
    sheet.write(0, 7, "Courier Cost", heading_xf)
683
    sheet.write(0, 8, "Risky", heading_xf)
11780 kshitij.so 684
    sheet.write(0, 9, "Commission Rate", heading_xf)
685
    sheet.write(0, 10, "Return Provision", heading_xf)
686
    sheet.write(0, 11, "Our SP", heading_xf)
687
    sheet.write(0, 13, "Our TP", heading_xf)
688
    sheet.write(0, 12, "Our Offer Price", heading_xf)
689
    sheet.write(0, 14, "Our Rank", heading_xf)
690
    sheet.write(0, 15, "Lowest Seller", heading_xf)
691
    sheet.write(0, 16, "Second Lowest Seller", heading_xf)
692
    sheet.write(0, 17, "Second Lowest Price", heading_xf)
693
    sheet.write(0, 18, "Second Lowest Offer Price", heading_xf)
694
    sheet.write(0, 19, "Second Lowest Seller TP", heading_xf)
695
    sheet.write(0, 20, "Our Snapdeal Inventory", heading_xf)
696
    sheet.write(0, 21, "Our Net Availability",heading_xf)
697
    sheet.write(0, 22, "Last Five Day Sale", heading_xf)
698
    sheet.write(0, 23, "Average Sale", heading_xf)
699
    sheet.write(0, 24, "Second Lowest Seller Inventory", heading_xf)
700
    sheet.write(0, 25, "Our NLC", heading_xf)
701
    sheet.write(0, 26, "Subsidy Difference", heading_xf)
702
    sheet.write(0, 27, "Target TP", heading_xf)
703
    sheet.write(0, 28, "Target SP", heading_xf)
704
    sheet.write(0, 29, "MARGIN INCREASED POTENTIAL", heading_xf)
705
    sheet.write(0, 30, "Auto Pricing Decision", heading_xf)
706
    sheet.write(0, 31, "Reason", heading_xf)
707
    sheet.write(0, 32, "Updated Price", heading_xf)
9949 kshitij.so 708
 
709
    sheet_iterator = 1
710
    for item in buyBoxItems:
711
        snapdealDetails = item[0]
712
        snapdealItemInfo = item[1]
713
        snapdealPricing = item[2]
714
        mpItem = item[3]
11780 kshitij.so 715
        spmObj = snapdealItemInfo.sourcePercentage
9949 kshitij.so 716
        sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
717
        sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
718
        sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
719
        sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
720
        sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
721
        sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
722
        sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
723
        sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
724
        sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
11780 kshitij.so 725
        sheet.write(sheet_iterator, 9, spmObj.commission)
726
        sheet.write(sheet_iterator, 10, spmObj.returnProvision)
727
        sheet.write(sheet_iterator, 11, snapdealPricing.ourSp)
728
        sheet.write(sheet_iterator, 12, snapdealDetails.ourOfferPrice)
729
        sheet.write(sheet_iterator, 13, snapdealPricing.ourTp)
730
        sheet.write(sheet_iterator, 14, snapdealDetails.rank)
731
        sheet.write(sheet_iterator, 15, snapdealDetails.lowestSellerName)
732
        sheet.write(sheet_iterator, 16, snapdealDetails.secondLowestSellerName)
733
        sheet.write(sheet_iterator, 17, snapdealDetails.secondLowestSellerSp)
734
        sheet.write(sheet_iterator, 18, snapdealDetails.secondLowestSellerOfferPrice)
735
        sheet.write(sheet_iterator, 19, snapdealPricing.secondLowestSellerTp)
736
        sheet.write(sheet_iterator, 20, snapdealDetails.ourInventory)
9949 kshitij.so 737
        if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
11780 kshitij.so 738
            sheet.write(sheet_iterator, 21, 'Info not available')
9949 kshitij.so 739
        else:
11780 kshitij.so 740
            sheet.write(sheet_iterator, 21, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
741
        sheet.write(sheet_iterator, 22, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
742
        sheet.write(sheet_iterator, 23, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
743
        sheet.write(sheet_iterator, 24, snapdealDetails.secondLowestSellerInventory)
744
        sheet.write(sheet_iterator, 25, snapdealItemInfo.nlc)
745
        sheet.write(sheet_iterator, 26, getSubsidyDiff(snapdealDetails))
9949 kshitij.so 746
        if (snapdealPricing.competitionBasis=='SP'):
747
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)), snapdealPricing.lowestPossibleSp)
748
            proposed_tp = getTargetTp(proposed_sp,mpItem)
749
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
750
        else:
10381 manish.sha 751
            #proposed_tp  = max(snapdealPricing.secondLowestSellerTp - max((20, snapdealPricing.secondLowestSellerTp*0.002)), snapdealPricing.lowestPossibleTp)
752
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
753
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)) -getSubsidyDiff(snapdealDetails), snapdealPricing.lowestPossibleSp)
754
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9949 kshitij.so 755
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
11780 kshitij.so 756
        sheet.write(sheet_iterator, 27, round(proposed_tp,2))
757
        sheet.write(sheet_iterator, 28, round(proposed_sp,2))
758
        sheet.write(sheet_iterator, 29, round((proposed_tp - snapdealPricing.ourTp),2))
10958 kshitij.so 759
        mp_history_item = session.query(MarketPlaceHistory).filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.item_id==snapdealItemInfo.item_id).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).one()
10960 kshitij.so 760
        if mp_history_item.decision is None:
11780 kshitij.so 761
            sheet.write(sheet_iterator, 30, 'Auto Pricing Inactive')
10959 kshitij.so 762
            sheet_iterator+=1
763
            continue
11780 kshitij.so 764
        sheet.write(sheet_iterator, 30, Decision._VALUES_TO_NAMES.get(mp_history_item.decision))
765
        sheet.write(sheet_iterator, 31, mp_history_item.reason)
10958 kshitij.so 766
        if Decision._VALUES_TO_NAMES.get(mp_history_item.decision) == "AUTO_DECREMENT_SUCCESS":
11780 kshitij.so 767
            sheet.write(sheet_iterator, 32, math.ceil(mp_history_item.proposedSellingPrice))
10958 kshitij.so 768
        if Decision._VALUES_TO_NAMES.get(mp_history_item.decision) == "AUTO_INCREMENT_SUCCESS":
11780 kshitij.so 769
            sheet.write(sheet_iterator, 32, math.ceil(mp_history_item.ourSellingPrice+max(10,.01*mp_history_item.ourSellingPrice)))
9949 kshitij.so 770
        sheet_iterator+=1
771
 
772
    sheet = wbk.add_sheet('Can Compete-With Inventory')
773
 
774
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
775
 
776
    excel_integer_format = '0'
777
    integer_style = xlwt.XFStyle()
778
    integer_style.num_format_str = excel_integer_format
779
    xstr = lambda s: s or ""
780
 
781
    sheet.write(0, 0, "Item ID", heading_xf)
782
    sheet.write(0, 1, "Category", heading_xf)
783
    sheet.write(0, 2, "Product Group.", heading_xf)
784
    sheet.write(0, 3, "SUPC", heading_xf)
785
    sheet.write(0, 4, "Brand", heading_xf)
786
    sheet.write(0, 5, "Product Name", heading_xf)
787
    sheet.write(0, 6, "Weight", heading_xf)
788
    sheet.write(0, 7, "Courier Cost", heading_xf)
789
    sheet.write(0, 8, "Risky", heading_xf)
11780 kshitij.so 790
    sheet.write(0, 9, "Commission Rate", heading_xf)
791
    sheet.write(0, 10, "Return Provision", heading_xf)
792
    sheet.write(0, 11, "Our SP", heading_xf)
793
    sheet.write(0, 13, "Our TP", heading_xf)
794
    sheet.write(0, 12, "Our Offer Price", heading_xf)
795
    sheet.write(0, 14, "Our Rank", heading_xf)
796
    sheet.write(0, 15, "Lowest Seller", heading_xf)
797
    sheet.write(0, 16, "Lowest SP", heading_xf)
798
    sheet.write(0, 17, "Lowest TP", heading_xf)
799
    sheet.write(0, 18, "Lowest Offer Price", heading_xf)
800
    sheet.write(0, 19, "Inventory of Top Vendors", heading_xf)
801
    sheet.write(0, 20, "Our Snapdeal Inventory", heading_xf)
802
    sheet.write(0, 21, "Our Net Availability",heading_xf)
803
    sheet.write(0, 22, "Last Five Day Sale", heading_xf)
804
    sheet.write(0, 23, "Average Sale", heading_xf)
805
    sheet.write(0, 24, "Our NLC", heading_xf)
806
    sheet.write(0, 25, "Lowest Possible TP", heading_xf)
807
    sheet.write(0, 26, "Lowest Possible SP", heading_xf)
808
    sheet.write(0, 27, "Subsidy Difference", heading_xf)
809
    sheet.write(0, 28, "Target TP", heading_xf)
810
    sheet.write(0, 29, "Target SP", heading_xf)  
811
    sheet.write(0, 30, "Sales Potential", heading_xf)
812
    sheet.write(0, 31, "Auto Pricing Decision", heading_xf)
813
    sheet.write(0, 32, "Reason", heading_xf)
814
    sheet.write(0, 33, "Updated Price", heading_xf)
9949 kshitij.so 815
 
816
    sheet_iterator = 1
817
    for item in competitive:
818
        snapdealDetails = item[0]
819
        snapdealItemInfo = item[1]
820
        snapdealPricing = item[2]
821
        mpItem = item[3]
11780 kshitij.so 822
        spmObj = snapdealItemInfo.sourcePercentage
9949 kshitij.so 823
        sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
824
        sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
825
        sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
826
        sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
827
        sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
828
        sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
829
        sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
830
        sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
831
        sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
11780 kshitij.so 832
        sheet.write(sheet_iterator, 9, spmObj.commission)
833
        sheet.write(sheet_iterator, 10, spmObj.returnProvision)
834
        sheet.write(sheet_iterator, 11, snapdealPricing.ourSp)
835
        sheet.write(sheet_iterator, 12, snapdealDetails.ourOfferPrice)
836
        sheet.write(sheet_iterator, 13, snapdealPricing.ourTp)
837
        sheet.write(sheet_iterator, 14, snapdealDetails.rank)
838
        sheet.write(sheet_iterator, 15, snapdealDetails.lowestSellerName)
839
        sheet.write(sheet_iterator, 16, snapdealDetails.lowestSp)
840
        sheet.write(sheet_iterator, 17, snapdealPricing.lowestTp)
841
        sheet.write(sheet_iterator, 18, snapdealDetails.lowestOfferPrice)
842
        sheet.write(sheet_iterator, 19, snapdealDetails.otherInventory)
843
        sheet.write(sheet_iterator, 20, snapdealDetails.ourInventory)
9949 kshitij.so 844
        if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
11780 kshitij.so 845
            sheet.write(sheet_iterator, 21, 'Info not available')
9949 kshitij.so 846
        else:
11780 kshitij.so 847
            sheet.write(sheet_iterator, 21, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
848
        sheet.write(sheet_iterator, 22, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
849
        sheet.write(sheet_iterator, 23, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
850
        sheet.write(sheet_iterator, 24, snapdealItemInfo.nlc)
851
        sheet.write(sheet_iterator, 25, snapdealPricing.lowestPossibleTp)
852
        sheet.write(sheet_iterator, 26, snapdealPricing.lowestPossibleSp)
853
        sheet.write(sheet_iterator, 27, getSubsidyDiff(snapdealDetails))
9949 kshitij.so 854
        if (snapdealPricing.competitionBasis=='SP'):
855
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
856
            proposed_tp = getTargetTp(proposed_sp,mpItem)
857
        else:
10381 manish.sha 858
            #proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
859
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
860
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)) -getSubsidyDiff(snapdealDetails), snapdealPricing.lowestPossibleSp)
861
            proposed_tp = getTargetTp(proposed_sp,mpItem)
11780 kshitij.so 862
        sheet.write(sheet_iterator, 28, round(proposed_tp,2))
863
        sheet.write(sheet_iterator, 29, round(proposed_sp,2))
864
        sheet.write(sheet_iterator, 30, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
10958 kshitij.so 865
        mp_history_item = session.query(MarketPlaceHistory).filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.item_id==snapdealItemInfo.item_id).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).one()
10960 kshitij.so 866
        if mp_history_item.decision is None:
11780 kshitij.so 867
            sheet.write(sheet_iterator, 31, 'Auto pricing Inactive')
10959 kshitij.so 868
            sheet_iterator+=1
869
            continue
11780 kshitij.so 870
        sheet.write(sheet_iterator, 31, Decision._VALUES_TO_NAMES.get(mp_history_item.decision))
871
        sheet.write(sheet_iterator, 32, mp_history_item.reason)
10958 kshitij.so 872
        if Decision._VALUES_TO_NAMES.get(mp_history_item.decision) == "AUTO_DECREMENT_SUCCESS":
11780 kshitij.so 873
            sheet.write(sheet_iterator, 33, math.ceil(mp_history_item.proposedSellingPrice))
10958 kshitij.so 874
        if Decision._VALUES_TO_NAMES.get(mp_history_item.decision) == "AUTO_INCREMENT_SUCCESS":
11780 kshitij.so 875
            sheet.write(sheet_iterator, 33, math.ceil(mp_history_item.ourSellingPrice+max(10,.01*mp_history_item.ourSellingPrice)))
9949 kshitij.so 876
        sheet_iterator+=1
877
 
878
    sheet = wbk.add_sheet('Negative Margin')
879
 
880
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
881
 
882
    excel_integer_format = '0'
883
    integer_style = xlwt.XFStyle()
884
    integer_style.num_format_str = excel_integer_format
885
    xstr = lambda s: s or ""
886
 
887
    sheet.write(0, 0, "Item ID", heading_xf)
888
    sheet.write(0, 1, "Category", heading_xf)
889
    sheet.write(0, 2, "Product Group.", heading_xf)
890
    sheet.write(0, 3, "SUPC", heading_xf)
891
    sheet.write(0, 4, "Brand", heading_xf)
892
    sheet.write(0, 5, "Product Name", heading_xf)
893
    sheet.write(0, 6, "Weight", heading_xf)
894
    sheet.write(0, 7, "Courier Cost", heading_xf)
895
    sheet.write(0, 8, "Risky", heading_xf)
11780 kshitij.so 896
    sheet.write(0, 9, "Commission Rate", heading_xf)
897
    sheet.write(0, 10, "Return Provision", heading_xf)
898
    sheet.write(0, 11, "Our SP", heading_xf)
899
    sheet.write(0, 13, "Our TP", heading_xf)
900
    sheet.write(0, 14, "Lowest Possible TP", heading_xf)
901
    sheet.write(0, 12, "Our Offer Price", heading_xf)
902
    sheet.write(0, 15, "Our Rank", heading_xf)
903
    sheet.write(0, 16, "Our Snapdeal Inventory", heading_xf)
904
    sheet.write(0, 17, "Net Availability", heading_xf)
905
    sheet.write(0, 18, "Last Five Day Sale", heading_xf)
906
    sheet.write(0, 19, "Average Sale", heading_xf)
907
    sheet.write(0, 20, "Our NLC", heading_xf)
908
    sheet.write(0, 21, "Margin", heading_xf)
9949 kshitij.so 909
 
910
    sheet_iterator=1
911
    for item in negativeMargin:
912
        snapdealDetails = item[0]
913
        snapdealItemInfo = item[1]
914
        snapdealPricing = item[2]
11780 kshitij.so 915
        spmObj = snapdealItemInfo.sourcePercentage
9949 kshitij.so 916
        sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
917
        sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
918
        sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
919
        sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
920
        sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
921
        sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
922
        sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
923
        sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
924
        sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
11780 kshitij.so 925
        sheet.write(sheet_iterator, 9, spmObj.commission)
926
        sheet.write(sheet_iterator, 10, spmObj.returnProvision)
927
        sheet.write(sheet_iterator, 11, snapdealPricing.ourSp)
928
        sheet.write(sheet_iterator, 12, snapdealDetails.ourOfferPrice)
929
        sheet.write(sheet_iterator, 13, snapdealPricing.ourTp)
930
        sheet.write(sheet_iterator, 14, snapdealPricing.lowestPossibleTp)
931
        sheet.write(sheet_iterator, 15, snapdealDetails.rank)
932
        sheet.write(sheet_iterator, 16, snapdealDetails.ourInventory)
9949 kshitij.so 933
        if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
11780 kshitij.so 934
            sheet.write(sheet_iterator, 17, 'Info not available')
9949 kshitij.so 935
        else:
11780 kshitij.so 936
            sheet.write(sheet_iterator, 17, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
937
        sheet.write(sheet_iterator, 18, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
938
        sheet.write(sheet_iterator, 19, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
939
        sheet.write(sheet_iterator, 20, snapdealItemInfo.nlc)
940
        sheet.write(sheet_iterator, 21, round((snapdealPricing.ourTp - snapdealPricing.lowestPossibleTp),2))
9949 kshitij.so 941
        sheet_iterator+=1
942
 
943
    sheet = wbk.add_sheet('Exception Item List')
944
 
945
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
946
 
947
    excel_integer_format = '0'
948
    integer_style = xlwt.XFStyle()
949
    integer_style.num_format_str = excel_integer_format
950
    xstr = lambda s: s or ""
951
 
952
    sheet.write(0, 0, "Item ID", heading_xf)
953
    sheet.write(0, 1, "Brand", heading_xf)
954
    sheet.write(0, 2, "Product Name", heading_xf)
955
    sheet.write(0, 3, "Reason", heading_xf)
956
    sheet_iterator=1
957
    for item in exceptionList:
958
        sheet.write(sheet_iterator, 0, item.item_id)
959
        sheet.write(sheet_iterator, 1, item.brand)
960
        sheet.write(sheet_iterator, 2, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
961
        sheet.write(sheet_iterator, 3, "Unable to fetch info from Snapdeal")
962
        sheet_iterator+=1
963
 
964
    sheet = wbk.add_sheet('Can Compete-No Inv')
965
 
966
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
967
 
968
    excel_integer_format = '0'
969
    integer_style = xlwt.XFStyle()
970
    integer_style.num_format_str = excel_integer_format
971
    xstr = lambda s: s or ""
972
 
973
    sheet.write(0, 0, "Item ID", heading_xf)
974
    sheet.write(0, 1, "Category", heading_xf)
975
    sheet.write(0, 2, "Product Group.", heading_xf)
976
    sheet.write(0, 3, "SUPC", heading_xf)
977
    sheet.write(0, 4, "Brand", heading_xf)
978
    sheet.write(0, 5, "Product Name", heading_xf)
979
    sheet.write(0, 6, "Weight", heading_xf)
980
    sheet.write(0, 7, "Courier Cost", heading_xf)
981
    sheet.write(0, 8, "Risky", heading_xf)
11780 kshitij.so 982
    sheet.write(0, 9, "Commission Rate", heading_xf)
983
    sheet.write(0, 10, "Return Provision", heading_xf)
984
    sheet.write(0, 11, "Our SP", heading_xf)
985
    sheet.write(0, 13, "Our TP", heading_xf)
986
    sheet.write(0, 12, "Our Offer Price", heading_xf)
987
    sheet.write(0, 14, "Our Rank", heading_xf)
988
    sheet.write(0, 15, "Lowest Seller", heading_xf)
989
    sheet.write(0, 16, "Lowest SP", heading_xf)
990
    sheet.write(0, 17, "Lowest TP", heading_xf)
991
    sheet.write(0, 18, "Lowest Offer Price", heading_xf)
992
    sheet.write(0, 19, "Inventory of Top Vendors", heading_xf)
993
    sheet.write(0, 20, "Our Snapdeal Inventory", heading_xf)
994
    sheet.write(0, 21, "Our Net Availability",heading_xf)
995
    sheet.write(0, 22, "Last Five Day Sale", heading_xf)
996
    sheet.write(0, 23, "Average Sale", heading_xf)
997
    sheet.write(0, 24, "Our NLC", heading_xf)
998
    sheet.write(0, 25, "Lowest Possible TP", heading_xf)
999
    sheet.write(0, 26, "Lowest Possible SP", heading_xf)
1000
    sheet.write(0, 27, "Subsidy Difference", heading_xf)
1001
    sheet.write(0, 28, "Target TP", heading_xf)
1002
    sheet.write(0, 29, "Target SP", heading_xf)  
1003
    sheet.write(0, 30, "Target NLC", heading_xf)
1004
    sheet.write(0, 31, "Sales Potential", heading_xf)
9949 kshitij.so 1005
 
1006
    sheet_iterator = 1
1007
    for item in competitiveNoInventory:
1008
        snapdealDetails = item[0]
1009
        snapdealItemInfo = item[1]
1010
        snapdealPricing = item[2]
1011
        mpItem = item[3]
11780 kshitij.so 1012
        spmObj = snapdealItemInfo.sourcePercentage
9949 kshitij.so 1013
        if ((not inventoryMap.has_key(snapdealItemInfo.item_id)) or getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id))<=0):
1014
            sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
1015
            sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
1016
            sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
1017
            sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
1018
            sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
1019
            sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
1020
            sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
1021
            sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
1022
            sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
11780 kshitij.so 1023
            sheet.write(sheet_iterator, 9, spmObj.commission)
1024
            sheet.write(sheet_iterator, 10, spmObj.returnProvision)
1025
            sheet.write(sheet_iterator, 11, snapdealPricing.ourSp)
1026
            sheet.write(sheet_iterator, 12, snapdealDetails.ourOfferPrice)
1027
            sheet.write(sheet_iterator, 13, snapdealPricing.ourTp)
1028
            sheet.write(sheet_iterator, 14, snapdealDetails.rank)
1029
            sheet.write(sheet_iterator, 15, snapdealDetails.lowestSellerName)
1030
            sheet.write(sheet_iterator, 16, snapdealDetails.lowestSp)
1031
            sheet.write(sheet_iterator, 17, snapdealPricing.lowestTp)
1032
            sheet.write(sheet_iterator, 18, snapdealDetails.lowestOfferPrice)
1033
            sheet.write(sheet_iterator, 19, snapdealDetails.otherInventory)
1034
            sheet.write(sheet_iterator, 20, snapdealDetails.ourInventory)
9949 kshitij.so 1035
            if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
11780 kshitij.so 1036
                sheet.write(sheet_iterator, 21, 'Info not available')
9949 kshitij.so 1037
            else:
11780 kshitij.so 1038
                sheet.write(sheet_iterator, 21, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
1039
            sheet.write(sheet_iterator, 22, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
1040
            sheet.write(sheet_iterator, 23, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
1041
            sheet.write(sheet_iterator, 24, snapdealItemInfo.nlc)
1042
            sheet.write(sheet_iterator, 25, snapdealPricing.lowestPossibleTp)
1043
            sheet.write(sheet_iterator, 26, snapdealPricing.lowestPossibleSp)
1044
            sheet.write(sheet_iterator, 27, getSubsidyDiff(snapdealDetails))
9949 kshitij.so 1045
            if (snapdealPricing.competitionBasis=='SP'):
1046
                proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
1047
                proposed_tp = getTargetTp(proposed_sp,mpItem)
1048
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
1049
            else:
10381 manish.sha 1050
                #proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
1051
                #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
1052
                proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001) -getSubsidyDiff(snapdealDetails)
1053
                proposed_tp = getTargetTp(proposed_sp,mpItem)
9949 kshitij.so 1054
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
11780 kshitij.so 1055
            sheet.write(sheet_iterator, 28, round(proposed_tp,2))
1056
            sheet.write(sheet_iterator, 29, round(proposed_sp,2))
1057
            sheet.write(sheet_iterator, 30, round(target_nlc,2))
1058
            sheet.write(sheet_iterator, 31, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
9949 kshitij.so 1059
            sheet_iterator+=1
1060
 
1061
    sheet = wbk.add_sheet('Can Compete-No Inv On SD')
1062
 
1063
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1064
 
1065
    excel_integer_format = '0'
1066
    integer_style = xlwt.XFStyle()
1067
    integer_style.num_format_str = excel_integer_format
1068
    xstr = lambda s: s or ""
1069
 
1070
    sheet.write(0, 0, "Item ID", heading_xf)
1071
    sheet.write(0, 1, "Category", heading_xf)
1072
    sheet.write(0, 2, "Product Group.", heading_xf)
1073
    sheet.write(0, 3, "SUPC", heading_xf)
1074
    sheet.write(0, 4, "Brand", heading_xf)
1075
    sheet.write(0, 5, "Product Name", heading_xf)
1076
    sheet.write(0, 6, "Weight", heading_xf)
1077
    sheet.write(0, 7, "Courier Cost", heading_xf)
1078
    sheet.write(0, 8, "Risky", heading_xf)
11780 kshitij.so 1079
    sheet.write(0, 9, "Commission Rate", heading_xf)
1080
    sheet.write(0, 10, "Return Provision", heading_xf)
1081
    sheet.write(0, 11, "Our SP", heading_xf)
1082
    sheet.write(0, 13, "Our TP", heading_xf)
1083
    sheet.write(0, 12, "Our Offer Price", heading_xf)
1084
    sheet.write(0, 14, "Our Rank", heading_xf)
1085
    sheet.write(0, 15, "Lowest Seller", heading_xf)
1086
    sheet.write(0, 16, "Lowest SP", heading_xf)
1087
    sheet.write(0, 17, "Lowest TP", heading_xf)
1088
    sheet.write(0, 18, "Lowest Offer Price", heading_xf)
1089
    sheet.write(0, 19, "Inventory of Top Vendors", heading_xf)
1090
    sheet.write(0, 20, "Our Snapdeal Inventory", heading_xf)
1091
    sheet.write(0, 21, "Our Net Availability",heading_xf)
1092
    sheet.write(0, 22, "Last Five Day Sale", heading_xf)
1093
    sheet.write(0, 23, "Average Sale", heading_xf)
1094
    sheet.write(0, 24, "Our NLC", heading_xf)
1095
    sheet.write(0, 25, "Lowest Possible TP", heading_xf)
1096
    sheet.write(0, 26, "Lowest Possible SP", heading_xf)
1097
    sheet.write(0, 27, "Subsidy Difference", heading_xf)
1098
    sheet.write(0, 28, "Target TP", heading_xf)
1099
    sheet.write(0, 29, "Target SP", heading_xf)  
1100
    sheet.write(0, 30, "Target NLC", heading_xf)
1101
    sheet.write(0, 31, "Sales Potential", heading_xf)
9949 kshitij.so 1102
 
1103
    sheet_iterator = 1
1104
    for item in competitiveNoInventory:
1105
        snapdealDetails = item[0]
1106
        snapdealItemInfo = item[1]
1107
        snapdealPricing = item[2]
1108
        mpItem = item[3]
11780 kshitij.so 1109
        spmObj = snapdealItemInfo.sourcePercentage
9949 kshitij.so 1110
        if (inventoryMap.has_key(snapdealItemInfo.item_id) and getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id))>0):
1111
            sheet.write(sheet_iterator, 0, snapdealItemInfo.item_id)
1112
            sheet.write(sheet_iterator, 1, snapdealItemInfo.parent_category_name)
1113
            sheet.write(sheet_iterator, 2, snapdealItemInfo.product_group)
1114
            sheet.write(sheet_iterator, 3, snapdealItemInfo.supc)
1115
            sheet.write(sheet_iterator, 4, snapdealItemInfo.brand)
1116
            sheet.write(sheet_iterator, 5, xstr(snapdealItemInfo.brand)+" "+xstr(snapdealItemInfo.model_name)+" "+xstr(snapdealItemInfo.model_number)+" "+xstr(snapdealItemInfo.color))
1117
            sheet.write(sheet_iterator, 6, snapdealItemInfo.weight)
1118
            sheet.write(sheet_iterator, 7, snapdealItemInfo.courierCost)
1119
            sheet.write(sheet_iterator, 8, snapdealItemInfo.risky)
11780 kshitij.so 1120
            sheet.write(sheet_iterator, 9, spmObj.commission)
1121
            sheet.write(sheet_iterator, 10, spmObj.returnProvision)
1122
            sheet.write(sheet_iterator, 11, snapdealPricing.ourSp)
1123
            sheet.write(sheet_iterator, 12, snapdealDetails.ourOfferPrice)
1124
            sheet.write(sheet_iterator, 13, snapdealPricing.ourTp)
1125
            sheet.write(sheet_iterator, 14, snapdealDetails.rank)
1126
            sheet.write(sheet_iterator, 15, snapdealDetails.lowestSellerName)
1127
            sheet.write(sheet_iterator, 16, snapdealDetails.lowestSp)
1128
            sheet.write(sheet_iterator, 17, snapdealPricing.lowestTp)
1129
            sheet.write(sheet_iterator, 18, snapdealDetails.lowestOfferPrice)
1130
            sheet.write(sheet_iterator, 19, snapdealDetails.otherInventory)
1131
            sheet.write(sheet_iterator, 20, snapdealDetails.ourInventory)
9949 kshitij.so 1132
            if (not inventoryMap.has_key(snapdealItemInfo.item_id)):
11780 kshitij.so 1133
                sheet.write(sheet_iterator, 21, 'Info not available')
9949 kshitij.so 1134
            else:
11780 kshitij.so 1135
                sheet.write(sheet_iterator, 21, getNetAvailability(inventoryMap.get(snapdealItemInfo.item_id)))
1136
            sheet.write(sheet_iterator, 22, getOosString((itemSaleMap.get(snapdealItemInfo.item_id))[1]))
1137
            sheet.write(sheet_iterator, 23, (itemSaleMap.get(snapdealItemInfo.item_id))[3])
1138
            sheet.write(sheet_iterator, 24, snapdealItemInfo.nlc)
1139
            sheet.write(sheet_iterator, 25, snapdealPricing.lowestPossibleTp)
1140
            sheet.write(sheet_iterator, 26, snapdealPricing.lowestPossibleSp)
1141
            sheet.write(sheet_iterator, 27, getSubsidyDiff(snapdealDetails))
9949 kshitij.so 1142
            if (snapdealPricing.competitionBasis=='SP'):
1143
                proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
1144
                proposed_tp = getTargetTp(proposed_sp,mpItem)
1145
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
1146
            else:
10381 manish.sha 1147
                #proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
1148
                #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
1149
                proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001) -getSubsidyDiff(snapdealDetails)
1150
                proposed_tp = getTargetTp(proposed_sp,mpItem)
9949 kshitij.so 1151
                target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
11780 kshitij.so 1152
            sheet.write(sheet_iterator, 28, round(proposed_tp,2))
1153
            sheet.write(sheet_iterator, 29, round(proposed_sp,2))
1154
            sheet.write(sheet_iterator, 30, round(target_nlc,2))
1155
            sheet.write(sheet_iterator, 31, getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
9949 kshitij.so 1156
            sheet_iterator+=1
9953 kshitij.so 1157
 
1158
    if (runType=='FULL'):    
1159
        sheet = wbk.add_sheet('Auto Favorites')
1160
 
1161
        heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1162
 
1163
        excel_integer_format = '0'
1164
        integer_style = xlwt.XFStyle()
1165
        integer_style.num_format_str = excel_integer_format
1166
        xstr = lambda s: s or ""
1167
 
1168
        sheet.write(0, 0, "Item ID", heading_xf)
1169
        sheet.write(0, 1, "Brand", heading_xf)
1170
        sheet.write(0, 2, "Product Name", heading_xf)
1171
        sheet.write(0, 3, "Auto Favourite", heading_xf)
1172
        sheet.write(0, 4, "Reason", heading_xf)
1173
 
1174
        sheet_iterator=1
1175
        for autoFav in nowAutoFav:
1176
            itemId = autoFav[0]
1177
            reason = autoFav[1]
1178
            it = Item.query.filter_by(id=itemId).one()
1179
            sheet.write(sheet_iterator, 0, itemId)
1180
            sheet.write(sheet_iterator, 1, it.brand)
1181
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1182
            sheet.write(sheet_iterator, 3, "True")
1183
            sheet.write(sheet_iterator, 4, reason)
1184
            sheet_iterator+=1
1185
        for prevFav in previousAutoFav:
1186
            it = Item.query.filter_by(id=prevFav).one()
1187
            sheet.write(sheet_iterator, 0, prevFav)
1188
            sheet.write(sheet_iterator, 1, it.brand)
1189
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1190
            sheet.write(sheet_iterator, 3, "False")
1191
            sheet_iterator+=1
9949 kshitij.so 1192
 
1193
 
10959 kshitij.so 1194
#    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()
1195
#    sheet = wbk.add_sheet('Auto Inc and Dec')
1196
#
1197
#    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1198
#    
1199
#    excel_integer_format = '0'
1200
#    integer_style = xlwt.XFStyle()
1201
#    integer_style.num_format_str = excel_integer_format
1202
#    xstr = lambda s: s or ""
1203
#    
1204
#    sheet.write(0, 0, "Item ID", heading_xf)
1205
#    sheet.write(0, 1, "Brand", heading_xf)
1206
#    sheet.write(0, 2, "Product Name", heading_xf)
1207
#    sheet.write(0, 3, "Decision", heading_xf)
1208
#    sheet.write(0, 4, "Reason", heading_xf)
1209
#    sheet.write(0, 5, "Old Selling Price", heading_xf)
1210
#    sheet.write(0, 6, "Selling Price Updated",heading_xf)
1211
#    
1212
#    sheet_iterator=1
1213
#    for autoPricingItem in autoPricingItems:
1214
#        mpHistory = autoPricingItem[0]
1215
#        item = autoPricingItem[1]
1216
#        it = Item.query.filter_by(id=item.id).one()
1217
#        sheet.write(sheet_iterator, 0, item.id)
1218
#        sheet.write(sheet_iterator, 1, it.brand)
1219
#        sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1220
#        sheet.write(sheet_iterator, 3, Decision._VALUES_TO_NAMES.get(mpHistory.decision))
1221
#        sheet.write(sheet_iterator, 4, mpHistory.reason)
1222
#        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_DECREMENT_SUCCESS":
1223
#            sheet.write(sheet_iterator, 5, mpHistory.ourSellingPrice)
1224
#            sheet.write(sheet_iterator, 6, math.ceil(mpHistory.proposedSellingPrice))
1225
#        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_INCREMENT_SUCCESS":
1226
#            sheet.write(sheet_iterator, 5, mpHistory.ourSellingPrice)
1227
#            sheet.write(sheet_iterator, 6, math.ceil(mpHistory.ourSellingPrice+max(10,.01*mpHistory.ourSellingPrice)))
1228
#        sheet_iterator+=1
9949 kshitij.so 1229
 
9953 kshitij.so 1230
    filename = "/tmp/snapdeal-report-"+runType+" " + str(timestamp) + ".xls"
9949 kshitij.so 1231
    wbk.save(filename)
10207 kshitij.so 1232
    try:
10293 kshitij.so 1233
        #EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["kshitij.sood@saholic.com"], " Snapdeal Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], [""], [])
11116 kshitij.so 1234
        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","anikendra.das@saholic.com","vikram.raghav@saholic.com","kshitij.sood@saholic.com","chaitnaya.vats@saholic.com","khushal.bhatia@saholic.com"], [])
10207 kshitij.so 1235
    except Exception as e:
1236
        print e
10219 kshitij.so 1237
        print "Unable to send report.Trying with local SMTP"
1238
        smtpServer = smtplib.SMTP('localhost')
1239
        smtpServer.set_debuglevel(1)
11777 kshitij.so 1240
        sender = 'build@shop2020.in'
10293 kshitij.so 1241
        #recipients = ['kshitij.sood@saholic.com']
10219 kshitij.so 1242
        msg = MIMEMultipart()
11753 kshitij.so 1243
        msg['Subject'] = "Snapdeal Auto Pricing " +runType+" " + str(timestamp)
10219 kshitij.so 1244
        msg['From'] = sender
11116 kshitij.so 1245
        recipients = ['rajneesh.arora@saholic.com','anikendra.das@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 1246
        msg['To'] = ",".join(recipients)
10219 kshitij.so 1247
        fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
1248
        fileMsg.set_payload(file(filename).read())
1249
        email.encoders.encode_base64(fileMsg)
1250
        fileMsg.add_header('Content-Disposition','attachment;filename=snapdeal.xls')
1251
        msg.attach(fileMsg)
1252
        try:
1253
            smtpServer.sendmail(sender, recipients, msg.as_string())
1254
            print "Successfully sent email"
1255
        except:
1256
            print "Error: unable to send email."
9881 kshitij.so 1257
 
10219 kshitij.so 1258
 
9881 kshitij.so 1259
def commitExceptionList(exceptionList,timestamp):
9949 kshitij.so 1260
    exceptionItems=[]
9881 kshitij.so 1261
    for item in exceptionList:
1262
        mpHistory = MarketPlaceHistory()
1263
        mpHistory.item_id =item.item_id
1264
        mpHistory.source = OrderSource.SNAPDEAL 
1265
        mpHistory.competitiveCategory = CompetitionCategory.EXCEPTION
1266
        mpHistory.risky = item.risky
1267
        mpHistory.timestamp = timestamp
9949 kshitij.so 1268
        mpHistory.run = RunType._NAMES_TO_VALUES.get(item.runType)
1269
        exceptionItems.append(mpHistory)
9881 kshitij.so 1270
    session.commit()
9949 kshitij.so 1271
    return exceptionItems
9881 kshitij.so 1272
 
1273
def commitNegativeMargin(negativeMargin,timestamp):
9949 kshitij.so 1274
    negativeMarginItems = []
9881 kshitij.so 1275
    for item in negativeMargin:
1276
        snapdealDetails = item[0]
1277
        snapdealItemInfo = item[1]
1278
        snapdealPricing = item[2]
1279
        mpHistory = MarketPlaceHistory()
1280
        mpHistory.item_id = snapdealItemInfo.item_id
1281
        mpHistory.source = OrderSource.SNAPDEAL
1282
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1283
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1284
        mpHistory.ourTp = snapdealPricing.ourTp
9919 kshitij.so 1285
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
12156 kshitij.so 1286
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
9881 kshitij.so 1287
        mpHistory.ourNlc = snapdealItemInfo.nlc
1288
        mpHistory.ourInventory = snapdealDetails.ourInventory
1289
        mpHistory.otherInventory = snapdealDetails.otherInventory
1290
        mpHistory.ourRank = snapdealDetails.rank
9919 kshitij.so 1291
        mpHistory.risky = snapdealItemInfo.risky
1292
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp  
9881 kshitij.so 1293
        mpHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
1294
        mpHistory.totalSeller = snapdealDetails.totalSeller
11060 kshitij.so 1295
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[3]
9881 kshitij.so 1296
        mpHistory.timestamp = timestamp
9949 kshitij.so 1297
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1298
        negativeMarginItems.append(mpHistory) 
9881 kshitij.so 1299
    session.commit()
9949 kshitij.so 1300
    return negativeMarginItems
9881 kshitij.so 1301
 
1302
def commitCompetitive(competitive,timestamp):
9949 kshitij.so 1303
    competitiveItems = []
9881 kshitij.so 1304
    for item in competitive:
1305
        snapdealDetails = item[0]
1306
        snapdealItemInfo = item[1]
1307
        snapdealPricing = item[2]
1308
        mpItem = item[3]
1309
        mpHistory = MarketPlaceHistory()
1310
        mpHistory.item_id = snapdealItemInfo.item_id
1311
        mpHistory.source = OrderSource.SNAPDEAL
1312
        mpHistory.lowestTp = snapdealPricing.lowestTp
1313
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1314
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1315
        mpHistory.ourInventory = snapdealDetails.ourInventory
1316
        mpHistory.otherInventory = snapdealDetails.otherInventory
1317
        mpHistory.ourRank = snapdealDetails.rank
1318
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1319
        mpHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
1320
        mpHistory.risky = snapdealItemInfo.risky
1321
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1322
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1323
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1324
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1325
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1326
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1327
        mpHistory.ourTp = snapdealPricing.ourTp
1328
        mpHistory.ourNlc = snapdealItemInfo.nlc
1329
        if (snapdealPricing.competitionBasis=='SP'):
1330
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
1331
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9954 kshitij.so 1332
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1333
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1334
        else:
10381 manish.sha 1335
            #proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
1336
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
1337
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)) -getSubsidyDiff(snapdealDetails), snapdealPricing.lowestPossibleSp)
1338
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9954 kshitij.so 1339
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1340
            mpHistory.proposedTp = round(proposed_tp,2)
9919 kshitij.so 1341
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1342
        mpHistory.totalSeller = snapdealDetails.totalSeller
11060 kshitij.so 1343
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[3]
9881 kshitij.so 1344
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
1345
        mpHistory.timestamp = timestamp
9949 kshitij.so 1346
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1347
        competitiveItems.append(mpHistory) 
9881 kshitij.so 1348
    session.commit()
9949 kshitij.so 1349
    return competitiveItems
9881 kshitij.so 1350
 
1351
def commitCompetitiveNoInventory(competitiveNoInventory,timestamp):
9949 kshitij.so 1352
    competitiveNoInventoryItems = []
9881 kshitij.so 1353
    for item in competitiveNoInventory:
1354
        snapdealDetails = item[0]
1355
        snapdealItemInfo = item[1]
1356
        snapdealPricing = item[2]
1357
        mpItem = item[3]
1358
        mpHistory = MarketPlaceHistory()
1359
        mpHistory.item_id = snapdealItemInfo.item_id
1360
        mpHistory.source = OrderSource.SNAPDEAL
1361
        mpHistory.lowestTp = snapdealPricing.lowestTp
1362
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1363
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1364
        mpHistory.ourInventory = snapdealDetails.ourInventory
1365
        mpHistory.otherInventory = snapdealDetails.otherInventory
1366
        mpHistory.ourRank = snapdealDetails.rank
1367
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1368
        mpHistory.competitiveCategory = CompetitionCategory.COMPETITIVE_NO_INVENTORY
1369
        mpHistory.risky = snapdealItemInfo.risky
1370
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1371
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1372
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1373
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1374
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1375
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1376
        mpHistory.ourTp = snapdealPricing.ourTp
1377
        mpHistory.ourNlc = snapdealItemInfo.nlc
1378
        if (snapdealPricing.competitionBasis=='SP'):
1379
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
1380
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9954 kshitij.so 1381
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1382
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1383
        else:
10381 manish.sha 1384
            #proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
1385
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
1386
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)) -getSubsidyDiff(snapdealDetails), snapdealPricing.lowestPossibleSp)
1387
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9954 kshitij.so 1388
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1389
            mpHistory.proposedTp = round(proposed_tp,2)
9919 kshitij.so 1390
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1391
        mpHistory.totalSeller = snapdealDetails.totalSeller
11060 kshitij.so 1392
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[3]
9881 kshitij.so 1393
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
1394
        mpHistory.timestamp = timestamp
9949 kshitij.so 1395
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1396
        competitiveNoInventoryItems.append(mpHistory)
9881 kshitij.so 1397
    session.commit()
9949 kshitij.so 1398
    return competitiveNoInventoryItems
9881 kshitij.so 1399
 
1400
def commitCantCompete(cantCompete,timestamp):
9949 kshitij.so 1401
    cantComepeteItems = []
9881 kshitij.so 1402
    for item in cantCompete:
1403
        snapdealDetails = item[0]
1404
        snapdealItemInfo = item[1]
1405
        snapdealPricing = item[2]
1406
        mpItem = item[3]
1407
        mpHistory = MarketPlaceHistory()
1408
        mpHistory.item_id = snapdealItemInfo.item_id
1409
        mpHistory.source = OrderSource.SNAPDEAL
1410
        mpHistory.lowestTp = snapdealPricing.lowestTp
1411
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1412
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1413
        mpHistory.ourInventory = snapdealDetails.ourInventory
1414
        mpHistory.otherInventory = snapdealDetails.otherInventory
1415
        mpHistory.ourRank = snapdealDetails.rank
1416
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1417
        mpHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
1418
        mpHistory.risky = snapdealItemInfo.risky
1419
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1420
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1421
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1422
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1423
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1424
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1425
        mpHistory.ourTp = snapdealPricing.ourTp
1426
        mpHistory.ourNlc = snapdealItemInfo.nlc
1427
        if (snapdealPricing.competitionBasis=='SP'):
1428
            proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
1429
            proposed_tp = getTargetTp(proposed_sp,mpItem)
1430
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1431
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1432
            mpHistory.proposedTp = round(proposed_tp,2)
1433
            mpHistory.targetNlc = round(target_nlc,2)
9881 kshitij.so 1434
        else:
10381 manish.sha 1435
            #proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
1436
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
1437
            proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001) -getSubsidyDiff(snapdealDetails)
1438
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9881 kshitij.so 1439
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1440
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1441
            mpHistory.proposedTp = round(proposed_tp,2)
1442
            mpHistory.targetNlc = round(target_nlc,2)
9919 kshitij.so 1443
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1444
        mpHistory.totalSeller = snapdealDetails.totalSeller
11060 kshitij.so 1445
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[3]
9881 kshitij.so 1446
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
1447
        mpHistory.timestamp = timestamp
9949 kshitij.so 1448
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1449
        cantComepeteItems.append(mpHistory)
9881 kshitij.so 1450
    session.commit()
9949 kshitij.so 1451
    return cantComepeteItems
9881 kshitij.so 1452
 
1453
def commitBuyBox(buyBoxItems,timestamp):
9949 kshitij.so 1454
    buyBoxList = []
9881 kshitij.so 1455
    for item in buyBoxItems:
1456
        snapdealDetails = item[0]
1457
        snapdealItemInfo = item[1]
1458
        snapdealPricing = item[2]
1459
        mpItem = item[3]
1460
        mpHistory = MarketPlaceHistory()
1461
        mpHistory.item_id = snapdealItemInfo.item_id
1462
        mpHistory.source = OrderSource.SNAPDEAL
1463
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
1464
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
1465
        mpHistory.ourInventory = snapdealDetails.ourInventory
1466
        mpHistory.secondLowestInventory = snapdealDetails.secondLowestSellerInventory
1467
        mpHistory.ourRank = snapdealDetails.rank
1468
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
1469
        mpHistory.competitiveCategory = CompetitionCategory.BUY_BOX
1470
        mpHistory.risky = snapdealItemInfo.risky
1471
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
1472
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
1473
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
1474
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
1475
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
1476
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
1477
        mpHistory.ourTp = snapdealPricing.ourTp
1478
        mpHistory.ourNlc = snapdealItemInfo.nlc
1479
        mpHistory.secondLowestSellerName = snapdealDetails.secondLowestSellerName
1480
        mpHistory.secondLowestSellerCode = snapdealDetails.secondLowestSellerCode
9885 kshitij.so 1481
        mpHistory.secondLowestSellingPrice = snapdealDetails.secondLowestSellerSp
9888 kshitij.so 1482
        mpHistory.secondLowestOfferPrice = snapdealDetails.secondLowestSellerOfferPrice
9881 kshitij.so 1483
        mpHistory.secondLowestTp = snapdealPricing.secondLowestSellerTp
1484
        if (snapdealPricing.competitionBasis=='SP'):
1485
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)), snapdealPricing.lowestPossibleSp)
1486
            proposed_tp = getTargetTp(proposed_sp,mpItem)
1487
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1488
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1489
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1490
            #mpHistory.targetNlc = target_nlc
1491
        else:
10381 manish.sha 1492
            #proposed_tp  = max(snapdealPricing.secondLowestSellerTp - max((20, snapdealPricing.secondLowestSellerTp*0.002)), snapdealPricing.lowestPossibleTp)
1493
            #proposed_sp = getTargetSp(proposed_tp,mpItem,snapdealPricing.ourSp)
1494
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)) -getSubsidyDiff(snapdealDetails), snapdealPricing.lowestPossibleSp)
1495
            proposed_tp = getTargetTp(proposed_sp,mpItem)
9881 kshitij.so 1496
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
9954 kshitij.so 1497
            mpHistory.proposedSellingPrice = round(proposed_sp,2)
1498
            mpHistory.proposedTp = round(proposed_tp,2)
9881 kshitij.so 1499
            #mpHistory.targetNlc = target_nlc
9919 kshitij.so 1500
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 1501
        mpHistory.marginIncreasedPotential = proposed_tp - snapdealPricing.ourTp
1502
        mpHistory.totalSeller = snapdealDetails.totalSeller
11060 kshitij.so 1503
        mpHistory.avgSales = (itemSaleMap.get(snapdealItemInfo.item_id))[3]
9881 kshitij.so 1504
        mpHistory.timestamp = timestamp
9949 kshitij.so 1505
        mpHistory.run = RunType._NAMES_TO_VALUES.get(snapdealItemInfo.runType)
1506
        buyBoxList.append(mpHistory)
9881 kshitij.so 1507
    session.commit()
9949 kshitij.so 1508
    return buyBoxList 
10219 kshitij.so 1509
 
9990 kshitij.so 1510
def sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease):
11116 kshitij.so 1511
    if len(successfulAutoDecrease)==0 and len(successfulAutoIncrease)==0 :
1512
        return
9990 kshitij.so 1513
    xstr = lambda s: s or ""
1514
    catalog_client = CatalogClient().get_client()
1515
    inventory_client = InventoryClient().get_client()
1516
    message="""<html>
1517
            <body>
1518
            <h3>Auto Decrease Items</h3>
1519
            <table border="1" style="width:100%;">
1520
            <thead>
1521
            <tr><th>Item Id</th>
1522
            <th>Product Name</th>
1523
            <th>Old Price</th>
1524
            <th>New Price</th>
1525
            <th>Old Margin</th>
1526
            <th>New Margin</th>
11781 kshitij.so 1527
            <th>Commission %</th>
1528
            <th>Return Provision %</th>
9990 kshitij.so 1529
            <th>Snapdeal Inventory</th>
11167 kshitij.so 1530
            <th>Sales History</th>
9990 kshitij.so 1531
            </tr></thead>
1532
            <tbody>"""
1533
    for item in successfulAutoDecrease:
1534
        it = Item.query.filter_by(id=item.item_id).one()
1535
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1536
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1537
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1538
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, item.proposedSellingPrice)
1539
        newMargin = round(getNewOurTp(mpItem,item.proposedSellingPrice) - getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,item.proposedSellingPrice))  
1540
        message+="""<tr>
1541
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
1542
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
1543
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
1544
                <td style="text-align:center">"""+str(math.ceil(item.proposedSellingPrice))+"""</td>
1545
                <td style="text-align:center">"""+str(round(item.margin))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
1546
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/item.proposedSellingPrice)*100,1))+"%)"+"""</td>
11781 kshitij.so 1547
                <td style="text-align:center">"""+str(mpItem.commission)+"""</td>
1548
                <td style="text-align:center">"""+str(mpItem.returnProvision)+" %"+"""</td>
9990 kshitij.so 1549
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
11167 kshitij.so 1550
                <td style="text-align:center">"""+getOosString((itemSaleMap.get(item.item_id))[1])+"""</td>
9990 kshitij.so 1551
                </tr>"""
1552
    message+="""</tbody></table><h3>Auto Increase Items</h3><table border="1" style="width:100%;">
1553
            <thead>
1554
            <tr><th>Item Id</th>
1555
            <th>Product Name</th>
1556
            <th>Old Price</th>
1557
            <th>New Price</th>
1558
            <th>Old Margin</th>
1559
            <th>New Margin</th>
11781 kshitij.so 1560
            <th>Commission %</th>
1561
            <th>Return Provision %</th>
9990 kshitij.so 1562
            <th>Snapdeal Inventory</th>
11167 kshitij.so 1563
            <th>Sales History</th>
9990 kshitij.so 1564
            </tr></thead>
1565
            <tbody>"""
1566
    for item in successfulAutoIncrease:
1567
        it = Item.query.filter_by(id=item.item_id).one()
1568
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1569
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1570
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1571
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
1572
        newMargin = round(getNewOurTp(mpItem,item.ourSellingPrice+max(10,.01*item.ourSellingPrice)) - getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))  
1573
        message+="""<tr>
1574
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
1575
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
1576
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
1577
                <td style="text-align:center">"""+str(math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))+"""</td>
1578
                <td style="text-align:center">"""+str(round((item.margin),1))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
1579
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))*100,1))+"%)"+"""</td>
11781 kshitij.so 1580
                <td style="text-align:center">"""+str(mpItem.commission)+"""</td>
1581
                <td style="text-align:center">"""+str(mpItem.returnProvision)+" %"+"""</td>
9990 kshitij.so 1582
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
11167 kshitij.so 1583
                <td style="text-align:center">"""+getOosString((itemSaleMap.get(item.item_id))[1])+"""</td>
9990 kshitij.so 1584
                </tr>"""
1585
    message+="""</tbody></table></body></html>"""
1586
    print message
1587
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
1588
    mailServer.ehlo()
1589
    mailServer.starttls()
1590
    mailServer.ehlo()
1591
 
10293 kshitij.so 1592
    #recipients = ['kshitij.sood@saholic.com']
11116 kshitij.so 1593
    recipients = ['rajneesh.arora@saholic.com','anikendra.das@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 1594
    msg = MIMEMultipart()
1595
    msg['Subject'] = "Snapdeal Auto Pricing" + ' - ' + str(datetime.now())
1596
    msg['From'] = ""
10005 kshitij.so 1597
    msg['To'] = ",".join(recipients)
9990 kshitij.so 1598
    msg.preamble = "Snapdeal Auto Pricing" + ' - ' + str(datetime.now())
1599
    html_msg = MIMEText(message, 'html')
1600
    msg.attach(html_msg)
10207 kshitij.so 1601
    try:
1602
        mailServer.login("build@shop2020.in", "cafe@nes")
1603
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
1604
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
1605
    except Exception as e:
1606
        print e
10219 kshitij.so 1607
        print "Unable to send pricing mail.Lets try with local SMTP."
1608
        smtpServer = smtplib.SMTP('localhost')
1609
        smtpServer.set_debuglevel(1)
11777 kshitij.so 1610
        sender = 'build@shop2020.in'
10219 kshitij.so 1611
        try:
1612
            smtpServer.sendmail(sender, recipients, msg.as_string())
1613
            print "Successfully sent email"
1614
        except:
1615
            print "Error: unable to send email."
1616
 
9990 kshitij.so 1617
 
1618
def commitPricing(successfulAutoDecrease,successfulAutoIncrease,timestamp):
1619
    catalog_client = CatalogClient().get_client()
1620
    inventory_client = InventoryClient().get_client()
1621
    for item in successfulAutoDecrease:
1622
        it = Item.query.filter_by(id=item.item_id).one()
1623
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1624
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1625
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1626
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, item.proposedSellingPrice)
1627
        addHistory(sdItem)
1628
        sdItem.transferPrice = getNewOurTp(mpItem,item.proposedSellingPrice)
1629
        sdItem.sellingPrice = math.ceil(item.proposedSellingPrice)
10293 kshitij.so 1630
        if ((mpItem.pgFee/100)*sdItem.sellingPrice)>=20:
1631
            sdItem.commission = round((mpItem.commission/100+mpItem.pgFee/100)*(sdItem.sellingPrice),2)
1632
        else:
1633
            sdItem.commission = round((mpItem.commission/100)*(sdItem.sellingPrice),2)+20
11099 kshitij.so 1634
        sdItem.serviceTax = round((mpItem.serviceTax/100)*(sdItem.commission+sdItem.courierCostMarketplace),2)
9990 kshitij.so 1635
        sdItem.updatedOn = timestamp
1636
        sdItem.priceUpdatedBy = 'SYSTEM'
1637
        mpItem.currentSp = sdItem.sellingPrice
1638
        mpItem.currentTp = sdItem.transferPrice
1639
        mpItem.minimumPossibleTp = getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,item.proposedSellingPrice) 
1640
        mpItem.minimumPossibleSp = getNewLowestPossibleSp(mpItem,item.ourNlc,vatRate)
1641
        markStatusForMarketplaceItems(sdItem,mpItem)
1642
    session.commit()
1643
    for item in successfulAutoIncrease:
1644
        it = Item.query.filter_by(id=item.item_id).one()
1645
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
1646
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1647
        warehouse = inventory_client.getWarehouse(sdItem.warehouseId)
1648
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
1649
        addHistory(sdItem)
1650
        sdItem.transferPrice = getNewOurTp(mpItem,item.ourSellingPrice+max(10,.01*item.ourSellingPrice))
1651
        sdItem.sellingPrice = math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice))
10293 kshitij.so 1652
        if ((mpItem.pgFee/100)*sdItem.sellingPrice)>=20:
1653
            sdItem.commission = round((mpItem.commission/100+mpItem.pgFee/100)*(sdItem.sellingPrice),2)
1654
        else:
1655
            sdItem.commission = round((mpItem.commission/100)*(sdItem.sellingPrice),2)+20
11099 kshitij.so 1656
        sdItem.serviceTax = round((mpItem.serviceTax/100)*(sdItem.commission+sdItem.courierCostMarketplace),2)
9990 kshitij.so 1657
        sdItem.updatedOn = timestamp
1658
        sdItem.priceUpdatedBy = 'SYSTEM'
1659
        mpItem.currentSp = sdItem.sellingPrice
1660
        mpItem.currentTp = sdItem.transferPrice
1661
        mpItem.minimumPossibleTp = getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,sdItem.sellingPrice) 
1662
        mpItem.minimumPossibleSp = getNewLowestPossibleSp(mpItem,item.ourNlc,vatRate)
1663
        markStatusForMarketplaceItems(sdItem,mpItem)
1664
    session.commit()
1665
 
10280 kshitij.so 1666
def updatePricesOnSnapdeal(successfulAutoDecrease,successfulAutoIncrease):
10284 kshitij.so 1667
    if syncPrice=='false':
10280 kshitij.so 1668
        return
1669
    url = 'http://support.shop2020.in:8080/Support/reports'
1670
    br = getBrowserObject()
1671
    br.open(url)
1672
    br.select_form(nr=0)
10286 kshitij.so 1673
    br.form['username'] = "manoj"
1674
    br.form['password'] = "man0j"
10280 kshitij.so 1675
    br.submit()
1676
    for item in successfulAutoDecrease:
1677
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1678
        sellingPrice =  str(math.ceil(item.proposedSellingPrice))
1679
        supc = sdItem.supc
10286 kshitij.so 1680
        updateUrl = 'http://support.shop2020.in:8080/Support/snapdeal-list!updateForAutoPricing?sellingPrice=%s&supc=%s&itemId=%s'%(sellingPrice,supc,str(item.item_id))
1681
        br.open(updateUrl)
10280 kshitij.so 1682
    for item in successfulAutoIncrease:
1683
        sdItem = SnapdealItem.get_by(item_id=item.item_id)
1684
        sellingPrice =  str(math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
1685
        supc = sdItem.supc
1686
        updateUrl = 'http://support.shop2020.in:8080/Support/snapdeal-list!updateForAutoPricing?sellingPrice=%s&supc=%s&itemId=%s'%(sellingPrice,supc,str(item.item_id))
1687
        br.open(updateUrl)
1688
 
1689
 
1690
 
9990 kshitij.so 1691
def addHistory(item):
10097 kshitij.so 1692
    itemHistory = MarketPlaceUpdateHistory()
9990 kshitij.so 1693
    itemHistory.item_id = item.item_id
10097 kshitij.so 1694
    itemHistory.source = OrderSource.SNAPDEAL
9990 kshitij.so 1695
    itemHistory.exceptionPrice = item.exceptionPrice
1696
    itemHistory.warehouseId = item.warehouseId
10097 kshitij.so 1697
    itemHistory.isListedOnSource = item.isListedOnSnapdeal
9990 kshitij.so 1698
    itemHistory.transferPrice = item.transferPrice
1699
    itemHistory.sellingPrice = item.sellingPrice
1700
    itemHistory.courierCost = item.courierCost
1701
    itemHistory.commission = item.commission
1702
    itemHistory.serviceTax = item.serviceTax
1703
    itemHistory.suppressPriceFeed = item.suppressPriceFeed
1704
    itemHistory.suppressInventoryFeed = item.suppressInventoryFeed
1705
    itemHistory.updatedOn = item.updatedOn
1706
    itemHistory.maxNlc = item.maxNlc
10097 kshitij.so 1707
    itemHistory.skuAtSource = item.skuAtSnapdeal
1708
    itemHistory.marketPlaceSerialNumber = item.supc
9990 kshitij.so 1709
    itemHistory.priceUpdatedBy = item.priceUpdatedBy
11099 kshitij.so 1710
    itemHistory.courierCostMarketplace = item.courierCostMarketplace
9990 kshitij.so 1711
 
1712
def markStatusForMarketplaceItems(snapdealItem,marketplaceItem):
1713
    markUpdatedItem = MarketPlaceItemPrice.query.filter(MarketPlaceItemPrice.item_id==snapdealItem.item_id).filter(MarketPlaceItemPrice.source==marketplaceItem.source).first()
1714
    if markUpdatedItem is None:
1715
        marketPlaceItemPrice = MarketPlaceItemPrice()
1716
        marketPlaceItemPrice.item_id = snapdealItem.item_id
1717
        marketPlaceItemPrice.source = marketplaceItem.source
1718
        marketPlaceItemPrice.lastUpdatedOn = snapdealItem.updatedOn
1719
        marketPlaceItemPrice.sellingPrice = snapdealItem.sellingPrice 
1720
        marketPlaceItemPrice.suppressPriceFeed = snapdealItem.suppressPriceFeed
1721
        marketPlaceItemPrice.isListedOnSource = snapdealItem.isListedOnSnapdeal
1722
    else:
1723
        if (markUpdatedItem.sellingPrice!=snapdealItem.sellingPrice or markUpdatedItem.suppressPriceFeed!=snapdealItem.suppressPriceFeed or markUpdatedItem.isListedOnSource!=snapdealItem.isListedOnSnapdeal):
1724
            markUpdatedItem.lastUpdatedOn = snapdealItem.updatedOn
1725
        markUpdatedItem.sellingPrice = snapdealItem.sellingPrice
1726
        markUpdatedItem.suppressPriceFeed = snapdealItem.suppressPriceFeed
1727
        markUpdatedItem.isListedOnSource = snapdealItem.isListedOnSnapdeal
10031 kshitij.so 1728
 
1729
def processLostBuyBoxItems(previousProcessingTimestamp,currentTimestamp):
1730
    previous_buy_box = session.query(MarketPlaceHistory.item_id).filter(MarketPlaceHistory.timestamp==previousProcessingTimestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.BUY_BOX).all()
1731
    cant_compete = session.query(MarketPlaceHistory.item_id).filter(MarketPlaceHistory.timestamp==currentTimestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.CANT_COMPETE).all()
12217 kshitij.so 1732
    if previous_buy_box is None or previous_buy_box==[]:
10812 kshitij.so 1733
        print "No item in buy box for last run"
1734
        return
10032 kshitij.so 1735
    lost_buy_box = list(set(list(zip(*previous_buy_box)[0]))&set(list(zip(*cant_compete)[0])))
10031 kshitij.so 1736
    if len(lost_buy_box)==0:
1737
        return
1738
    xstr = lambda s: s or ""
1739
    message="""<html>
1740
            <body>
1741
            <h3>Lost Buy Box</h3>
1742
            <table border="1" style="width:100%;">
1743
            <thead>
1744
            <tr><th>Item Id</th>
1745
            <th>Product Name</th>
1746
            <th>Current Price</th>
1747
            <th>Current TP</th>
1748
            <th>Current Margin</th>
1749
            <th>Competition TP</th>
1750
            <th>Lowest Possible TP</th>
1751
            <th>NLC</th>
1752
            <th>Target NLC</th>
11781 kshitij.so 1753
            <th>Commission %</th>
1754
            <th>Return Provision %</th>
10031 kshitij.so 1755
            <th>Snapdeal Inventory</th>
1756
            <th>Total Inventory</th>
1757
            <th>Sales History</th>
1758
            </tr></thead>
1759
            <tbody>"""
1760
    items = session.query(MarketPlaceHistory).filter(MarketPlaceHistory.timestamp==currentTimestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.item_id.in_(lost_buy_box)).all()
1761
    for item in items:
1762
        it = Item.query.filter_by(id=item.item_id).one()
11781 kshitij.so 1763
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.SNAPDEAL)
10031 kshitij.so 1764
        netInventory=''
1765
        if not inventoryMap.has_key(item.item_id):
1766
            netInventory='Info Not Available'
1767
        else:
1768
            netInventory = str(getNetAvailability(inventoryMap.get(item.item_id)))
1769
        message+="""<tr>
1770
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
1771
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
1772
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
1773
                <td style="text-align:center">"""+str(item.ourTp)+"""</td>
1774
                <td style="text-align:center">"""+str(round(item.margin))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
1775
                <td style="text-align:center">"""+str(item.lowestTp)+"""</td>
1776
                <td style="text-align:center">"""+str(item.lowestPossibleTp)+"""</td>
1777
                <td style="text-align:center">"""+str(item.ourNlc)+"""</td>
1778
                <td style="text-align:center">"""+str(item.targetNlc)+"""</td>
11781 kshitij.so 1779
                <td style="text-align:center">"""+str(mpItem.commission)+"""</td>
1780
                <td style="text-align:center">"""+str(mpItem.returnProvision)+" %"+"""</td>
10031 kshitij.so 1781
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
1782
                <td style="text-align:center">"""+netInventory+"""</td>
1783
                <td style="text-align:center">"""+getOosString((itemSaleMap.get(item.item_id))[1])+"""</td>
1784
                </tr>"""
1785
    message+="""</tbody></table></body></html>"""
1786
    print message
1787
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
1788
    mailServer.ehlo()
1789
    mailServer.starttls()
1790
    mailServer.ehlo()
1791
 
10033 kshitij.so 1792
    #recipients = ['kshitij.sood@saholic.com']
11116 kshitij.so 1793
    recipients = ['rajneesh.arora@saholic.com','anikendra.das@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 1794
    msg = MIMEMultipart()
1795
    msg['Subject'] = "Snapdeal Lost Buy Box" + ' - ' + str(datetime.now())
1796
    msg['From'] = ""
1797
    msg['To'] = ",".join(recipients)
1798
    msg.preamble = "Snapdeal Lost Buy Box" + ' - ' + str(datetime.now())
1799
    html_msg = MIMEText(message, 'html')
1800
    msg.attach(html_msg)
10207 kshitij.so 1801
    try:
1802
        mailServer.login("build@shop2020.in", "cafe@nes")
1803
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
1804
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
1805
    except Exception as e:
1806
        print e
10381 manish.sha 1807
        print "Unable to send lost buy box mail.Lets try local SMTP"
10219 kshitij.so 1808
        smtpServer = smtplib.SMTP('localhost')
1809
        smtpServer.set_debuglevel(1)
11777 kshitij.so 1810
        sender = 'build@shop2020.in'
10219 kshitij.so 1811
        try:
1812
            smtpServer.sendmail(sender, recipients, msg.as_string())
1813
            print "Successfully sent email"
1814
        except:
1815
            print "Error: unable to send email."
1816
 
10381 manish.sha 1817
def getSubsidyDiff(snapdealDetails):
1818
    ourSubsidy = snapdealDetails.ourSp - snapdealDetails.ourOfferPrice
1819
    if snapdealDetails.rank !=1:
1820
        competitionSubsidy = snapdealDetails.lowestSp - snapdealDetails.lowestOfferPrice
1821
    else:
10386 manish.sha 1822
        competitionSubsidy = snapdealDetails.secondLowestSellerSp - snapdealDetails.secondLowestSellerOfferPrice
10381 manish.sha 1823
    return competitionSubsidy - ourSubsidy    
9881 kshitij.so 1824
 
1825
def getOtherTp(snapdealDetails,val,spm):
10473 kshitij.so 1826
    if val.parent_category==10011 or val.parent_category==12001:
9881 kshitij.so 1827
        commissionPercentage = spm.competitorCommissionAccessory
1828
    else:
1829
        commissionPercentage = spm.competitorCommissionOther
1830
    if snapdealDetails.rank==1:
10289 kshitij.so 1831
        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 1832
        return round(otherTp,2)
10289 kshitij.so 1833
    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 1834
    return round(otherTp,2)
9881 kshitij.so 1835
 
1836
def getLowestPossibleTp(snapdealDetails,val,spm,mpItem):
1837
    if snapdealDetails.rank==0:
1838
        return mpItem.minimumPossibleTp
1839
    vat = (snapdealDetails.ourSp/(1+(val.vatRate/100))-(val.nlc/(1+(val.vatRate/100))))*(val.vatRate/100);
12133 kshitij.so 1840
    inHouseCost = mpItem.packagingCost+vat+(mpItem.returnProvision/100)*snapdealDetails.ourSp+mpItem.otherCost;
9881 kshitij.so 1841
    lowest_possible_tp = val.nlc+inHouseCost;
9954 kshitij.so 1842
    return round(lowest_possible_tp,2)
9881 kshitij.so 1843
 
1844
def getOurTp(snapdealDetails,val,spm,mpItem):
1845
    if snapdealDetails.rank==0:
1846
        return mpItem.currentTp
10289 kshitij.so 1847
    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 1848
    return round(ourTp,2)
9966 kshitij.so 1849
 
1850
def getNewLowestPossibleTp(mpItem,nlc,vatRate,proposedSellingPrice):
1851
    vat = (proposedSellingPrice/(1+(vatRate/100))-(nlc/(1+(vatRate/100))))*(vatRate/100);
12133 kshitij.so 1852
    inHouseCost = mpItem.packagingCost+vat+(mpItem.returnProvision/100)*proposedSellingPrice+mpItem.otherCost;
9966 kshitij.so 1853
    lowest_possible_tp = nlc+inHouseCost;
1854
    return round(lowest_possible_tp,2)
1855
 
1856
def getNewOurTp(mpItem,proposedSellingPrice):
11099 kshitij.so 1857
    ourTp = proposedSellingPrice- proposedSellingPrice*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(mpItem.courierCostMarketplace+mpItem.closingFee)*(1+(mpItem.serviceTax/100))-(max(20,(mpItem.pgFee/100)*proposedSellingPrice)*(1+(mpItem.serviceTax/100)));
9966 kshitij.so 1858
    return round(ourTp,2)
9990 kshitij.so 1859
 
1860
def getNewLowestPossibleSp(mpItem,nlc,vatRate):
10294 kshitij.so 1861
    if (mpItem.pgFee/100)*mpItem.currentSp>=20:
12133 kshitij.so 1862
        lowestPossibleSp = (nlc+(mpItem.courierCostMarketplace+mpItem.closingFee)*(1+(mpItem.serviceTax/100))*(1+(vatRate/100))+(mpItem.packagingCost+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));
10289 kshitij.so 1863
    else:
12133 kshitij.so 1864
        lowestPossibleSp = (nlc+(mpItem.courierCostMarketplace+mpItem.closingFee+20)*(1+(mpItem.serviceTax/100))*(1+(vatRate/100))+(mpItem.packagingCost+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 1865
    return round(lowestPossibleSp,2)    
9881 kshitij.so 1866
 
1867
def getLowestPossibleSp(snapdealDetails,val,spm,mpItem):
1868
    if snapdealDetails.rank==0:
1869
        return mpItem.minimumPossibleSp
10289 kshitij.so 1870
    #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));
1871
    if (mpItem.pgFee/100)*snapdealDetails.ourSp>=20:
12133 kshitij.so 1872
        lowestPossibleSp = (val.nlc+(val.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))*(1+(mpItem.vat/100))+(mpItem.packagingCost+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))
10289 kshitij.so 1873
    else:
12133 kshitij.so 1874
        lowestPossibleSp = (val.nlc+(val.courierCost+mpItem.closingFee+20)*(1+(mpItem.serviceTax/100))*(1+(mpItem.vat/100))+(mpItem.packagingCost+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 1875
    return round(lowestPossibleSp,2)    
9881 kshitij.so 1876
 
1877
def getTargetTp(targetSp,mpItem):
11099 kshitij.so 1878
    targetTp = targetSp- targetSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(mpItem.courierCostMarketplace+mpItem.closingFee)*(1+(mpItem.serviceTax/100))-(max(20,(mpItem.pgFee/100)*targetSp)*(1+(mpItem.serviceTax/100)))
9954 kshitij.so 1879
    return round(targetTp,2)
9881 kshitij.so 1880
 
10289 kshitij.so 1881
def getTargetSp(targetTp,mpItem,ourSp):
10292 kshitij.so 1882
    if (ourSp*(mpItem.pgFee/100)) < 20:
11099 kshitij.so 1883
        targetSp = float(targetTp+(mpItem.courierCostMarketplace+mpItem.closingFee+20)*(1+(mpItem.serviceTax/100)))/(1-((mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))))
10289 kshitij.so 1884
    else:
11099 kshitij.so 1885
        targetSp = float(targetTp+(mpItem.courierCostMarkeplace+mpItem.closingFee)*(1+(mpItem.serviceTax/100)))/(1-((mpItem.commission/100+mpItem.emiFee/100+mpItem.pgFee/100)*(1+(mpItem.serviceTax/100))))
9954 kshitij.so 1886
    return round(targetSp,2)
9881 kshitij.so 1887
 
1888
def getSalesPotential(lowestOfferPrice,ourNlc):
1889
    if lowestOfferPrice - ourNlc < 0:
1890
        return 'HIGH'
9897 kshitij.so 1891
    elif (float(lowestOfferPrice - ourNlc))/lowestOfferPrice >=0 and (float(lowestOfferPrice - ourNlc))/lowestOfferPrice <=.02:
9881 kshitij.so 1892
        return 'MEDIUM'
1893
    else:
1894
        return 'LOW'  
1895
 
11041 kshitij.so 1896
def groupData(previousTimestamp,timestampNow):
1897
    previousData = session.query(MarketPlaceHistory).filter(MarketPlaceHistory.timestamp==previousTimestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).all()
1898
    for data in previousData:
11043 kshitij.so 1899
        latestItemData = session.query(MarketPlaceHistory).filter(MarketPlaceHistory.timestamp==timestampNow).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.item_id==data.item_id).first()
11041 kshitij.so 1900
        if latestItemData is None:
1901
            continue
1902
        if data.ourSellingPrice == latestItemData.ourSellingPrice and data.ourOfferPrice == latestItemData.ourOfferPrice and data.competitiveCategory == latestItemData.competitiveCategory:
1903
            if data.toGroup is None:
1904
                data.toGroup=False
1905
                latestItemData.toGroup=True
1906
            else:
1907
                latestItemData.toGroup=True
1908
                data.toGroup=False
1909
        else:
1910
            latestItemData=None
11044 kshitij.so 1911
    session.commit()
11777 kshitij.so 1912
 
1913
def sendAlertForNegativeMargins(timestamp):
1914
    xstr = lambda s: s or ""
1915
    negativeMargins = session.query(MarketPlaceHistory,Item).join((Item,MarketPlaceHistory.item_id==Item.id)).filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.NEGATIVE_MARGIN).all()
1916
    if len(negativeMargins) == 0:
1917
        return
1918
    message="""<html>
1919
            <body>
1920
            <h3 style="color:red;font-weight:bold;">Snapdeal Negative Margins</h3>
1921
            <table border="1" style="width:100%;">
1922
            <thead>
1923
            <tr><th>Item Id</th>
1924
            <th>Product Name</th>
1925
            <th>SP</th>
1926
            <th>TP</th>
1927
            <th>Lowest Possible SP</th>
1928
            <th>Lowest Possible TP</th>
1929
            <th>Margin</th>
1930
            <th>Margin %</th>
11784 kshitij.so 1931
            <th>Commission %</th>
1932
            <th>Return Provision %</th>
11778 kshitij.so 1933
            <th>Snapdeal Inventory</th>
11777 kshitij.so 1934
            <th>Total Inventory</th>
1935
            <th>Sales History</th>
1936
            </tr></thead>
1937
            <tbody>"""
1938
    for item in negativeMargins:
1939
        mpHistory = item[0]
1940
        catItem = item[1]
1941
        netInventory=''
1942
        if not inventoryMap.has_key(mpHistory.item_id):
1943
            netInventory='Info Not Available'
1944
        else:
1945
            netInventory = str(getNetAvailability(inventoryMap.get(mpHistory.item_id)))
11784 kshitij.so 1946
        mpItem = MarketplaceItems.get_by(itemId=mpHistory.item_id,source=OrderSource.SNAPDEAL)
11777 kshitij.so 1947
        message+="""<tr>
1948
            <td style="text-align:center">"""+str(mpHistory.item_id)+"""</td>
1949
            <td style="text-align:center">"""+xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color)+"""</td>
1950
            <td style="text-align:center">"""+str(mpHistory.ourSellingPrice)+"""</td>
1951
            <td style="text-align:center">"""+str(mpHistory.ourTp)+"""</td>
1952
            <td style="text-align:center">"""+str(mpHistory.lowestPossibleSp)+"""</td>
1953
            <td style="text-align:center">"""+str(mpHistory.lowestPossibleTp)+"""</td>
1954
            <td style="text-align:center">"""+str(mpHistory.margin)+"""</td>
11951 kshitij.so 1955
            <td style="text-align:center">"""+str(round((mpHistory.margin/mpHistory.ourSellingPrice)*100,1))+"""</td>
11784 kshitij.so 1956
            <td style="text-align:center">"""+str(mpItem.commission)+"""</td>
1957
            <td style="text-align:center">"""+str(mpItem.returnProvision)+" %"+"""</td>
11777 kshitij.so 1958
            <td style="text-align:center">"""+str(mpHistory.ourInventory)+"""</td>
1959
            <td style="text-align:center">"""+netInventory+"""</td>
1960
            <td style="text-align:center">"""+getOosString((itemSaleMap.get(mpHistory.item_id))[1])+"""</td>
1961
            </tr>"""
1962
    message+="""</tbody></table></body></html>"""
1963
    print message
1964
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
1965
    mailServer.ehlo()
1966
    mailServer.starttls()
1967
    mailServer.ehlo()
1968
 
1969
    #recipients = ['kshitij.sood@saholic.com']
1970
    recipients = ['rajneesh.arora@saholic.com','anikendra.das@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']
1971
    msg = MIMEMultipart()
1972
    msg['Subject'] = "Snapdeal Negative Margin" + ' - ' + str(datetime.now())
1973
    msg['From'] = ""
1974
    msg['To'] = ",".join(recipients)
1975
    msg.preamble = "Snapdeal Negative Margin" + ' - ' + str(datetime.now())
1976
    html_msg = MIMEText(message, 'html')
1977
    msg.attach(html_msg)
1978
    try:
1979
        mailServer.login("build@shop2020.in", "cafe@nes")
1980
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
1981
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
1982
    except Exception as e:
1983
        print e
1984
        print "Unable to send Snapdeal Negative margin mail.Lets try local SMTP"
1985
        smtpServer = smtplib.SMTP('localhost')
1986
        smtpServer.set_debuglevel(1)
1987
        sender = 'build@shop2020.in'
1988
        try:
1989
            smtpServer.sendmail(sender, recipients, msg.as_string())
1990
            print "Successfully sent email"
1991
        except:
1992
            print "Error: unable to send email."
1993
 
12318 kshitij.so 1994
def sendAlertForCompetitiveNoInventory(timestamp):
1995
    xstr = lambda s: s or ""
1996
    competitiveNoInv = session.query(MarketPlaceHistory,Item).join((Item,MarketPlaceHistory.item_id==Item.id)).filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.COMPETITIVE_NO_INVENTORY).all()
1997
    if len(competitiveNoInv) == 0:
1998
        return
1999
    message="""<html>
2000
            <body>
2001
            <h3 style="color:red;font-weight:bold;">Snapdeal Competitive But No Inventory</h3>
2002
            <table border="1" style="width:100%;">
2003
            <thead>
2004
            <tr><th>Item Id</th>
2005
            <th>Product Name</th>
2006
            <th>SP</th>
2007
            <th>TP</th>
2008
            <th>Lowest Possible SP</th>
2009
            <th>Lowest Possible TP</th>
2010
            <th>Lowest Seller</th>
2011
            <th>Lowest Seller SP</th>
2012
            <th>Margin</th>
2013
            <th>Margin %</th>
2014
            <th>Commission %</th>
2015
            <th>Return Provision %</th>
2016
            <th>Snapdeal Inventory</th>
2017
            <th>Total Inventory</th>
2018
            <th>Sales History</th>
2019
            </tr></thead>
2020
            <tbody>"""
2021
    for item in competitiveNoInv:
2022
        mpHistory = item[0]
2023
        catItem = item[1]
2024
        netInventory=''
2025
        if not inventoryMap.has_key(mpHistory.item_id):
2026
            netInventory='Info Not Available'
2027
        else:
2028
            netInventory = str(getNetAvailability(inventoryMap.get(mpHistory.item_id)))
2029
        mpItem = MarketplaceItems.get_by(itemId=mpHistory.item_id,source=OrderSource.SNAPDEAL)
2030
        message+="""<tr>
2031
            <td style="text-align:center">"""+str(mpHistory.item_id)+"""</td>
2032
            <td style="text-align:center">"""+xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color)+"""</td>
2033
            <td style="text-align:center">"""+str(mpHistory.ourSellingPrice)+"""</td>
2034
            <td style="text-align:center">"""+str(mpHistory.ourTp)+"""</td>
2035
            <td style="text-align:center">"""+str(mpHistory.lowestPossibleSp)+"""</td>
2036
            <td style="text-align:center">"""+str(mpHistory.lowestPossibleTp)+"""</td>
2037
            <td style="text-align:center">"""+str(mpHistory.lowestSellerName)+"""</td>
2038
            <td style="text-align:center">"""+str(mpHistory.lowestSellingPrice)+"""</td>
2039
            <td style="text-align:center">"""+str(mpHistory.margin)+"""</td>
2040
            <td style="text-align:center">"""+str(round((mpHistory.margin/mpHistory.ourSellingPrice)*100,1))+" %"+"""</td>
2041
            <td style="text-align:center">"""+str(mpItem.commission)+"""</td>
2042
            <td style="text-align:center">"""+str(mpItem.returnProvision)+" %"+"""</td>
2043
            <td style="text-align:center">"""+str(mpHistory.ourInventory)+"""</td>
2044
            <td style="text-align:center">"""+netInventory+"""</td>
2045
            <td style="text-align:center">"""+getOosString((itemSaleMap.get(mpHistory.item_id))[1])+"""</td>
2046
            </tr>"""
2047
    message+="""</tbody></table></body></html>"""
2048
    print message
2049
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
2050
    mailServer.ehlo()
2051
    mailServer.starttls()
2052
    mailServer.ehlo()
2053
 
2054
    #recipients = ['kshitij.sood@saholic.com']
2055
    recipients = ['rajneesh.arora@saholic.com','anikendra.das@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']
2056
    msg = MIMEMultipart()
2057
    msg['Subject'] = "Snapdeal Competitive But No Inventory" + ' - ' + str(datetime.now())
2058
    msg['From'] = ""
2059
    msg['To'] = ",".join(recipients)
2060
    msg.preamble = "Snapdeal Competitive But No Inventory" + ' - ' + str(datetime.now())
2061
    html_msg = MIMEText(message, 'html')
2062
    msg.attach(html_msg)
2063
    try:
2064
        mailServer.login("build@shop2020.in", "cafe@nes")
2065
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
2066
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
2067
    except Exception as e:
2068
        print e
2069
        print "Unable to send Snapdeal Competitive But No Inventory mail.Lets try local SMTP"
2070
        smtpServer = smtplib.SMTP('localhost')
2071
        smtpServer.set_debuglevel(1)
2072
        sender = 'build@shop2020.in'
2073
        try:
2074
            smtpServer.sendmail(sender, recipients, msg.as_string())
2075
            print "Successfully sent email"
2076
        except:
2077
            print "Error: unable to send email."
2078
 
2079
def sendAlertForInactiveAutoPricing(timestamp):
2080
    xstr = lambda s: s or ""
2081
    inactiveAutoPricing = session.query(MarketPlaceHistory,Item,MarketplaceItems).join((Item,MarketPlaceHistory.item_id==Item.id)).join((MarketplaceItems,MarketPlaceHistory.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).filter(or_(MarketplaceItems.autoDecrement==0,MarketplaceItems.autoIncrement==0)).filter(MarketPlaceHistory.competitiveCategory.in_([CompetitionCategory.BUY_BOX,CompetitionCategory.COMPETITIVE])).all()
2082
    if len(inactiveAutoPricing) == 0:
2083
        return
2084
    message="""<html>
2085
            <body>
12337 kshitij.so 2086
            <h3 style="color:red;font-weight:bold;">Snapdeal Inactive Auto Pricing</h3>
12318 kshitij.so 2087
            <table border="1" style="width:100%;">
2088
            <thead>
2089
            <tr><th>Item Id</th>
2090
            <th>Product Name</th>
2091
            <th>Selling Price</th>
2092
            <th>Competitive Category</th>
2093
            <th>Margin</th>
2094
            <th>Margin %</th>
2095
            <th>Commission %</th>
2096
            <th>Return Provision %</th>
2097
            <th>Snapdeal Inventory</th>
2098
            <th>Total Inventory</th>
2099
            <th>Sales History</th>
12337 kshitij.so 2100
            <th>Action</th>
12318 kshitij.so 2101
            </tr></thead>
2102
            <tbody>"""
2103
    for item in inactiveAutoPricing:
2104
        mpHistory = item[0]
2105
        catItem = item[1]
2106
        mpItem = item[2]
2107
        netInventory=''
2108
        if not inventoryMap.has_key(mpHistory.item_id):
2109
            netInventory='Info Not Available'
2110
        else:
2111
            netInventory = str(getNetAvailability(inventoryMap.get(mpHistory.item_id)))
12337 kshitij.so 2112
        if (mpHistory.competitiveCategory==2):
2113
            decision="Auto Increment"
2114
        elif (mpHistory.competitiveCategory in (3)):
2115
            decision="Auto Decrement"
2116
        else:
2117
            decision=""
12318 kshitij.so 2118
        message+="""<tr>
2119
            <td style="text-align:center">"""+str(mpHistory.item_id)+"""</td>
2120
            <td style="text-align:center">"""+xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color)+"""</td>
2121
            <td style="text-align:center">"""+str(mpHistory.ourSellingPrice)+"""</td>
2122
            <td style="text-align:center">"""+str(CompetitionCategory._VALUES_TO_NAMES.get(mpHistory.competitiveCategory))+"""</td>
2123
            <td style="text-align:center">"""+str(mpHistory.margin)+"""</td>
2124
            <td style="text-align:center">"""+str(round((mpHistory.margin/mpHistory.ourSellingPrice)*100,1))+" %"+"""</td>
2125
            <td style="text-align:center">"""+str(mpItem.commission)+"""</td>
2126
            <td style="text-align:center">"""+str(mpItem.returnProvision)+" %"+"""</td>
2127
            <td style="text-align:center">"""+str(mpHistory.ourInventory)+"""</td>
2128
            <td style="text-align:center">"""+netInventory+"""</td>
2129
            <td style="text-align:center">"""+getOosString((itemSaleMap.get(mpHistory.item_id))[1])+"""</td>
12337 kshitij.so 2130
            <td style="text-align:center">"""+decision+"""</td>
12318 kshitij.so 2131
            </tr>"""
2132
    message+="""</tbody></table></body></html>"""
2133
    print message
2134
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
2135
    mailServer.ehlo()
2136
    mailServer.starttls()
2137
    mailServer.ehlo()
2138
 
2139
    #recipients = ['kshitij.sood@saholic.com']
2140
    recipients = ['rajneesh.arora@saholic.com','anikendra.das@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']
2141
    msg = MIMEMultipart()
2142
    msg['Subject'] = "Snapdeal Auto Pricing Inactive" + ' - ' + str(datetime.now())
2143
    msg['From'] = ""
2144
    msg['To'] = ",".join(recipients)
2145
    msg.preamble = "Snapdeal Auto Pricing Inactive" + ' - ' + str(datetime.now())
2146
    html_msg = MIMEText(message, 'html')
2147
    msg.attach(html_msg)
2148
    try:
2149
        mailServer.login("build@shop2020.in", "cafe@nes")
2150
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
2151
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
2152
    except Exception as e:
2153
        print e
2154
        print "Unable to send Snapdeal Auto Pricing Inactive mail.Lets try local SMTP"
2155
        smtpServer = smtplib.SMTP('localhost')
2156
        smtpServer.set_debuglevel(1)
2157
        sender = 'build@shop2020.in'
2158
        try:
2159
            smtpServer.sendmail(sender, recipients, msg.as_string())
2160
            print "Successfully sent email"
2161
        except:
2162
            print "Error: unable to send email."     
11041 kshitij.so 2163
 
9881 kshitij.so 2164
def main():
9949 kshitij.so 2165
    parser = optparse.OptionParser()
2166
    parser.add_option("-t", "--type", dest="runType",
2167
                   default="FULL", type="string",
2168
                   help="Run type FULL or FAVOURITE")
2169
    (options, args) = parser.parse_args()
2170
    if options.runType not in ('FULL','FAVOURITE'):
2171
        print "Run type argument illegal."
2172
        sys.exit(1)
10289 kshitij.so 2173
    timestamp = datetime.now()
2174
    itemInfo= populateStuff(options.runType,timestamp)
9881 kshitij.so 2175
    cantCompete, buyBoxItems, competitive, \
10289 kshitij.so 2176
    competitiveNoInventory, exceptionList, negativeMargin = decideCategory(itemInfo)
10759 kshitij.so 2177
    previousProcessingTimestamp = session.query(func.max(MarketPlaceHistory.timestamp)).filter(MarketPlaceHistory.source==OrderSource.SNAPDEAL).one()
9949 kshitij.so 2178
    exceptionItems = commitExceptionList(exceptionList,timestamp)
2179
    cantComepeteItems = commitCantCompete(cantCompete,timestamp)
2180
    buyBoxList = commitBuyBox(buyBoxItems,timestamp)
2181
    competitiveItems = commitCompetitive(competitive,timestamp)
2182
    competitiveNoInventoryItems = commitCompetitiveNoInventory(competitiveNoInventory,timestamp)
2183
    negativeMarginItems = commitNegativeMargin(negativeMargin,timestamp)
11045 kshitij.so 2184
    groupData(previousProcessingTimestamp[0],timestamp)
9954 kshitij.so 2185
    successfulAutoDecrease = fetchItemsForAutoDecrease(timestamp)
2186
    successfulAutoIncrease = fetchItemsForAutoIncrease(timestamp)
9949 kshitij.so 2187
    if options.runType=='FULL':
2188
        previousAutoFav, nowAutoFav = markAutoFavourite()
9954 kshitij.so 2189
    if options.runType=='FULL':
2190
        writeReport(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionList, negativeMargin, previousAutoFav, nowAutoFav,timestamp, options.runType)
11780 kshitij.so 2191
        try:
2192
            sendAlertForNegativeMargins(timestamp)
2193
        except Exception as e:
2194
            print "Unable to send neagtive margin alert due to ",e
2195
            pass
9954 kshitij.so 2196
    else:
2197
        writeReport(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionList, negativeMargin, None, None, timestamp, options.runType)
10293 kshitij.so 2198
    commitPricing(successfulAutoDecrease,successfulAutoIncrease,timestamp)
9954 kshitij.so 2199
    sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease)
10031 kshitij.so 2200
    processLostBuyBoxItems(previousProcessingTimestamp[0],timestamp)
10293 kshitij.so 2201
    updatePricesOnSnapdeal(successfulAutoDecrease,successfulAutoIncrease)
12318 kshitij.so 2202
    if options.runType=='FULL':
2203
        sendAlertForCompetitiveNoInventory(timestamp)
2204
        sendAlertForInactiveAutoPricing(timestamp)
9881 kshitij.so 2205
if __name__ == '__main__':
11753 kshitij.so 2206
    main()