Subversion Repositories SmartDukaan

Rev

Rev 11561 | Rev 11563 | 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
 
11562 kshitij.so 778
def decideCategory(itemInfo):
11560 kshitij.so 779
    print "length****",len(itemInfo)
11193 kshitij.so 780
    global itemSaleMap
11560 kshitij.so 781
    global cantCompete 
782
    global buyBoxItems 
783
    global competitive 
784
    global competitiveNoInventory
785
    global exceptionItems
786
    global negativeMargin
787
    global cheapButNotPref
788
    global prefButNotCheap
789
 
11193 kshitij.so 790
    catalog_client = CatalogClient().get_client()
791
    inventory_client = InventoryClient().get_client()
792
 
793
    for val in itemInfo:
794
        spm = val.sourcePercentage
795
        #print "Fetching details of ",val.fkSerialNumber
796
        #flipkartDetails = fetchDetails(val.fkSerialNumber,scraper)
797
        try:
798
            flipkartDetails = fetchDetails(val.fkSerialNumber,scraper)
799
        except Exception as e:
800
            print "Unable to fetch details of",val.fkSerialNumber
801
            print e
802
            exceptionItems.append(val)
803
            continue
804
 
11560 kshitij.so 805
        try:
806
            request_url = "https://api.flipkart.net/sellers/skus/%s/listings"%(str(val.skuAtFlipkart))
807
            r = requests.get(request_url, auth=('m2z93iskuj81qiid', '0c7ab6a5-98c0-4cdc-8be3-72c591e0add4'))
808
            print "Inventory info",r.json()
809
            stock_count = int((r.json()['attributeValues'])['stock_count'])
810
        except:
811
            stock_count = 0
812
 
813
        val.ourFlipkartInventory = stock_count
814
 
11193 kshitij.so 815
        if (flipkartDetails.totalAvailableSeller==0):
816
            exceptionItems.append(val)
817
            continue
818
 
819
        mpItem = MarketplaceItems.get_by(itemId=val.item_id,source=OrderSource.FLIPKART)
820
        warehouse = inventory_client.getWarehouse(val.warehouseId)
821
 
822
        itemSaleList = []
823
        oosForAllSources = inventory_client.getOosStatusesForXDaysForItem(val.item_id, 0, 3)
824
        oosForFlipkart = inventory_client.getOosStatusesForXDaysForItem(val.item_id, OrderSource.FLIPKART, 5)
825
        oosForFlipkartLastDay = inventory_client.getOosStatusesForXDaysForItem(val.item_id, OrderSource.FLIPKART, 1)
826
        itemSaleList.append(oosForAllSources)
827
        itemSaleList.append(oosForFlipkart)
828
        itemSaleList.append(calculateAverageSale(oosForAllSources))
829
        itemSaleList.append(calculateAverageSale(oosForFlipkart))
830
        itemSaleList.append(calculateAverageSale(oosForFlipkartLastDay))
831
        itemSaleList.append(calculateTotalSale(oosForFlipkart))
832
        itemSaleMap[val.item_id]=itemSaleList
833
 
834
        if flipkartDetails.rank==0:
835
            flipkartDetails.ourSp = mpItem.currentSp
836
            ourSp = mpItem.currentSp
837
        else:
838
            ourSp = flipkartDetails.ourSp
839
        vatRate = catalog_client.getVatPercentageForItem(val.item_id, warehouse.stateId, flipkartDetails.ourSp)
840
        val.vatRate = vatRate
841
        if (flipkartDetails.ourBuyTrend == 'PrefCheap') or (flipkartDetails.rank==1 and flipkartDetails.totalAvailableSeller==1):
842
            temp=[]
843
            temp.append(flipkartDetails)
844
            temp.append(val)
845
            secondLowestTp=0 if flipkartDetails.totalAvailableSeller==1 else getOtherTp(flipkartDetails,val,spm,False)
846
            prefSellerTp=0 if flipkartDetails.totalAvailableSeller < 2 else getOtherTp(flipkartDetails,val,spm,True)  
847
            flipkartPricing = __FlipkartPricing(flipkartDetails.ourSp,getOurTp(flipkartDetails,val,spm,mpItem),None,getLowestPossibleTp(flipkartDetails,val,spm,mpItem),secondLowestTp,getLowestPossibleSp(flipkartDetails,val,spm,mpItem),prefSellerTp)
848
            temp.append(flipkartPricing)
849
            temp.append(mpItem)
850
            buyBoxItems.append(temp)
851
            continue
852
 
853
        if (flipkartDetails.ourBuyTrend == 'PrefNCheap'):
854
            temp=[]
855
            temp.append(flipkartDetails)
856
            temp.append(val)
857
            secondLowestTp=0 if flipkartDetails.totalAvailableSeller==1 else getOtherTp(flipkartDetails,val,spm,False)
858
            prefSellerTp=0 if flipkartDetails.totalAvailableSeller < 2 else getOtherTp(flipkartDetails,val,spm,True)  
859
            flipkartPricing = __FlipkartPricing(flipkartDetails.ourSp,getOurTp(flipkartDetails,val,spm,mpItem),None,getLowestPossibleTp(flipkartDetails,val,spm,mpItem),secondLowestTp,getLowestPossibleSp(flipkartDetails,val,spm,mpItem),prefSellerTp)
860
            temp.append(flipkartPricing)
861
            temp.append(mpItem)
862
            prefButNotCheap.append(temp)
863
            continue
864
 
865
        if (flipkartDetails.ourBuyTrend == 'NPrefCheap') and (flipkartDetails.rank==1):
866
            temp=[]
867
            temp.append(flipkartDetails)
868
            temp.append(val)
869
            prefSellerTp=0 if flipkartDetails.totalAvailableSeller < 2 else getOtherTp(flipkartDetails,val,spm,True)  
870
            flipkartPricing = __FlipkartPricing(flipkartDetails.ourSp,getOurTp(flipkartDetails,val,spm,mpItem),None,getLowestPossibleTp(flipkartDetails,val,spm,mpItem),None,getLowestPossibleSp(flipkartDetails,val,spm,mpItem),prefSellerTp)
871
            temp.append(flipkartPricing)
872
            temp.append(mpItem)
873
            cheapButNotPref.append(temp)
874
            continue
875
 
876
 
877
        lowestTp = getOtherTp(flipkartDetails,val,spm,False)
878
        ourTp = getOurTp(flipkartDetails,val,spm,mpItem)
879
        lowestPossibleTp = getLowestPossibleTp(flipkartDetails,val,spm,mpItem)
880
        lowestPossibleSp = getLowestPossibleSp(flipkartDetails,val,spm,mpItem)
881
        prefSellerTp = getOtherTp(flipkartDetails,val,spm,True)
882
 
883
        if (ourTp<lowestPossibleTp):
884
            temp=[]
885
            temp.append(flipkartDetails)
886
            temp.append(val)
887
            flipkartPricing = __FlipkartPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,None,None)
888
            temp.append(flipkartPricing)
889
            negativeMargin.append(temp)
890
            continue
891
 
892
        if (flipkartDetails.lowestSellerSp > lowestPossibleSp) and val.ourFlipkartInventory!=0:
893
            type(val.ourFlipkartInventory)
894
            temp=[]
895
            temp.append(flipkartDetails)
896
            temp.append(val)
897
            flipkartPricing = __FlipkartPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,lowestPossibleSp,prefSellerTp)
898
            temp.append(flipkartPricing)
899
            temp.append(mpItem)
900
            competitive.append(temp)
901
            continue
902
 
903
        if (flipkartDetails.lowestSellerSp) > lowestPossibleSp and val.ourFlipkartInventory==0:
904
            temp=[]
905
            temp.append(flipkartDetails)
906
            temp.append(val)
907
            flipkartPricing = __FlipkartPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,lowestPossibleSp,prefSellerTp)
908
            temp.append(flipkartPricing)
909
            temp.append(mpItem)
910
            competitiveNoInventory.append(temp)
911
            continue
912
 
913
        temp=[]
914
        temp.append(flipkartDetails)
915
        temp.append(val)
916
        flipkartPricing = __FlipkartPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,lowestPossibleSp,prefSellerTp)
917
        temp.append(flipkartPricing)
918
        temp.append(mpItem)
919
        cantCompete.append(temp)
920
 
11560 kshitij.so 921
    #return cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap
11193 kshitij.so 922
 
923
def getOtherTp(flipkartDetails,val,spm,prefferedSeller):
924
    if val.parent_category==10011 or val.parent_category==12001:
925
        commissionPercentage = spm.competitorCommissionAccessory
926
    else:
927
        commissionPercentage = spm.competitorCommissionOther
928
    if flipkartDetails.rank==1 and not prefferedSeller:
929
        otherTp = flipkartDetails.secondLowestSellerSp- flipkartDetails.secondLowestSellerSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100))
930
        return round(otherTp,2)
931
    if prefferedSeller:
932
        otherTp = flipkartDetails.prefSellerSp- flipkartDetails.prefSellerSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100))
933
        return round(otherTp,2)
934
    otherTp = flipkartDetails.lowestSellerSp- flipkartDetails.lowestSellerSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100))
935
    return round(otherTp,2)
936
 
937
def getLowestPossibleTp(flipkartDetails,val,spm,mpItem):
938
    if flipkartDetails.rank==0:
939
        return mpItem.minimumPossibleTp
940
    vat = (flipkartDetails.ourSp/(1+(val.vatRate/100))-(val.nlc/(1+(val.vatRate/100))))*(val.vatRate/100);
941
    inHouseCost = 15+vat+(mpItem.returnProvision/100)*flipkartDetails.ourSp+mpItem.otherCost;
942
    lowest_possible_tp = val.nlc+inHouseCost;
943
    return round(lowest_possible_tp,2)
944
 
945
def getOurTp(flipkartDetails,val,spm,mpItem):
946
    if flipkartDetails.rank==0:
