Subversion Repositories SmartDukaan

Rev

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

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