Subversion Repositories SmartDukaan

Rev

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