947
        return mpItem.currentTp
948
    ourTp = flipkartDetails.ourSp- flipkartDetails.ourSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(val.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))
949
    return round(ourTp,2)
950
 
951
def getLowestPossibleSp(flipkartDetails,val,spm,mpItem):
952
    if flipkartDetails.rank==0:
953
        return mpItem.minimumPossibleSp
954
    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));
955
    return round(lowestPossibleSp,2)
956
 
957
def getTargetTp(targetSp,mpItem):
958
    targetTp = targetSp- targetSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))
959
    return round(targetTp,2)
960
 
961
def getTargetSp(targetTp,mpItem,ourSp):
962
    targetSp = float(targetTp+(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100)))/(1-((mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))))
963
    return round(targetSp,2)
964
 
965
def markAutoFavourite():
966
    previouslyAutoFav = []
967
    nowAutoFav = []
968
    marketplaceItems = session.query(MarketplaceItems).filter(MarketplaceItems.source==OrderSource.FLIPKART).all()
969
    fromDate = datetime.now()-timedelta(days = 3, hours=datetime.now().hour, minutes=datetime.now().minute, seconds=datetime.now().second)
970
    toDate = datetime.now()-timedelta(days = 0, hours=datetime.now().hour, minutes=datetime.now().minute, seconds=datetime.now().second)
971
    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()
972
    toUpdate = [key for key, value in itemSaleMap.items() if value[5] >= 1]
973
    buyBoxLast3days = []
974
    for item in items:
975
        buyBoxLast3days.append(item[0])
976
    for marketplaceItem in marketplaceItems:
977
        reason = ""
978
        toMark = False
979
        if marketplaceItem.itemId in toUpdate:
980
            toMark = True
981
            reason+="Total sale is greater than 1 for last five days (Flipkart)."
982
        if marketplaceItem.itemId in buyBoxLast3days:
983
            toMark = True
984
            reason+="Item is present in buy box in last 3 days"
985
        if not marketplaceItem.autoFavourite:
986
            print "Item is not under auto favourite"
987
        if toMark:
988
            temp=[]
989
            temp.append(marketplaceItem.itemId)
990
            temp.append(reason)
991
            nowAutoFav.append(temp)
992
        if (not toMark) and marketplaceItem.autoFavourite:
993
            previouslyAutoFav.append(marketplaceItem.itemId)
994
        marketplaceItem.autoFavourite = toMark
995
    session.commit()
996
    return previouslyAutoFav, nowAutoFav
997
 
998
def write_report(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionList, negativeMargin, cheapButNotPref, prefButNotCheap, previousAutoFav, nowAutoFav,timestamp,runType):
999
    wbk = xlwt.Workbook()
1000
    sheet = wbk.add_sheet('Can\'t Compete')
1001
    xstr = lambda s: s or ""
1002
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1003
 
1004
    excel_integer_format = '0'
1005
    integer_style = xlwt.XFStyle()
1006
    integer_style.num_format_str = excel_integer_format
1007
 
1008
    sheet.write(0, 0, "Item ID", heading_xf)
1009
    sheet.write(0, 1, "Category", heading_xf)
1010
    sheet.write(0, 2, "Product Group.", heading_xf)
1011
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1012
    sheet.write(0, 4, "Brand", heading_xf)
1013
    sheet.write(0, 5, "Product Name", heading_xf)
1014
    sheet.write(0, 6, "Weight", heading_xf)
1015
    sheet.write(0, 7, "Courier Cost", heading_xf)
1016
    sheet.write(0, 8, "Risky", heading_xf)
1017
    sheet.write(0, 9, "Our Rating", heading_xf)
1018
    sheet.write(0, 10, "Our Shipping Time", heading_xf)
1019
    sheet.write(0, 11, "Our Rank", heading_xf)
1020
    sheet.write(0, 12, "Our SP", heading_xf)
1021
    sheet.write(0, 13, "Our TP", heading_xf)
1022
    sheet.write(0, 14, "Lowest Seller", heading_xf)
1023
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1024
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
1025
    sheet.write(0, 17, "Lowest Seller SP", heading_xf)
1026
    sheet.write(0, 18, "Lowest Seller TP", heading_xf)
1027
    sheet.write(0, 19, "Preffered Seller", heading_xf)
1028
    sheet.write(0, 20, "Preffered Seller Rating", heading_xf)
1029
    sheet.write(0, 21, "Preffered Seller Shipping Time", heading_xf)
1030
    sheet.write(0, 22, "Preffer Seller SP", heading_xf)
1031
    sheet.write(0, 23, "Preffered Seller TP", heading_xf)
1032
    sheet.write(0, 24, "Our Flipkart Inventory", heading_xf)
1033
    sheet.write(0, 25, "Our Net Availability",heading_xf)
1034
    sheet.write(0, 26, "Last Five Day Sale", heading_xf)
1035
    sheet.write(0, 27, "Average Sale", heading_xf)
1036
    sheet.write(0, 28, "Our NLC", heading_xf)
1037
    sheet.write(0, 29, "Lowest Possible SP", heading_xf)
1038
    sheet.write(0, 30, "Lowest Possible TP", heading_xf)
1039
    sheet.write(0, 31, "Target SP", heading_xf)
1040
    sheet.write(0, 32, "Target TP", heading_xf)  
1041
    sheet.write(0, 33, "Target NLC", heading_xf)
1042
    sheet.write(0, 34, "Sales Potential", heading_xf)
1043
    sheet.write(0, 35, "Total Seller", heading_xf)
1044
    sheet_iterator = 1
1045
    for item in cantCompete:
1046
        flipkartDetails = item[0]
1047
        flipkartItemInfo = item[1]
1048
        flipkartPricing = item[2]
1049
        mpItem = item[3]
1050
        sheet.write(sheet_iterator,0,flipkartItemInfo.item_id)
1051
        sheet.write(sheet_iterator,1,flipkartItemInfo.parent_category_name)
1052
        sheet.write(sheet_iterator,2,flipkartItemInfo.product_group)
1053
        sheet.write(sheet_iterator,3,flipkartItemInfo.fkSerialNumber)
1054
        sheet.write(sheet_iterator,4,flipkartItemInfo.brand)
1055
        sheet.write(sheet_iterator,5,xstr(flipkartItemInfo.brand)+" "+xstr(flipkartItemInfo.model_name)+" "+xstr(flipkartItemInfo.model_number)+" "+xstr(flipkartItemInfo.color))
1056
        sheet.write(sheet_iterator,6,flipkartItemInfo.weight)
1057
        sheet.write(sheet_iterator,7,flipkartItemInfo.courierCost)
1058
        sheet.write(sheet_iterator,8,flipkartItemInfo.risky)
1059
        sheet.write(sheet_iterator,9,flipkartDetails.ourScore)
1060
        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1061
        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
1062
        sheet.write(sheet_iterator,10,ourShippingTime)
1063
        sheet.write(sheet_iterator,11,flipkartDetails.rank)
1064
        sheet.write(sheet_iterator,12,flipkartPricing.ourSp)
1065
        sheet.write(sheet_iterator,13,flipkartPricing.ourTp)
1066
        sheet.write(sheet_iterator,14,flipkartDetails.lowestSellerName)
1067
        sheet.write(sheet_iterator,15,flipkartDetails.lowestSellerScore)
1068
        lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1069
        else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
1070
        sheet.write(sheet_iterator,16,lowestSellerShippingTime)
1071
        sheet.write(sheet_iterator,17,flipkartDetails.lowestSellerSp)
1072
        sheet.write(sheet_iterator,18,flipkartPricing.lowestTp)
1073
        sheet.write(sheet_iterator,19,flipkartDetails.prefSellerName)
1074
        sheet.write(sheet_iterator,20,flipkartDetails.prefSellerScore)
1075
        prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1076
        else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
1077
        sheet.write(sheet_iterator,21,prefferedSellerShippingTime)
1078
        sheet.write(sheet_iterator,22,flipkartDetails.prefSellerSp)
1079
        sheet.write(sheet_iterator,23,flipkartPricing.prefSellerTp)
1080
        sheet.write(sheet_iterator,24,flipkartItemInfo.ourFlipkartInventory)
1081
        if (not inventoryMap.has_key(flipkartItemInfo.item_id)):
1082
            sheet.write(sheet_iterator, 25, 'Info not available')
1083
        else:
1084
            sheet.write(sheet_iterator, 25, getNetAvailability(inventoryMap.get(flipkartItemInfo.item_id)))
1085
        sheet.write(sheet_iterator, 26, getOosString((itemSaleMap.get(flipkartItemInfo.item_id))[1]))
1086
        sheet.write(sheet_iterator, 27, (itemSaleMap.get(flipkartItemInfo.item_id))[3])
1087
        sheet.write(sheet_iterator, 28, flipkartItemInfo.nlc)
1088
        sheet.write(sheet_iterator, 29, flipkartPricing.lowestPossibleSp)
1089
        sheet.write(sheet_iterator, 30, flipkartPricing.lowestPossibleTp)
1090
        proposed_sp = flipkartDetails.lowestSellerSp - max(10, flipkartDetails.lowestSellerSp*0.001)
1091
        proposed_tp = getTargetTp(proposed_sp,mpItem)
1092
        target_nlc = proposed_tp - flipkartPricing.lowestPossibleTp + flipkartItemInfo.nlc
1093
        sheet.write(sheet_iterator, 31, proposed_sp)
1094
        sheet.write(sheet_iterator, 32, proposed_tp)
1095
        sheet.write(sheet_iterator, 33, target_nlc)
1096
        sheet.write(sheet_iterator, 34, getSalesPotential(flipkartDetails.lowestSellerSp,flipkartItemInfo.nlc))
1097
        sheet.write(sheet_iterator, 35, flipkartDetails.totalAvailableSeller)
1098
        sheet_iterator+=1
