Subversion Repositories SmartDukaan

Rev

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