Subversion Repositories SmartDukaan

Rev

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

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