1099
 
1100
    sheet = wbk.add_sheet('Pref and Cheap')
1101
 
1102
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1103
 
1104
    excel_integer_format = '0'
1105
    integer_style = xlwt.XFStyle()
1106
    integer_style.num_format_str = excel_integer_format
1107
    xstr = lambda s: s or ""
1108
 
1109
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1110
 
1111
    excel_integer_format = '0'
1112
    integer_style = xlwt.XFStyle()
1113
    integer_style.num_format_str = excel_integer_format
1114
 
1115
    sheet.write(0, 0, "Item ID", heading_xf)
1116
    sheet.write(0, 1, "Category", heading_xf)
1117
    sheet.write(0, 2, "Product Group.", heading_xf)
1118
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1119
    sheet.write(0, 4, "Brand", heading_xf)
1120
    sheet.write(0, 5, "Product Name", heading_xf)
1121
    sheet.write(0, 6, "Weight", heading_xf)
1122
    sheet.write(0, 7, "Courier Cost", heading_xf)
1123
    sheet.write(0, 8, "Risky", heading_xf)
1124
    sheet.write(0, 9, "Our Rating", heading_xf)
1125
    sheet.write(0, 10, "Our Shipping Time", heading_xf)
1126
    sheet.write(0, 11, "Our Rank", heading_xf)
1127
    sheet.write(0, 12, "Our SP", heading_xf)
1128
    sheet.write(0, 13, "Our TP", heading_xf)
1129
    sheet.write(0, 14, "Lowest Seller", heading_xf)
1130
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1131
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
1132
    sheet.write(0, 17, "Lowest Seller SP", heading_xf)
1133
    sheet.write(0, 18, "Lowest Seller TP", heading_xf)
1134
    sheet.write(0, 19, "Second Lowest Seller", heading_xf)
1135
    sheet.write(0, 20, "Second Lowest Seller Rating", heading_xf)
1136
    sheet.write(0, 21, "Second Lowest Seller Shipping Time", heading_xf)
1137
    sheet.write(0, 22, "Second Lowest Seller SP", heading_xf)
1138
    sheet.write(0, 23, "Second Lowest Seller TP", heading_xf)
1139
    sheet.write(0, 24, "Our Flipkart Inventory", heading_xf)
1140
    sheet.write(0, 25, "Our Net Availability",heading_xf)
1141
    sheet.write(0, 26, "Last Five Day Sale", heading_xf)
1142
    sheet.write(0, 27, "Average Sale", heading_xf)
1143
    sheet.write(0, 28, "Our NLC", heading_xf)
1144
    sheet.write(0, 29, "Lowest Possible SP", heading_xf)
1145
    sheet.write(0, 30, "Lowest Possible TP", heading_xf)
1146
    sheet.write(0, 31, "Target SP", heading_xf)
1147
    sheet.write(0, 32, "Target TP", heading_xf)  
1148
    sheet.write(0, 33, "Margin Increased Potential", heading_xf)
1149
    sheet.write(0, 34, "Total Seller", heading_xf)
1150
    sheet_iterator = 1
1151
    for item in buyBoxItems:
1152
        flipkartDetails = item[0]
1153
        flipkartItemInfo = item[1]
1154
        flipkartPricing = item[2]
1155
        mpItem = item[3]
1156
        sheet.write(sheet_iterator,0,flipkartItemInfo.item_id)
1157
        sheet.write(sheet_iterator,1,flipkartItemInfo.parent_category_name)
1158
        sheet.write(sheet_iterator,2,flipkartItemInfo.product_group)
1159
        sheet.write(sheet_iterator,3,flipkartItemInfo.fkSerialNumber)
1160
        sheet.write(sheet_iterator,4,flipkartItemInfo.brand)
1161
        sheet.write(sheet_iterator,5,xstr(flipkartItemInfo.brand)+" "+xstr(flipkartItemInfo.model_name)+" "+xstr(flipkartItemInfo.model_number)+" "+xstr(flipkartItemInfo.color))
1162
        sheet.write(sheet_iterator,6,flipkartItemInfo.weight)
1163
        sheet.write(sheet_iterator,7,flipkartItemInfo.courierCost)
1164
        sheet.write(sheet_iterator,8,flipkartItemInfo.risky)
1165
        sheet.write(sheet_iterator,9,flipkartDetails.ourScore)
1166
        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1167
        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
1168
        sheet.write(sheet_iterator,10,ourShippingTime)
1169
        sheet.write(sheet_iterator,11,flipkartDetails.rank)
1170
        sheet.write(sheet_iterator,12,flipkartPricing.ourSp)
1171
        sheet.write(sheet_iterator,13,flipkartPricing.ourTp)
1172
        sheet.write(sheet_iterator,14,flipkartDetails.lowestSellerName)
1173
        sheet.write(sheet_iterator,15,flipkartDetails.lowestSellerScore)
1174
        lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1175
        else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
1176
        sheet.write(sheet_iterator,16,lowestSellerShippingTime)
1177
        sheet.write(sheet_iterator,17,flipkartDetails.lowestSellerSp)
1178
        sheet.write(sheet_iterator,18,flipkartPricing.lowestTp)
1179
        sheet.write(sheet_iterator,19,flipkartDetails.secondLowestSellerName)
1180
        sheet.write(sheet_iterator,20,flipkartDetails.secondLowestSellerScore)
1181
        secondLowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitSecondLowestSeller) if flipkartDetails.shippingTimeUpperLimitSecondLowestSeller==0\
1182
        else str(flipkartDetails.shippingTimeLowerLimitSecondLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitSecondLowestSeller)
1183
        sheet.write(sheet_iterator,21,secondLowestSellerShippingTime)
1184
        sheet.write(sheet_iterator,22,flipkartDetails.secondLowestSellerSp)
1185
        sheet.write(sheet_iterator,23,flipkartPricing.secondLowestSellerTp)
1186
        sheet.write(sheet_iterator,24,flipkartItemInfo.ourFlipkartInventory)
1187
        if (not inventoryMap.has_key(flipkartItemInfo.item_id)):
1188
            sheet.write(sheet_iterator, 25, 'Info not available')
1189
        else:
1190
            sheet.write(sheet_iterator, 25, getNetAvailability(inventoryMap.get(flipkartItemInfo.item_id)))
1191
        sheet.write(sheet_iterator, 26, getOosString((itemSaleMap.get(flipkartItemInfo.item_id))[1]))
1192
        sheet.write(sheet_iterator, 27, (itemSaleMap.get(flipkartItemInfo.item_id))[3])
1193
        sheet.write(sheet_iterator, 28, flipkartItemInfo.nlc)
1194
        sheet.write(sheet_iterator, 29, flipkartPricing.lowestPossibleSp)
1195
        sheet.write(sheet_iterator, 30, flipkartPricing.lowestPossibleTp)
1196
        proposed_sp = max(flipkartDetails.secondLowestSellerSp - max((20, flipkartDetails.secondLowestSellerSp*0.002)), flipkartPricing.lowestPossibleSp)
1197
        proposed_tp = getTargetTp(proposed_sp,mpItem)
1198
        target_nlc = proposed_tp - flipkartPricing.lowestPossibleTp + flipkartItemInfo.nlc
1199
        sheet.write(sheet_iterator, 31, proposed_sp)
1200
        sheet.write(sheet_iterator, 32, proposed_tp)
1201
        sheet.write(sheet_iterator, 33, proposed_tp - flipkartPricing.ourTp)
1202
        sheet.write(sheet_iterator, 34, flipkartDetails.totalAvailableSeller)
1203
        sheet_iterator+=1
1204
 
1205
 
1206
    sheet = wbk.add_sheet('PREF BUT NOT CHEAP')
1207
 
1208
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1209
 
1210
    excel_integer_format = '0'
1211
    integer_style = xlwt.XFStyle()
1212
    integer_style.num_format_str = excel_integer_format
1213
    xstr = lambda s: s or ""
1214
 
1215
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1216
 
1217
    excel_integer_format = '0'
1218
    integer_style = xlwt.XFStyle()
1219
    integer_style.num_format_str = excel_integer_format
1220
 
1221
    sheet.write(0, 0, "Item ID", heading_xf)
1222
    sheet.write(0, 1, "Category", heading_xf)
1223
    sheet.write(0, 2, "Product Group.", heading_xf)
1224
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1225
    sheet.write(0, 4, "Brand", heading_xf)
1226
    sheet.write(0, 5, "Product Name", heading_xf)
1227
    sheet.write(0, 6, "Weight", heading_xf)
1228
    sheet.write(0, 7, "Courier Cost", heading_xf)
1229
    sheet.write(0, 8, "Risky", heading_xf)
1230
    sheet.write(0, 9, "Our Rank", heading_xf)
1231
    sheet.write(0, 10, "Lowest Seller", heading_xf)
1232
    sheet.write(0, 11, "Our Rating", heading_xf)
1233
    sheet.write(0, 12, "Our Shipping Time", heading_xf)
1234
    sheet.write(0, 13, "Our SP", heading_xf)
1235
    sheet.write(0, 14, "Our TP", heading_xf)
1236
    sheet.write(0, 15, "Preffered Seller", heading_xf)
1237
    sheet.write(0, 16, "Preffered Seller Rating", heading_xf)
1238
    sheet.write(0, 17, "Preffered Seller Shipping Time", heading_xf)
1239
    sheet.write(0, 18, "Preffered Seller SP", heading_xf)
1240
    sheet.write(0, 19, "Preffered Seller TP", heading_xf)
1241
    sheet.write(0, 20, "Our Flipkart Inventory", heading_xf)
1242
    sheet.write(0, 21, "Our Net Availability",heading_xf)
1243
    sheet.write(0, 22, "Last Five Day Sale", heading_xf)
1244
    sheet.write(0, 23, "Average Sale", heading_xf)
1245
    sheet.write(0, 24, "Our NLC", heading_xf)
