Subversion Repositories SmartDukaan

Rev

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

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