Subversion Repositories SmartDukaan

Rev

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