1246
    sheet.write(0, 25, "Lowest Possible SP", heading_xf)
1247
    sheet.write(0, 26, "Lowest Possible TP", heading_xf)
1248
    sheet.write(0, 27, "Total Seller", heading_xf)
1249
    sheet_iterator = 1
1250
    for item in prefButNotCheap:
1251
        flipkartDetails = item[0]
1252
        flipkartItemInfo = item[1]
1253
        flipkartPricing = item[2]
1254
        mpItem = item[3]
1255
        sheet.write(sheet_iterator,0,flipkartItemInfo.item_id)
1256
        sheet.write(sheet_iterator,1,flipkartItemInfo.parent_category_name)
1257
        sheet.write(sheet_iterator,2,flipkartItemInfo.product_group)
1258
        sheet.write(sheet_iterator,3,flipkartItemInfo.fkSerialNumber)
1259
        sheet.write(sheet_iterator,4,flipkartItemInfo.brand)
1260
        sheet.write(sheet_iterator,5,xstr(flipkartItemInfo.brand)+" "+xstr(flipkartItemInfo.model_name)+" "+xstr(flipkartItemInfo.model_number)+" "+xstr(flipkartItemInfo.color))
1261
        sheet.write(sheet_iterator,6,flipkartItemInfo.weight)
1262
        sheet.write(sheet_iterator,7,flipkartItemInfo.courierCost)
1263
        sheet.write(sheet_iterator,8,flipkartItemInfo.risky)
1264
        sheet.write(sheet_iterator,9,flipkartDetails.rank)
1265
        sheet.write(sheet_iterator,10,flipkartDetails.lowestSellerName)
1266
        sheet.write(sheet_iterator,11,flipkartDetails.ourScore)
1267
        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1268
        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
1269
        sheet.write(sheet_iterator,12,ourShippingTime)
1270
        sheet.write(sheet_iterator,13,flipkartPricing.ourSp)
1271
        sheet.write(sheet_iterator,14,flipkartPricing.ourTp)
1272
        sheet.write(sheet_iterator,15,flipkartDetails.prefSellerName)
1273
        sheet.write(sheet_iterator,16,flipkartDetails.prefSellerScore)
1274
        prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1275
        else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
1276
        sheet.write(sheet_iterator,17,prefferedSellerShippingTime)
1277
        sheet.write(sheet_iterator,18,flipkartDetails.prefSellerSp)
1278
        sheet.write(sheet_iterator,19,flipkartPricing.prefSellerTp)
1279
        sheet.write(sheet_iterator,20,flipkartItemInfo.ourFlipkartInventory)
1280
        if (not inventoryMap.has_key(flipkartItemInfo.item_id)):
1281
            sheet.write(sheet_iterator, 21, 'Info not available')
1282
        else:
1283
            sheet.write(sheet_iterator, 21, getNetAvailability(inventoryMap.get(flipkartItemInfo.item_id)))
1284
        sheet.write(sheet_iterator, 22, getOosString((itemSaleMap.get(flipkartItemInfo.item_id))[1]))
1285
        sheet.write(sheet_iterator, 23, (itemSaleMap.get(flipkartItemInfo.item_id))[3])
1286
        sheet.write(sheet_iterator, 24, flipkartItemInfo.nlc)
1287
        sheet.write(sheet_iterator, 25, flipkartPricing.lowestPossibleSp)
1288
        sheet.write(sheet_iterator, 26, flipkartPricing.lowestPossibleTp)
1289
        #proposed_sp = max(flipkartDetails.secondLowestSellerSp - max((20, flipkartDetails.secondLowestSellerSp*0.002)), flipkartPricing.lowestPossibleSp)
1290
        #proposed_tp = getTargetTp(proposed_sp,mpItem)
1291
        #target_nlc = proposed_tp - flipkartPricing.lowestPossibleTp + flipkartItemInfo.nlc
1292
        sheet.write(sheet_iterator, 27, flipkartDetails.totalAvailableSeller)
1293
        sheet_iterator+=1
1294
 
1295
    sheet = wbk.add_sheet('Cheap But Not Pref')
1296
 
1297
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1298
 
1299
    excel_integer_format = '0'
1300
    integer_style = xlwt.XFStyle()
1301
    integer_style.num_format_str = excel_integer_format
1302
    xstr = lambda s: s or ""
1303
 
1304
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1305
 
1306
    excel_integer_format = '0'
1307
    integer_style = xlwt.XFStyle()
1308
    integer_style.num_format_str = excel_integer_format
1309
 
1310
    sheet.write(0, 0, "Item ID", heading_xf)
1311
    sheet.write(0, 1, "Category", heading_xf)
1312
    sheet.write(0, 2, "Product Group.", heading_xf)
1313
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1314
    sheet.write(0, 4, "Brand", heading_xf)
1315
    sheet.write(0, 5, "Product Name", heading_xf)
1316
    sheet.write(0, 6, "Weight", heading_xf)
1317
    sheet.write(0, 7, "Courier Cost", heading_xf)
1318
    sheet.write(0, 8, "Risky", heading_xf)
1319
    sheet.write(0, 9, "Our Rank", heading_xf)
1320
    sheet.write(0, 10, "Lowest Seller", heading_xf)
1321
    sheet.write(0, 11, "Our Rating", heading_xf)
1322
    sheet.write(0, 12, "Our Shipping Time", heading_xf)
1323
    sheet.write(0, 13, "Our SP", heading_xf)
1324
    sheet.write(0, 14, "Our TP", heading_xf)
1325
    sheet.write(0, 15, "Preffered Seller", heading_xf)
1326
    sheet.write(0, 16, "Preffered Seller Rating", heading_xf)
1327
    sheet.write(0, 17, "Preffered Seller Shipping Time", heading_xf)
1328
    sheet.write(0, 18, "Preffered Seller SP", heading_xf)
1329
    sheet.write(0, 19, "Preffered Seller TP", heading_xf)
1330
    sheet.write(0, 20, "Our Flipkart Inventory", heading_xf)
1331
    sheet.write(0, 21, "Our Net Availability",heading_xf)
1332
    sheet.write(0, 22, "Last Five Day Sale", heading_xf)
1333
    sheet.write(0, 23, "Average Sale", heading_xf)
1334
    sheet.write(0, 24, "Our NLC", heading_xf)
1335
    sheet.write(0, 25, "Lowest Possible SP", heading_xf)
1336
    sheet.write(0, 26, "Lowest Possible TP", heading_xf)
1337
    sheet.write(0, 27, "Total Seller", heading_xf)
1338
    sheet_iterator = 1
1339
    for item in cheapButNotPref:
1340
        flipkartDetails = item[0]
1341
        flipkartItemInfo = item[1]
1342
        flipkartPricing = item[2]
1343
        mpItem = item[3]
1344
        sheet.write(sheet_iterator,0,flipkartItemInfo.item_id)
1345
        sheet.write(sheet_iterator,1,flipkartItemInfo.parent_category_name)
1346
        sheet.write(sheet_iterator,2,flipkartItemInfo.product_group)
1347
        sheet.write(sheet_iterator,3,flipkartItemInfo.fkSerialNumber)
1348
        sheet.write(sheet_iterator,4,flipkartItemInfo.brand)
1349
        sheet.write(sheet_iterator,5,xstr(flipkartItemInfo.brand)+" "+xstr(flipkartItemInfo.model_name)+" "+xstr(flipkartItemInfo.model_number)+" "+xstr(flipkartItemInfo.color))
1350
        sheet.write(sheet_iterator,6,flipkartItemInfo.weight)
1351
        sheet.write(sheet_iterator,7,flipkartItemInfo.courierCost)
1352
        sheet.write(sheet_iterator,8,flipkartItemInfo.risky)
1353
        sheet.write(sheet_iterator,9,flipkartDetails.rank)
1354
        sheet.write(sheet_iterator,10,flipkartDetails.lowestSellerName)
1355
        sheet.write(sheet_iterator,11,flipkartDetails.ourScore)
1356
        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1357
        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
1358
        sheet.write(sheet_iterator,12,ourShippingTime)
1359
        sheet.write(sheet_iterator,13,flipkartPricing.ourSp)
1360
        sheet.write(sheet_iterator,14,flipkartPricing.ourTp)
1361
        sheet.write(sheet_iterator,15,flipkartDetails.prefSellerName)
1362
        sheet.write(sheet_iterator,16,flipkartDetails.prefSellerScore)
1363
        prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1364
        else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
1365
        sheet.write(sheet_iterator,17,prefferedSellerShippingTime)
1366
        sheet.write(sheet_iterator,18,flipkartDetails.prefSellerSp)
1367
        sheet.write(sheet_iterator,19,flipkartPricing.prefSellerTp)
1368
        sheet.write(sheet_iterator,20,flipkartItemInfo.ourFlipkartInventory)
1369
        if (not inventoryMap.has_key(flipkartItemInfo.item_id)):
1370
            sheet.write(sheet_iterator, 21, 'Info not available')
1371
        else:
1372
            sheet.write(sheet_iterator, 21, getNetAvailability(inventoryMap.get(flipkartItemInfo.item_id)))
1373
        sheet.write(sheet_iterator, 22, getOosString((itemSaleMap.get(flipkartItemInfo.item_id))[1]))
1374
        sheet.write(sheet_iterator, 23, (itemSaleMap.get(flipkartItemInfo.item_id))[3])
1375
        sheet.write(sheet_iterator, 24, flipkartItemInfo.nlc)
1376
        sheet.write(sheet_iterator, 25, flipkartPricing.lowestPossibleSp)
1377
        sheet.write(sheet_iterator, 26, flipkartPricing.lowestPossibleTp)
1378
        #proposed_sp = max(flipkartDetails.secondLowestSellerSp - max((20, flipkartDetails.secondLowestSellerSp*0.002)), flipkartPricing.lowestPossibleSp)
