Subversion Repositories SmartDukaan

Rev

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