Subversion Repositories SmartDukaan

Rev

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