1379
        #proposed_tp = getTargetTp(proposed_sp,mpItem)
1380
        #target_nlc = proposed_tp - flipkartPricing.lowestPossibleTp + flipkartItemInfo.nlc
1381
        sheet.write(sheet_iterator, 27, flipkartDetails.totalAvailableSeller)
1382
        sheet_iterator+=1
1383
 
1384
    sheet = wbk.add_sheet('Can Compete-With Inventory')
1385
    xstr = lambda s: s or ""
1386
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1387
 
1388
    excel_integer_format = '0'
1389
    integer_style = xlwt.XFStyle()
1390
    integer_style.num_format_str = excel_integer_format
1391
 
1392
    sheet.write(0, 0, "Item ID", heading_xf)
1393
    sheet.write(0, 1, "Category", heading_xf)
1394
    sheet.write(0, 2, "Product Group.", heading_xf)
1395
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1396
    sheet.write(0, 4, "Brand", heading_xf)
1397
    sheet.write(0, 5, "Product Name", heading_xf)
1398
    sheet.write(0, 6, "Weight", heading_xf)
1399
    sheet.write(0, 7, "Courier Cost", heading_xf)
1400
    sheet.write(0, 8, "Risky", heading_xf)
1401
    sheet.write(0, 9, "Our Rating", heading_xf)
1402
    sheet.write(0, 10, "Our Shipping Time", heading_xf)
1403
    sheet.write(0, 11, "Our Rank", heading_xf)
1404
    sheet.write(0, 12, "Our SP", heading_xf)
1405
    sheet.write(0, 13, "Our TP", heading_xf)
1406
    sheet.write(0, 14, "Lowest Seller", heading_xf)
1407
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1408
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
1409
    sheet.write(0, 17, "Lowest Seller SP", heading_xf)
1410
    sheet.write(0, 18, "Lowest Seller TP", heading_xf)
1411
    sheet.write(0, 19, "Preffered Seller", heading_xf)
1412
    sheet.write(0, 20, "Preffered Seller Rating", heading_xf)
1413
    sheet.write(0, 21, "Preffered Seller Shipping Time", heading_xf)
1414
    sheet.write(0, 22, "Preffer Seller SP", heading_xf)
1415
    sheet.write(0, 23, "Preffered Seller TP", heading_xf)
1416
    sheet.write(0, 24, "Our Flipkart Inventory", heading_xf)
1417
    sheet.write(0, 25, "Our Net Availability",heading_xf)
1418
    sheet.write(0, 26, "Last Five Day Sale", heading_xf)
1419
    sheet.write(0, 27, "Average Sale", heading_xf)
1420
    sheet.write(0, 28, "Our NLC", heading_xf)
1421
    sheet.write(0, 29, "Lowest Possible SP", heading_xf)
1422
    sheet.write(0, 30, "Lowest Possible TP", heading_xf)
1423
    sheet.write(0, 31, "Target SP", heading_xf)
1424
    sheet.write(0, 32, "Target TP", heading_xf)  
1425
    sheet.write(0, 33, "Target NLC", heading_xf)
1426
    sheet.write(0, 34, "Sales Potential", heading_xf)
1427
    sheet.write(0, 35, "Total Seller", heading_xf)
1428
    sheet_iterator = 1
1429
    for item in competitive:
1430
        flipkartDetails = item[0]
1431
        flipkartItemInfo = item[1]
1432
        flipkartPricing = item[2]
1433
        mpItem = item[3]
1434
        sheet.write(sheet_iterator,0,flipkartItemInfo.item_id)
1435
        sheet.write(sheet_iterator,1,flipkartItemInfo.parent_category_name)
1436
        sheet.write(sheet_iterator,2,flipkartItemInfo.product_group)
1437
        sheet.write(sheet_iterator,3,flipkartItemInfo.fkSerialNumber)
1438
        sheet.write(sheet_iterator,4,flipkartItemInfo.brand)
1439
        sheet.write(sheet_iterator,5,xstr(flipkartItemInfo.brand)+" "+xstr(flipkartItemInfo.model_name)+" "+xstr(flipkartItemInfo.model_number)+" "+xstr(flipkartItemInfo.color))
1440
        sheet.write(sheet_iterator,6,flipkartItemInfo.weight)
1441
        sheet.write(sheet_iterator,7,flipkartItemInfo.courierCost)
1442
        sheet.write(sheet_iterator,8,flipkartItemInfo.risky)
1443
        sheet.write(sheet_iterator,9,flipkartDetails.ourScore)
1444
        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1445
        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
1446
        sheet.write(sheet_iterator,10,ourShippingTime)
1447
        sheet.write(sheet_iterator,11,flipkartDetails.rank)
1448
        sheet.write(sheet_iterator,12,flipkartPricing.ourSp)
1449
        sheet.write(sheet_iterator,13,flipkartPricing.ourTp)
1450
        sheet.write(sheet_iterator,14,flipkartDetails.lowestSellerName)
1451
        sheet.write(sheet_iterator,15,flipkartDetails.lowestSellerScore)
1452
        lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1453
        else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
1454
        sheet.write(sheet_iterator,16,lowestSellerShippingTime)
1455
        sheet.write(sheet_iterator,17,flipkartDetails.lowestSellerSp)
1456
        sheet.write(sheet_iterator,18,flipkartPricing.lowestTp)
1457
        sheet.write(sheet_iterator,19,flipkartDetails.prefSellerName)
1458
        sheet.write(sheet_iterator,20,flipkartDetails.prefSellerScore)
1459
        prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1460
        else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
1461
        sheet.write(sheet_iterator,21,prefferedSellerShippingTime)
1462
        sheet.write(sheet_iterator,22,flipkartDetails.prefSellerSp)
1463
        sheet.write(sheet_iterator,23,flipkartPricing.prefSellerTp)
1464
        sheet.write(sheet_iterator,24,flipkartItemInfo.ourFlipkartInventory)
1465
        if (not inventoryMap.has_key(flipkartItemInfo.item_id)):
1466
            sheet.write(sheet_iterator, 25, 'Info not available')
1467
        else:
1468
            sheet.write(sheet_iterator, 25, getNetAvailability(inventoryMap.get(flipkartItemInfo.item_id)))
1469
        sheet.write(sheet_iterator, 26, getOosString((itemSaleMap.get(flipkartItemInfo.item_id))[1]))
1470
        sheet.write(sheet_iterator, 27, (itemSaleMap.get(flipkartItemInfo.item_id))[3])
1471
        sheet.write(sheet_iterator, 28, flipkartItemInfo.nlc)
1472
        sheet.write(sheet_iterator, 29, flipkartPricing.lowestPossibleSp)
1473
        sheet.write(sheet_iterator, 30, flipkartPricing.lowestPossibleTp)
1474
        proposed_sp = max(flipkartDetails.lowestSellerSp - max((10, flipkartDetails.lowestSellerSp*0.001)), flipkartPricing.lowestPossibleSp)
1475
        proposed_tp = getTargetTp(proposed_sp,mpItem)
1476
        target_nlc = proposed_tp - flipkartPricing.lowestPossibleTp + flipkartItemInfo.nlc
1477
        sheet.write(sheet_iterator, 31, proposed_sp)
1478
        sheet.write(sheet_iterator, 32, proposed_tp)
1479
        sheet.write(sheet_iterator, 33, target_nlc)
1480
        sheet.write(sheet_iterator, 34, getSalesPotential(flipkartDetails.lowestSellerSp,flipkartItemInfo.nlc))
1481
        sheet.write(sheet_iterator, 35, flipkartDetails.totalAvailableSeller)
1482
        sheet_iterator+=1
1483
 
1484
    sheet = wbk.add_sheet('Negative Margin')
1485
    xstr = lambda s: s or ""
1486
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1487
 
1488
    excel_integer_format = '0'
1489
    integer_style = xlwt.XFStyle()
1490
    integer_style.num_format_str = excel_integer_format
1491
 
1492
    sheet.write(0, 0, "Item ID", heading_xf)
1493
    sheet.write(0, 1, "Category", heading_xf)
1494
    sheet.write(0, 2, "Product Group.", heading_xf)
1495
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1496
    sheet.write(0, 4, "Brand", heading_xf)
1497
    sheet.write(0, 5, "Product Name", heading_xf)
1498
    sheet.write(0, 6, "Weight", heading_xf)
1499
    sheet.write(0, 7, "Courier Cost", heading_xf)
1500
    sheet.write(0, 8, "Risky", heading_xf)
1501
    sheet.write(0, 9, "Our Rating", heading_xf)
1502
    sheet.write(0, 10, "Our Shipping Time", heading_xf)
1503
    sheet.write(0, 11, "Our Rank", heading_xf)
1504
    sheet.write(0, 12, "Our SP", heading_xf)
1505
    sheet.write(0, 13, "Our TP", heading_xf)
1506
    sheet.write(0, 14, "Lowest Seller", heading_xf)
1507
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1508
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
1509
    sheet.write(0, 17, "Lowest Seller SP", heading_xf)
1510
    sheet.write(0, 18, "Lowest Seller TP", heading_xf)
1511
    sheet.write(0, 19, "Preffered Seller", heading_xf)
1512
    sheet.write(0, 20, "Preffered Seller Rating", heading_xf)
1513
    sheet.write(0, 21, "Preffered Seller Shipping Time", heading_xf)
1514
    sheet.write(0, 22, "Preffer Seller SP", heading_xf)
1515
    sheet.write(0, 23, "Preffered Seller TP", heading_xf)
1516
    sheet.write(0, 24, "Our Flipkart Inventory", heading_xf)
1517
    sheet.write(0, 25, "Our Net Availability",heading_xf)
1518
    sheet.write(0, 26, "Last Five Day Sale", heading_xf)
1519
    sheet.write(0, 27, "Average Sale", heading_xf)
