Subversion Repositories SmartDukaan

Rev

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