1520
    sheet.write(0, 28, "Our NLC", heading_xf)
1521
    sheet.write(0, 29, "Lowest Possible SP", heading_xf)
1522
    sheet.write(0, 30, "Lowest Possible TP", heading_xf)
1523
    sheet.write(0, 31, "Margin", heading_xf)
1524
    sheet.write(0, 32, "Total Seller", heading_xf)
1525
    sheet_iterator = 1
1526
    for item in negativeMargin:
1527
        flipkartDetails = item[0]
1528
        flipkartItemInfo = item[1]
1529
        flipkartPricing = item[2]
1530
        sheet.write(sheet_iterator,0,flipkartItemInfo.item_id)
1531
        sheet.write(sheet_iterator,1,flipkartItemInfo.parent_category_name)
1532
        sheet.write(sheet_iterator,2,flipkartItemInfo.product_group)
1533
        sheet.write(sheet_iterator,3,flipkartItemInfo.fkSerialNumber)
1534
        sheet.write(sheet_iterator,4,flipkartItemInfo.brand)
1535
        sheet.write(sheet_iterator,5,xstr(flipkartItemInfo.brand)+" "+xstr(flipkartItemInfo.model_name)+" "+xstr(flipkartItemInfo.model_number)+" "+xstr(flipkartItemInfo.color))
1536
        sheet.write(sheet_iterator,6,flipkartItemInfo.weight)
1537
        sheet.write(sheet_iterator,7,flipkartItemInfo.courierCost)
1538
        sheet.write(sheet_iterator,8,flipkartItemInfo.risky)
1539
        sheet.write(sheet_iterator,9,flipkartDetails.ourScore)
1540
        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1541
        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
1542
        sheet.write(sheet_iterator,10,ourShippingTime)
1543
        sheet.write(sheet_iterator,11,flipkartDetails.rank)
1544
        sheet.write(sheet_iterator,12,flipkartPricing.ourSp)
1545
        sheet.write(sheet_iterator,13,flipkartPricing.ourTp)
1546
        sheet.write(sheet_iterator,14,flipkartDetails.lowestSellerName)
1547
        sheet.write(sheet_iterator,15,flipkartDetails.lowestSellerScore)
1548
        lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1549
        else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
1550
        sheet.write(sheet_iterator,16,lowestSellerShippingTime)
1551
        sheet.write(sheet_iterator,17,flipkartDetails.lowestSellerSp)
1552
        sheet.write(sheet_iterator,18,flipkartPricing.lowestTp)
1553
        sheet.write(sheet_iterator,19,flipkartDetails.prefSellerName)
1554
        sheet.write(sheet_iterator,20,flipkartDetails.prefSellerScore)
1555
        prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1556
        else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
1557
        sheet.write(sheet_iterator,21,prefferedSellerShippingTime)
1558
        sheet.write(sheet_iterator,22,flipkartDetails.prefSellerSp)
1559
        sheet.write(sheet_iterator,23,flipkartPricing.prefSellerTp)
1560
        sheet.write(sheet_iterator,24,flipkartItemInfo.ourFlipkartInventory)
1561
        if (not inventoryMap.has_key(flipkartItemInfo.item_id)):
1562
            sheet.write(sheet_iterator, 25, 'Info not available')
1563
        else:
1564
            sheet.write(sheet_iterator, 25, getNetAvailability(inventoryMap.get(flipkartItemInfo.item_id)))
1565
        sheet.write(sheet_iterator, 26, getOosString((itemSaleMap.get(flipkartItemInfo.item_id))[1]))
1566
        sheet.write(sheet_iterator, 27, (itemSaleMap.get(flipkartItemInfo.item_id))[3])
1567
        sheet.write(sheet_iterator, 28, flipkartItemInfo.nlc)
1568
        sheet.write(sheet_iterator, 29, flipkartPricing.lowestPossibleSp)
1569
        sheet.write(sheet_iterator, 30, flipkartPricing.lowestPossibleTp)
1570
        sheet.write(sheet_iterator, 31, round((flipkartPricing.ourTp - flipkartPricing.lowestPossibleTp),2))
1571
        sheet.write(sheet_iterator, 32, flipkartDetails.totalAvailableSeller)
1572
        sheet_iterator+=1
1573
 
1574
    if (runType=='FULL'):    
1575
        sheet = wbk.add_sheet('Auto Favorites')
1576
 
1577
        heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1578
 
1579
        excel_integer_format = '0'
1580
        integer_style = xlwt.XFStyle()
1581
        integer_style.num_format_str = excel_integer_format
1582
        xstr = lambda s: s or ""
1583
 
1584
        sheet.write(0, 0, "Item ID", heading_xf)
1585
        sheet.write(0, 1, "Brand", heading_xf)
1586
        sheet.write(0, 2, "Product Name", heading_xf)
1587
        sheet.write(0, 3, "Auto Favourite", heading_xf)
1588
        sheet.write(0, 4, "Reason", heading_xf)
1589
 
1590
        sheet_iterator=1
1591
        for autoFav in nowAutoFav:
1592
            itemId = autoFav[0]
1593
            reason = autoFav[1]
1594
            it = Item.query.filter_by(id=itemId).one()
1595
            sheet.write(sheet_iterator, 0, itemId)
1596
            sheet.write(sheet_iterator, 1, it.brand)
1597
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1598
            sheet.write(sheet_iterator, 3, "True")
1599
            sheet.write(sheet_iterator, 4, reason)
1600
            sheet_iterator+=1
1601
        for prevFav in previousAutoFav:
1602
            it = Item.query.filter_by(id=prevFav).one()
1603
            sheet.write(sheet_iterator, 0, prevFav)
1604
            sheet.write(sheet_iterator, 1, it.brand)
1605
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1606
            sheet.write(sheet_iterator, 3, "False")
1607
            sheet_iterator+=1
1608
 
1609
    sheet = wbk.add_sheet('Exception Item List')
1610
 
1611
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1612
 
1613
    excel_integer_format = '0'
1614
    integer_style = xlwt.XFStyle()
1615
    integer_style.num_format_str = excel_integer_format
1616
    xstr = lambda s: s or ""
1617
 
1618
    sheet.write(0, 0, "Item ID", heading_xf)
1619
    sheet.write(0, 1, "FK Serial number", heading_xf)
1620
    sheet.write(0, 2, "Brand", heading_xf)
1621
    sheet.write(0, 3, "Product Name", heading_xf)
1622
    sheet.write(0, 4, "Reason", heading_xf)
1623
    sheet_iterator=1
1624
    for item in exceptionList:
1625
        sheet.write(sheet_iterator, 0, item.item_id)
1626
        sheet.write(sheet_iterator, 1, item.fkSerialNumber)
1627
        sheet.write(sheet_iterator, 2, item.brand)
1628
        sheet.write(sheet_iterator, 3, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1629
        try:
1630
            if item.totalAvailableSeller is None:
1631
                pass
1632
        except:
1633
            sheet.write(sheet_iterator, 4, "Unable to fetch info from Flipkart")
1634
            sheet_iterator+=1
1635
            continue
1636
        sheet.write(sheet_iterator, 4, "No Seller Available")
1637
        sheet_iterator+=1
1638
 
1639
    sheet = wbk.add_sheet('Can Compete-No Inv')
1640
    xstr = lambda s: s or ""
1641
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1642
 
1643
    excel_integer_format = '0'
1644
    integer_style = xlwt.XFStyle()
1645
    integer_style.num_format_str = excel_integer_format
1646
 
1647
    sheet.write(0, 0, "Item ID", heading_xf)
1648
    sheet.write(0, 1, "Category", heading_xf)
1649
    sheet.write(0, 2, "Product Group.", heading_xf)
1650
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1651
    sheet.write(0, 4, "Brand", heading_xf)
1652
    sheet.write(0, 5, "Product Name", heading_xf)
1653
    sheet.write(0, 6, "Weight", heading_xf)
1654
    sheet.write(0, 7, "Courier Cost", heading_xf)
1655
    sheet.write(0, 8, "Risky", heading_xf)
1656
    sheet.write(0, 9, "Our Rating", heading_xf)
1657
    sheet.write(0, 10, "Our Shipping Time", heading_xf)
1658
    sheet.write(0, 11, "Our Rank", heading_xf)
1659
    sheet.write(0, 12, "Our SP", heading_xf)
1660
    sheet.write(0, 13, "Our TP", heading_xf)
1661
    sheet.write(0, 14, "Lowest Seller", heading_xf)
1662
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1663
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
1664
    sheet.write(0, 17, "Lowest Seller SP", heading_xf)
1665
    sheet.write(0, 18, "Lowest Seller TP", heading_xf)
1666
    sheet.write(0, 19, "Preffered Seller", heading_xf)
1667
    sheet.write(0, 20, "Preffered Seller Rating", heading_xf)
1668
    sheet.write(0, 21, "Preffered Seller Shipping Time", heading_xf)
1669
    sheet.write(0, 22, "Preffer Seller SP", heading_xf)
1670
    sheet.write(0, 23, "Preffered Seller TP", heading_xf)
1671
    sheet.write(0, 24, "Our Flipkart Inventory", heading_xf)
1672
    sheet.write(0, 25, "Our Net Availability",heading_xf)
1673
    sheet.write(0, 26, "Last Five Day Sale", heading_xf)
1674
    sheet.write(0, 27, "Average Sale", heading_xf)
1675
    sheet.write(0, 28, "Our NLC", heading_xf)
1676
    sheet.write(0, 29, "Lowest Possible SP", heading_xf)
1677
    sheet.write(0, 30, "Lowest Possible TP", heading_xf)
1678
    sheet.write(0, 31, "Target SP", heading_xf)
1679
    sheet.write(0, 32, "Target TP", heading_xf)  
1680
    sheet.write(0, 33, "Sales Potential", heading_xf)
1681
    sheet.write(0, 34, "Total Seller", heading_xf)
1682
    sheet_iterator = 1
1683
    for item in competitiveNoInventory:
1684
        flipkartDetails = item[0]
1685
        flipkartItemInfo = item[1]
1686
        flipkartPricing = item[2]
1687
        mpItem = item[3]
1688
        if ((not inventoryMap.has_key(flipkartItemInfo.item_id)) or getNetAvailability(inventoryMap.get(flipkartItemInfo.item_id))<=0):
1689
            sheet.write(sheet_iterator,0,flipkartItemInfo.item_id)
1690
            sheet.write(sheet_iterator,1,flipkartItemInfo.parent_category_name)
1691
            sheet.write(sheet_iterator,2,flipkartItemInfo.product_group)
1692
            sheet.write(sheet_iterator,3,flipkartItemInfo.fkSerialNumber)
1693
            sheet.write(sheet_iterator,4,flipkartItemInfo.brand)
1694
            sheet.write(sheet_iterator,5,xstr(flipkartItemInfo.brand)+" "+xstr(flipkartItemInfo.model_name)+" "+xstr(flipkartItemInfo.model_number)+" "+xstr(flipkartItemInfo.color))
1695
            sheet.write(sheet_iterator,6,flipkartItemInfo.weight)
1696
            sheet.write(sheet_iterator,7,flipkartItemInfo.courierCost)
1697
            sheet.write(sheet_iterator,8,flipkartItemInfo.risky)
1698
            sheet.write(sheet_iterator,9,flipkartDetails.ourScore)
1699
            ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1700
            else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
1701
            sheet.write(sheet_iterator,10,ourShippingTime)
1702
            sheet.write(sheet_iterator,11,flipkartDetails.rank)
1703
            sheet.write(sheet_iterator,12,flipkartPricing.ourSp)
1704
            sheet.write(sheet_iterator,13,flipkartPricing.ourTp)
1705
            sheet.write(sheet_iterator,14,flipkartDetails.lowestSellerName)
1706
            sheet.write(sheet_iterator,15,flipkartDetails.lowestSellerScore)
1707
            lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1708
            else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
1709
            sheet.write(sheet_iterator,16,lowestSellerShippingTime)
1710
            sheet.write(sheet_iterator,17,flipkartDetails.lowestSellerSp)
1711
            sheet.write(sheet_iterator,18,flipkartPricing.lowestTp)
1712
            sheet.write(sheet_iterator,19,flipkartDetails.prefSellerName)
1713
            sheet.write(sheet_iterator,20,flipkartDetails.prefSellerScore)
1714
            prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1715
            else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
1716
            sheet.write(sheet_iterator,21,prefferedSellerShippingTime)
1717
            sheet.write(sheet_iterator,22,flipkartDetails.prefSellerSp)
1718
            sheet.write(sheet_iterator,23,flipkartPricing.prefSellerTp)
1719
            sheet.write(sheet_iterator,24,flipkartItemInfo.ourFlipkartInventory)
1720
            if (not inventoryMap.has_key(flipkartItemInfo.item_id)):
1721
                sheet.write(sheet_iterator, 25, 'Info not available')
1722
            else:
1723
                sheet.write(sheet_iterator, 25, getNetAvailability(inventoryMap.get(flipkartItemInfo.item_id)))
1724
            sheet.write(sheet_iterator, 26, getOosString((itemSaleMap.get(flipkartItemInfo.item_id))[1]))
1725
            sheet.write(sheet_iterator, 27, (itemSaleMap.get(flipkartItemInfo.item_id))[3])
1726
            sheet.write(sheet_iterator, 28, flipkartItemInfo.nlc)
1727
            sheet.write(sheet_iterator, 29, flipkartPricing.lowestPossibleSp)
1728
            sheet.write(sheet_iterator, 30, flipkartPricing.lowestPossibleTp)
1729
            proposed_sp = max(flipkartDetails.lowestSellerSp - max((10, flipkartDetails.lowestSellerSp*0.001)), flipkartPricing.lowestPossibleSp)
1730
            proposed_tp = getTargetTp(proposed_sp,mpItem)
1731
            sheet.write(sheet_iterator, 31, proposed_sp)
1732
            sheet.write(sheet_iterator, 32, proposed_tp)
1733
            sheet.write(sheet_iterator, 33, getSalesPotential(flipkartDetails.lowestSellerSp,flipkartItemInfo.nlc))
1734
            sheet.write(sheet_iterator, 34, flipkartDetails.totalAvailableSeller)
1735
            sheet_iterator+=1
1736
 
1737
    sheet = wbk.add_sheet('Can Compete-No Inv On FK')
1738
    xstr = lambda s: s or ""
1739
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1740
 
1741
    excel_integer_format = '0'
1742
    integer_style = xlwt.XFStyle()
1743
    integer_style.num_format_str = excel_integer_format
1744
 
1745
    sheet.write(0, 0, "Item ID", heading_xf)
1746
    sheet.write(0, 1, "Category", heading_xf)
1747
    sheet.write(0, 2, "Product Group.", heading_xf)
1748
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1749
    sheet.write(0, 4, "Brand", heading_xf)
1750
    sheet.write(0, 5, "Product Name", heading_xf)
1751
    sheet.write(0, 6, "Weight", heading_xf)
1752
    sheet.write(0, 7, "Courier Cost", heading_xf)
1753
    sheet.write(0, 8, "Risky", heading_xf)
1754
    sheet.write(0, 9, "Our Rating", heading_xf)
1755
    sheet.write(0, 10, "Our Shipping Time", heading_xf)
1756
    sheet.write(0, 11, "Our Rank", heading_xf)
1757
    sheet.write(0, 12, "Our SP", heading_xf)
1758
    sheet.write(0, 13, "Our TP", heading_xf)
1759
    sheet.write(0, 14, "Lowest Seller", heading_xf)
1760
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1761
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
1762
    sheet.write(0, 17, "Lowest Seller SP", heading_xf)
1763
    sheet.write(0, 18, "Lowest Seller TP", heading_xf)
1764
    sheet.write(0, 19, "Preffered Seller", heading_xf)
1765
    sheet.write(0, 20, "Preffered Seller Rating", heading_xf)
1766
    sheet.write(0, 21, "Preffered Seller Shipping Time", heading_xf)
1767
    sheet.write(0, 22, "Preffer Seller SP", heading_xf)
1768
    sheet.write(0, 23, "Preffered Seller TP", heading_xf)
1769
    sheet.write(0, 24, "Our Flipkart Inventory", heading_xf)
1770
    sheet.write(0, 25, "Our Net Availability",heading_xf)
1771
    sheet.write(0, 26, "Last Five Day Sale", heading_xf)
1772
    sheet.write(0, 27, "Average Sale", heading_xf)
1773
    sheet.write(0, 28, "Our NLC", heading_xf)
1774
    sheet.write(0, 29, "Lowest Possible SP", heading_xf)
1775
    sheet.write(0, 30, "Lowest Possible TP", heading_xf)
1776
    sheet.write(0, 31, "Target SP", heading_xf)
1777
    sheet.write(0, 32, "Target TP", heading_xf)  
1778
    sheet.write(0, 33, "Sales Potential", heading_xf)
1779
    sheet.write(0, 34, "Total Seller", heading_xf)
1780
    sheet_iterator = 1
1781
    for item in competitiveNoInventory:
1782
        flipkartDetails = item[0]
1783
        flipkartItemInfo = item[1]
1784
        flipkartPricing = item[2]
1785
        mpItem = item[3]
1786
        if (inventoryMap.has_key(flipkartItemInfo.item_id) and getNetAvailability(inventoryMap.get(flipkartItemInfo.item_id))>0):
1787
            sheet.write(sheet_iterator,0,flipkartItemInfo.item_id)
1788
            sheet.write(sheet_iterator,1,flipkartItemInfo.parent_category_name)
1789
            sheet.write(sheet_iterator,2,flipkartItemInfo.product_group)
1790
            sheet.write(sheet_iterator,3,flipkartItemInfo.fkSerialNumber)
1791
            sheet.write(sheet_iterator,4,flipkartItemInfo.brand)
1792
            sheet.write(sheet_iterator,5,xstr(flipkartItemInfo.brand)+" "+xstr(flipkartItemInfo.model_name)+" "+xstr(flipkartItemInfo.model_number)+" "+xstr(flipkartItemInfo.color))
1793
            sheet.write(sheet_iterator,6,flipkartItemInfo.weight)
1794
            sheet.write(sheet_iterator,7,flipkartItemInfo.courierCost)
1795
            sheet.write(sheet_iterator,8,flipkartItemInfo.risky)
1796
            sheet.write(sheet_iterator,9,flipkartDetails.ourScore)
1797
            ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1798
            else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
1799
            sheet.write(sheet_iterator,10,ourShippingTime)
1800
            sheet.write(sheet_iterator,11,flipkartDetails.rank)
1801
            sheet.write(sheet_iterator,12,flipkartPricing.ourSp)
1802
            sheet.write(sheet_iterator,13,flipkartPricing.ourTp)
1803
            sheet.write(sheet_iterator,14,flipkartDetails.lowestSellerName)
1804
            sheet.write(sheet_iterator,15,flipkartDetails.lowestSellerScore)
1805
            lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1806
            else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
1807
            sheet.write(sheet_iterator,16,lowestSellerShippingTime)
1808
            sheet.write(sheet_iterator,17,flipkartDetails.lowestSellerSp)
1809
            sheet.write(sheet_iterator,18,flipkartPricing.lowestTp)
1810
            sheet.write(sheet_iterator,19,flipkartDetails.prefSellerName)
1811
            sheet.write(sheet_iterator,20,flipkartDetails.prefSellerScore)
1812
            prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1813
            else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
1814
            sheet.write(sheet_iterator,21,prefferedSellerShippingTime)
1815
            sheet.write(sheet_iterator,22,flipkartDetails.prefSellerSp)
1816
            sheet.write(sheet_iterator,23,flipkartPricing.prefSellerTp)
1817
            sheet.write(sheet_iterator,24,flipkartItemInfo.ourFlipkartInventory)
1818
            if (not inventoryMap.has_key(flipkartItemInfo.item_id)):
1819
                sheet.write(sheet_iterator, 25, 'Info not available')
1820
            else:
1821
                sheet.write(sheet_iterator, 25, getNetAvailability(inventoryMap.get(flipkartItemInfo.item_id)))
1822
            sheet.write(sheet_iterator, 26, getOosString((itemSaleMap.get(flipkartItemInfo.item_id))[1]))
1823
            sheet.write(sheet_iterator, 27, (itemSaleMap.get(flipkartItemInfo.item_id))[3])
1824
            sheet.write(sheet_iterator, 28, flipkartItemInfo.nlc)
1825
            sheet.write(sheet_iterator, 29, flipkartPricing.lowestPossibleSp)
1826
            sheet.write(sheet_iterator, 30, flipkartPricing.lowestPossibleTp)
1827
            proposed_sp = max(flipkartDetails.lowestSellerSp - max((10, flipkartDetails.lowestSellerSp*0.001)), flipkartPricing.lowestPossibleSp)
1828
            proposed_tp = getTargetTp(proposed_sp,mpItem)
1829
            sheet.write(sheet_iterator, 31, proposed_sp)
1830
            sheet.write(sheet_iterator, 32, proposed_tp)
1831
            sheet.write(sheet_iterator, 33, getSalesPotential(flipkartDetails.lowestSellerSp,flipkartItemInfo.nlc))
1832
            sheet.write(sheet_iterator, 34, flipkartDetails.totalAvailableSeller)
1833
            sheet_iterator+=1
1834
 
1835
    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()
1836
    sheet = wbk.add_sheet('Auto Inc and Dec')
1837
 
1838
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1839
 
1840
    excel_integer_format = '0'
1841
    integer_style = xlwt.XFStyle()
1842
    integer_style.num_format_str = excel_integer_format
1843
    xstr = lambda s: s or ""
1844
 
1845
    sheet.write(0, 0, "Item ID", heading_xf)
1846
    sheet.write(0, 1, "Brand", heading_xf)
1847
    sheet.write(0, 2, "Product Name", heading_xf)
1848
    sheet.write(0, 3, "Decision", heading_xf)
1849
    sheet.write(0, 4, "Reason", heading_xf)
1850
    sheet.write(0, 5, "Old Selling Price", heading_xf)
1851
    sheet.write(0, 6, "Selling Price Updated",heading_xf)
1852
 
1853
    sheet_iterator=1
1854
    for autoPricingItem in autoPricingItems:
1855
        mpHistory = autoPricingItem[0]
1856
        item = autoPricingItem[1]
1857
        it = Item.query.filter_by(id=item.id).one()
1858
        sheet.write(sheet_iterator, 0, item.id)
1859
        sheet.write(sheet_iterator, 1, it.brand)
1860
        sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1861
        sheet.write(sheet_iterator, 3, Decision._VALUES_TO_NAMES.get(mpHistory.decision))
1862
        sheet.write(sheet_iterator, 4, mpHistory.reason)
1863
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_DECREMENT_SUCCESS":
1864
            sheet.write(sheet_iterator, 5, mpHistory.ourSellingPrice)
1865
            sheet.write(sheet_iterator, 6, math.ceil(mpHistory.proposedSellingPrice))
1866
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_INCREMENT_SUCCESS":
1867
            sheet.write(sheet_iterator, 5, mpHistory.ourSellingPrice)
1868
            sheet.write(sheet_iterator, 6, math.ceil(mpHistory.ourSellingPrice+max(10,.01*mpHistory.ourSellingPrice)))
1869
        sheet_iterator+=1
1870
 
1871
    filename = "/tmp/flipkart-report-"+runType+" " + str(timestamp) + ".xls"
1872
    wbk.save(filename)
1873
    try:
11560 kshitij.so 1874
        EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["kshitij.sood@saholic.com"], " Flipkart Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], [""], [])
1875
        #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 1876
    except Exception as e:
1877
        print e
1878
        print "Unable to send report.Trying with local SMTP"
1879
        smtpServer = smtplib.SMTP('localhost')
1880
        smtpServer.set_debuglevel(1)
1881
        sender = 'support@shop2020.in'
11560 kshitij.so 1882
        recipients = ["kshitij.sood@saholic.com"]
11193 kshitij.so 1883
        msg = MIMEMultipart()
11228 kshitij.so 1884
        msg['Subject'] = "Flipkart Scraping" + ' '+runType+' - ' + str(datetime.now())
11193 kshitij.so 1885
        msg['From'] = sender
11560 kshitij.so 1886
        #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 1887
        msg['To'] = ",".join(recipients)
1888
        fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
1889
        fileMsg.set_payload(file(filename).read())
1890
        email.encoders.encode_base64(fileMsg)
1891
        fileMsg.add_header('Content-Disposition','attachment;filename=flipkart.xls')
1892
        msg.attach(fileMsg)
1893
        try:
1894
            smtpServer.sendmail(sender, recipients, msg.as_string())
1895
            print "Successfully sent email"
1896
        except:
1897
            print "Error: unable to send email."
11560 kshitij.so 1898
 
1899
def test(start,end):
1900
    print "Start "+str(start)+" end"+str(end)
1901
 
1902
def threadsToSpawn(runType,itemInfo,scraper,itemPopulated):
1903
    global threads
1904
    if runType == RunType.FAVOURITE:
1905
        startOffset = itemPopulated
1906
        endOffset = startOffset
1907
        while(len(threads)< 3 and endOffset<len(itemInfo)):
1908
            endOffset = startOffset + 20
1909
            if (endOffset >= len(itemInfo)):
1910
                endOffset = len(itemInfo)
11562 kshitij.so 1911
            t = threading.Thread(target=partial(decideCategory, itemInfo[startOffset:endOffset]))
11560 kshitij.so 1912
            #t = threading.Thread(target=partial(test, startOffset, endOffset))
1913
            threads.append(t)
1914
            startOffset = startOffset + 20
1915
        [t.start() for t in threads]
1916
        [t.join() for t in threads] 
1917
        threads = []
1918
        return endOffset
1919
    else:
11561 kshitij.so 1920
        count = 0
1921
        pool = ThreadPool(5)
11560 kshitij.so 1922
        startOffset = itemPopulated
1923
        endOffset = startOffset
11561 kshitij.so 1924
        while(count<10 and endOffset<len(itemInfo)):
11560 kshitij.so 1925
            endOffset = startOffset + 50
1926
            if (endOffset >= len(itemInfo)):
1927
                endOffset = len(itemInfo)
11562 kshitij.so 1928
            pool.map(decideCategory,itemInfo[startOffset:endOffset])
11561 kshitij.so 1929
            #t = Process(target=decideCategory,args=(itemInfo[startOffset:endOffset], scraper))
11560 kshitij.so 1930
            #t = threading.Thread(target=partial(decideCategory, itemInfo[startOffset:endOffset], scraper))
1931
            #t = threading.Thread(target=partial(test, startOffset, endOffset))
11561 kshitij.so 1932
            #threads.append(t)
11560 kshitij.so 1933
            startOffset = startOffset + 50
11561 kshitij.so 1934
            count+=1
1935
        #[t.start() for t in threads]
1936
        #[t.join() for t in threads] 
1937
        #threads = []
11560 kshitij.so 1938
        return endOffset
1939
 
1940
 
11193 kshitij.so 1941
def main():
1942
    parser = optparse.OptionParser()
1943
    parser.add_option("-t", "--type", dest="runType",
1944
                   default="FULL", type="string",
1945
                   help="Run type FULL or FAVOURITE")
1946
    (options, args) = parser.parse_args()
1947
    if options.runType not in ('FULL','FAVOURITE'):
1948
        print "Run type argument illegal."
1949
        sys.exit(1)
1950
    timestamp = datetime.now()
1951
    itemInfo= populateStuff(options.runType,timestamp)
11560 kshitij.so 1952
    itemsPopulated = 0
1953
    while (itemsPopulated<len(itemInfo)):
1954
        itemsPopulated = threadsToSpawn(options.runType,itemInfo,scraper,itemsPopulated)
11193 kshitij.so 1955
    previousProcessingTimestamp = session.query(func.max(MarketPlaceHistory.timestamp)).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).one()
11560 kshitij.so 1956
    commitExceptionList(exceptionItems,timestamp)
1957
    commitCantCompete(cantCompete,timestamp)
1958
    commitBuyBox(buyBoxItems,timestamp)
1959
    commitCompetitive(competitive,timestamp)
1960
    commitCompetitiveNoInventory(competitiveNoInventory,timestamp)
1961
    commitNegativeMargin(negativeMargin,timestamp)
1962
    commitCheapButNotPref(cheapButNotPref,timestamp)
1963
    commitPrefButNotCheap(prefButNotCheap, timestamp)
1964
    #getLastUpdatedOn(mailSender.start, mailSender.stop)
11193 kshitij.so 1965
    #successfulAutoDecrease = fetchItemsForAutoDecrease(timestamp)
1966
    #successfulAutoIncrease = fetchItemsForAutoIncrease(timestamp)
1967
    if options.runType=='FULL':
1968
        previousAutoFav, nowAutoFav = markAutoFavourite()
1969
    if options.runType=='FULL':
11560 kshitij.so 1970
        write_report(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap, previousAutoFav, nowAutoFav,timestamp, options.runType)
11193 kshitij.so 1971
    else:
11560 kshitij.so 1972
        write_report(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap, None, None, timestamp, options.runType)
11193 kshitij.so 1973
 
1974
 
1975
if __name__ == '__main__':
1976
    main()