Subversion Repositories SmartDukaan

Rev

Rev 11967 | Rev 11969 | 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:
11825 kshitij.so 136
#        if not autoDecrementItem.risky:
137
#            markReasonForMpItem(autoDecrementItem,'Item is not risky',Decision.AUTO_DECREMENT_FAILED)
138
#            continue
11193 kshitij.so 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")
11825 kshitij.so 168
        if daysOfStock<2 and autoDecrementItem.risky:
11193 kshitij.so 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]
11619 kshitij.so 571
        mpItem = item[3]
11193 kshitij.so 572
        mpHistory = MarketPlaceHistory()
573
        mpHistory.item_id = flipkartItemInfo.item_id
574
        mpHistory.source = OrderSource.FLIPKART
575
        mpHistory.lowestTp = flipkartPricing.lowestTp
576
        mpHistory.lowestPossibleTp = flipkartPricing.lowestPossibleTp
577
        mpHistory.lowestPossibleSp = flipkartPricing.lowestPossibleSp
578
        mpHistory.ourInventory = flipkartItemInfo.ourFlipkartInventory
579
        mpHistory.ourRank = flipkartDetails.rank
580
        mpHistory.competitiveCategory = CompetitionCategory.PREF_BUT_NOT_CHEAP
581
        mpHistory.risky = flipkartItemInfo.risky
582
        mpHistory.lowestSellingPrice = flipkartDetails.lowestSellerSp
583
        mpHistory.lowestSellerName = flipkartDetails.lowestSellerName
584
        mpHistory.lowestSellerCode = flipkartDetails.lowestSellerCode
585
        mpHistory.lowestSellerRating = flipkartDetails.lowestSellerScore
586
        mpHistory.lowestSellerShippingTime = ''
587
        mpHistory.lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
588
        else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
589
        mpHistory.ourSellingPrice = flipkartPricing.ourSp
590
        mpHistory.ourTp = flipkartPricing.ourTp
591
        mpHistory.ourNlc = flipkartItemInfo.nlc
592
        mpHistory.ourRating = flipkartDetails.ourScore
593
        mpHistory.ourShippingTime = ''
594
        mpHistory.ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
595
        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
596
        mpHistory.prefferedSellerName = flipkartDetails.prefSellerName
597
        mpHistory.prefferedSellerCode = flipkartDetails.prefSellerCode
598
        mpHistory.prefferedSellerRating = flipkartDetails.prefSellerScore
599
        mpHistory.prefferedSellerSellingPrice = flipkartDetails.prefSellerSp
600
        mpHistory.prefferedSellerTp = flipkartPricing.prefSellerTp
601
        mpHistory.prefferedSellerShippingTime = ''
602
        mpHistory.prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
603
        else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
604
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
11775 kshitij.so 605
        proposed_sp = max(flipkartDetails.lowestSellerSp - max((10, flipkartDetails.lowestSellerSp*0.001)), flipkartPricing.lowestPossibleSp)
11619 kshitij.so 606
        proposed_tp = getTargetTp(proposed_sp,mpItem)
607
        mpHistory.proposedSellingPrice = proposed_sp
608
        mpHistory.proposedTp = proposed_tp  
11193 kshitij.so 609
        mpHistory.totalSeller = flipkartDetails.totalAvailableSeller
610
        mpHistory.avgSales = (itemSaleMap.get(flipkartItemInfo.item_id))[3]
611
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(flipkartDetails.lowestSellerSp,flipkartItemInfo.nlc))
612
        mpHistory.timestamp = timestamp
613
        mpHistory.run = RunType._NAMES_TO_VALUES.get(flipkartItemInfo.runType)
614
    session.commit()
615
 
616
def populateStuff(runType,time):
11581 kshitij.so 617
    global itemSaleMap
11615 kshitij.so 618
    global categoryMap
619
 
11193 kshitij.so 620
    itemInfo = []
621
    if runType=='FAVOURITE':
622
        items = session.query(FlipkartItem,MarketplaceItems).join((MarketplaceItems,FlipkartItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.FLIPKART).\
623
        filter(or_(MarketplaceItems.autoFavourite==True, MarketplaceItems.manualFavourite==True)).all()
624
    else:
625
        #items = session.query(FlipkartItem,MarketplaceItems).join((MarketplaceItems,FlipkartItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.FLIPKART).all()
626
        items = session.query(FlipkartItem,MarketplaceItems).join((MarketplaceItems,FlipkartItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.FLIPKART).all()
11581 kshitij.so 627
 
628
    inventory_client = InventoryClient().get_client()
629
 
11193 kshitij.so 630
    for item in items:
631
        flipkart_item = item[0]
632
        mp_item = item[1]
633
        it = Item.query.filter_by(id=flipkart_item.item_id).one()
634
        category = Category.query.filter_by(id=it.category).one()
635
        parent_category = Category.query.filter_by(id=category.parent_category_id).first()
11615 kshitij.so 636
        if not categoryMap.has_key(category.id):
637
            temp = []
11616 kshitij.so 638
            temp.append(category.display_name)
639
            temp.append(parent_category.display_name)
11615 kshitij.so 640
            categoryMap[category.id] = temp
11193 kshitij.so 641
        sip = SourceItemPercentage.query.filter(SourceItemPercentage.item_id==it.id).filter(SourceItemPercentage.source==OrderSource.FLIPKART).filter(SourceItemPercentage.startDate<=time).filter(SourceItemPercentage.expiryDate>=time).first()
642
        sourcePercentage = None
643
        if sip is not None:
644
            sourcePercentage = sip
645
        else:
646
            scp = SourceCategoryPercentage.query.filter(SourceCategoryPercentage.category_id==it.category).filter(SourceCategoryPercentage.source==OrderSource.FLIPKART).filter(SourceCategoryPercentage.startDate<=time).filter(SourceCategoryPercentage.expiryDate>=time).first()
647
            if scp is not None:
648
                sourcePercentage = scp
649
            else:
650
                spm = SourcePercentageMaster.get_by(source=OrderSource.FLIPKART)
651
                sourcePercentage = spm
11581 kshitij.so 652
 
653
        warehouse = inventory_client.getWarehouse(flipkart_item.warehouseId)    
654
        itemSaleList = []
655
        oosForAllSources = inventory_client.getOosStatusesForXDaysForItem(flipkart_item.item_id, 0, 3)
656
        oosForFlipkart = inventory_client.getOosStatusesForXDaysForItem(flipkart_item.item_id, OrderSource.FLIPKART, 5)
657
        oosForFlipkartLastDay = inventory_client.getOosStatusesForXDaysForItem(flipkart_item.item_id, OrderSource.FLIPKART, 1)
11615 kshitij.so 658
        oosForFlipkartTwoDay = inventory_client.getOosStatusesForXDaysForItem(flipkart_item.item_id, OrderSource.FLIPKART, 2)
11581 kshitij.so 659
        itemSaleList.append(oosForAllSources)
660
        itemSaleList.append(oosForFlipkart)
661
        itemSaleList.append(calculateAverageSale(oosForAllSources))
662
        itemSaleList.append(calculateAverageSale(oosForFlipkart))
663
        itemSaleList.append(calculateAverageSale(oosForFlipkartLastDay))
664
        itemSaleList.append(calculateTotalSale(oosForFlipkart))
11615 kshitij.so 665
        itemSaleList.append(calculateAverageSale(oosForFlipkartTwoDay))
11581 kshitij.so 666
        itemSaleMap[flipkart_item.item_id]=itemSaleList
667
 
11560 kshitij.so 668
#        try:
669
#            request_url = "https://api.flipkart.net/sellers/skus/%s/listings"%(str(flipkart_item.skuAtFlipkart))
670
#            r = requests.get(request_url, auth=('m2z93iskuj81qiid', '0c7ab6a5-98c0-4cdc-8be3-72c591e0add4'))
671
#            print "Inventory info",r.json()
672
#            stock_count = int((r.json()['attributeValues'])['stock_count'])
673
#        except:
674
#            stock_count = 0
11581 kshitij.so 675
        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 676
        itemInfo.append(flipkartItemInfo)
677
    return itemInfo
678
 
679
def fetchDetails(flipkartSerialNumber,scraper):
680
    url = "http://www.flipkart.com/ps/%s"%(flipkartSerialNumber)
681
    #url = "http://www.flipkart.com/ps/MOBDTXVZXVY3GFG8"
682
    scraper.read(url)
683
    vendorsData = scraper.createData()
684
    sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
11968 kshitij.so 685
    vendorsData[:]=[]
11193 kshitij.so 686
    rank ,ourSp, iterator, secondLowestSellerSp, prefSellerSp, lowestSellerSp, lowestSellerScore, prefSellerScore, secondLowestSellerScore, ourScore, shippingTimeLowerLimitLowestSeller,shippingTimeUpperLimitLowestSeller, \
687
    shippingTimeLowerLimitPrefSeller, shippingTimeUpperLimitPrefSeller, shippingTimeLowerLimitOur, shippingTimeUpperLimitOur, shippingTimeLowerLimitSecondLowestSeller, shippingTimeUpperLimitSecondLowestSeller, totalAvailableSeller= (0,)*19
688
    lowestSellerName, lowestSellerCode, secondLowestSellerName, secondLowestSellerCode, prefSellerName, prefSellerCode, lowestSellerBuyTrend, \
689
    ourBuyTrend, prefSellerBuyTrend, secondLowestSellerBuyTrend, ourCode = ('',)*11
690
    for data in sortedVendorsData:
691
        if iterator == 0:
692
            lowestSellerName = data['sellerName']
693
            lowestSellerScore = data['sellerScore']
694
            lowestSellerCode = data['sellerCode']
695
            lowestSellerSp = data['sellingPrice']
696
            lowestSellerBuyTrend = data['buyTrend']
697
            try:
698
                shippingTimeLowerLimitLowestSeller, shippingTimeUpperLimitLowestSeller = data['shippingTime'].split('-')
699
            except ValueError:
700
                shippingTimeLowerLimitLowestSeller = int(data['shippingTime'])
701
 
702
        if iterator ==1:
703
            secondLowestSellerName = data['sellerName']
704
            secondLowestSellerScore = data['sellerScore']
705
            secondLowestSellerCode = data['sellerCode']
706
            secondLowestSellerSp = data['sellingPrice']
707
            secondLowestSellerBuyTrend = data['buyTrend']
708
            try:
709
                shippingTimeLowerLimitSecondLowestSeller, shippingTimeUpperLimitSecondLowestSeller = data['shippingTime'].split('-')
710
            except ValueError:
711
                shippingTimeLowerLimitSecondLowestSeller = int(data['shippingTime'])
712
 
713
        if data['sellerName'] == 'Saholic':
714
            ourScore = data['sellerScore']
715
            ourCode = data['sellerCode']
716
            ourSp = data['sellingPrice']
717
            ourBuyTrend = data['buyTrend']
718
            try:
719
                shippingTimeLowerLimitOur, shippingTimeUpperLimitOur = data['shippingTime'].split('-')
720
            except ValueError:
721
                shippingTimeLowerLimitOur = int(data['shippingTime'])
722
            rank = iterator + 1
723
 
724
        if data['buyTrend'] in ('PrefCheap','PrefNCheap',''):
725
            prefSellerName = data['sellerName']
726
            prefSellerScore = data['sellerScore']
727
            prefSellerCode = data['sellerCode']
728
            prefSellerSp = data['sellingPrice']
729
            prefSellerBuyTrend = data['buyTrend']
730
            try:
731
                shippingTimeLowerLimitPrefSeller, shippingTimeUpperLimitPrefSeller = data['shippingTime'].split('-')
732
            except ValueError:
733
                shippingTimeLowerLimitPrefSeller = int(data['shippingTime'])
734
 
735
        iterator+=1
11774 kshitij.so 736
 
11193 kshitij.so 737
    flipkartDetails = __FlipkartDetails(rank ,ourSp , secondLowestSellerSp, prefSellerSp, lowestSellerSp, lowestSellerScore, prefSellerScore, secondLowestSellerScore, ourScore, int(shippingTimeLowerLimitLowestSeller),int(shippingTimeUpperLimitLowestSeller), \
738
    int(shippingTimeLowerLimitPrefSeller), int(shippingTimeUpperLimitPrefSeller), int(shippingTimeLowerLimitOur), int(shippingTimeUpperLimitOur), int(shippingTimeLowerLimitSecondLowestSeller), int(shippingTimeUpperLimitSecondLowestSeller), len(sortedVendorsData), lowestSellerName, lowestSellerCode, secondLowestSellerName, secondLowestSellerCode, prefSellerName, prefSellerCode, lowestSellerBuyTrend, \
739
    ourBuyTrend, prefSellerBuyTrend, secondLowestSellerBuyTrend, ourCode)
11774 kshitij.so 740
 
741
    if flipkartDetails.ourBuyTrend == 'PrefCheap'and flipkartDetails.rank!=1 and flipkartDetails.ourSp==flipkartDetails.secondLowestSellerSp:
11775 kshitij.so 742
        print "Under PrefCheap category.Switching data for ",flipkartSerialNumber
11774 kshitij.so 743
        flipkartDetails.lowestSellerSp, flipkartDetails.secondLowestSellerSp = flipkartDetails.secondLowestSellerSp,flipkartDetails.lowestSellerSp
744
        flipkartDetails.lowestSellerScore, flipkartDetails.secondLowestSellerScore = flipkartDetails.secondLowestSellerScore,flipkartDetails.lowestSellerScore
745
        flipkartDetails.shippingTimeLowerLimitLowestSeller, flipkartDetails.shippingTimeLowerLimitSecondLowestSeller = flipkartDetails.shippingTimeLowerLimitSecondLowestSeller,flipkartDetails.shippingTimeLowerLimitLowestSeller
746
        flipkartDetails.shippingTimeUpperLimitLowestSeller, flipkartDetails.shippingTimeUpperLimitSecondLowestSeller = flipkartDetails.shippingTimeUpperLimitSecondLowestSeller,flipkartDetails.shippingTimeUpperLimitLowestSeller
747
        flipkartDetails.lowestSellerName, flipkartDetails.secondLowestSellerName = flipkartDetails.secondLowestSellerName,flipkartDetails.lowestSellerName
748
        flipkartDetails.lowestSellerCode, flipkartDetails.secondLowestSellerCode = flipkartDetails.secondLowestSellerCode,flipkartDetails.lowestSellerCode
749
        flipkartDetails.lowestSellerBuyTrend, flipkartDetails.secondLowestSellerBuyTrend = flipkartDetails.secondLowestSellerBuyTrend,flipkartDetails.lowestSellerBuyTrend
750
        flipkartDetails.rank=1
751
 
752
    if flipkartDetails.ourBuyTrend == 'NPrefCheap'and flipkartDetails.rank!=1 and flipkartDetails.ourSp==flipkartDetails.lowestSellerSp:
11775 kshitij.so 753
        print "Under NPrefCheap category.Switching data for ",flipkartSerialNumber
11774 kshitij.so 754
        flipkartDetails.lowestSellerSp = flipkartDetails.ourSp
755
        flipkartDetails.lowestSellerScore = flipkartDetails.ourScore
756
        flipkartDetails.shippingTimeLowerLimitLowestSeller = flipkartDetails.shippingTimeLowerLimitOur
757
        flipkartDetails.shippingTimeUpperLimitLowestSeller = flipkartDetails.shippingTimeUpperLimitOur
758
        flipkartDetails.lowestSellerName = 'Saholic'
759
        flipkartDetails.lowestSellerCode = flipkartDetails.ourCode
760
        flipkartDetails.lowestSellerBuyTrend = flipkartDetails.ourBuyTrend
761
 
11193 kshitij.so 762
    return flipkartDetails
763
 
764
def calculateAverageSale(oosStatus):
765
    count,sale = 0,0
766
    for obj in oosStatus:
767
        if not obj.is_oos:
768
            count+=1
769
            sale = sale+obj.num_orders
770
    avgSalePerDay=0 if count==0 else (float(sale)/count)
771
    return round(avgSalePerDay,2)
772
 
773
def calculateTotalSale(oosStatus):
774
    sale = 0
775
    for obj in oosStatus:
776
        if not obj.is_oos:
777
            sale = sale+obj.num_orders
778
    return sale
779
 
780
def getNetAvailability(itemInventory):
781
    totalAvailability, totalReserved = 0,0
782
    availableMap  = itemInventory.availability
783
    reserveMap = itemInventory.reserved
784
    for warehouse,availability in availableMap.iteritems():
785
        if warehouse==16:
786
            continue
787
        totalAvailability = totalAvailability+availability
788
    for warehouse,reserve in reserveMap.iteritems():
789
        if warehouse==16:
790
            continue
791
        totalReserved = totalReserved+reserve
792
    return totalAvailability - totalReserved
793
 
794
def getOosString(oosStatus):
795
    lastNdaySale=""
796
    for obj in oosStatus:
797
        if obj.is_oos:
798
            lastNdaySale += "X-"
799
        else:
800
            lastNdaySale += str(obj.num_orders) + "-"
801
    return lastNdaySale[:-1]
802
 
803
def getLastDaySale(itemId):
804
    return (itemSaleMap.get(itemId))[4]
805
 
806
def getSalesPotential(lowestSellingPrice,ourNlc):
807
    if lowestSellingPrice - ourNlc < 0:
808
        return 'HIGH'
809
    elif (float(lowestSellingPrice - ourNlc))/lowestSellingPrice >=0 and (float(lowestSellingPrice - ourNlc))/lowestSellingPrice <=.02:
810
        return 'MEDIUM'
811
    else:
812
        return 'LOW'  
813
 
11571 kshitij.so 814
def decideCategory(itemInfo):
11193 kshitij.so 815
    global itemSaleMap
11560 kshitij.so 816
 
11571 kshitij.so 817
    cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap = [],[],[],[],[],[],[],[]
818
 
11193 kshitij.so 819
    catalog_client = CatalogClient().get_client()
820
 
11571 kshitij.so 821
    for val in itemInfo:
822
        spm = val.sourcePercentage
823
        flipkartDetails = val.flipkartDetails
11581 kshitij.so 824
        if (flipkartDetails is None or flipkartDetails.totalAvailableSeller==0):
11571 kshitij.so 825
            exceptionItems.append(val)
826
            continue
827
 
828
        mpItem = MarketplaceItems.get_by(itemId=val.item_id,source=OrderSource.FLIPKART)
829
        if flipkartDetails.rank==0:
830
            flipkartDetails.ourSp = mpItem.currentSp
831
            ourSp = mpItem.currentSp
832
        else:
833
            ourSp = flipkartDetails.ourSp
11581 kshitij.so 834
        vatRate = catalog_client.getVatPercentageForItem(val.item_id, val.stateId, flipkartDetails.ourSp)
11571 kshitij.so 835
        val.vatRate = vatRate
836
        if (flipkartDetails.ourBuyTrend == 'PrefCheap') or (flipkartDetails.rank==1 and flipkartDetails.totalAvailableSeller==1):
837
            temp=[]
838
            temp.append(flipkartDetails)
839
            temp.append(val)
840
            secondLowestTp=0 if flipkartDetails.totalAvailableSeller==1 else getOtherTp(flipkartDetails,val,spm,False)
841
            prefSellerTp=0 if flipkartDetails.totalAvailableSeller < 2 else getOtherTp(flipkartDetails,val,spm,True)  
842
            flipkartPricing = __FlipkartPricing(flipkartDetails.ourSp,getOurTp(flipkartDetails,val,spm,mpItem),None,getLowestPossibleTp(flipkartDetails,val,spm,mpItem),secondLowestTp,getLowestPossibleSp(flipkartDetails,val,spm,mpItem),prefSellerTp)
843
            temp.append(flipkartPricing)
844
            temp.append(mpItem)
845
            buyBoxItems.append(temp)
846
            continue
847
 
848
        if (flipkartDetails.ourBuyTrend == 'PrefNCheap'):
849
            temp=[]
850
            temp.append(flipkartDetails)
851
            temp.append(val)
11618 kshitij.so 852
            secondLowestTp=0 if flipkartDetails.totalAvailableSeller==1 else getSecondLowestSellerTp(flipkartDetails,val,spm,False)
11615 kshitij.so 853
            lowestTp=0 if flipkartDetails.totalAvailableSeller==1 else getOtherTp(flipkartDetails,val,spm,False)
11571 kshitij.so 854
            prefSellerTp=0 if flipkartDetails.totalAvailableSeller < 2 else getOtherTp(flipkartDetails,val,spm,True)  
855
            flipkartPricing = __FlipkartPricing(flipkartDetails.ourSp,getOurTp(flipkartDetails,val,spm,mpItem),None,getLowestPossibleTp(flipkartDetails,val,spm,mpItem),secondLowestTp,getLowestPossibleSp(flipkartDetails,val,spm,mpItem),prefSellerTp)
856
            temp.append(flipkartPricing)
857
            temp.append(mpItem)
858
            prefButNotCheap.append(temp)
859
            continue
860
 
861
        if (flipkartDetails.ourBuyTrend == 'NPrefCheap') and (flipkartDetails.rank==1):
862
            temp=[]
863
            temp.append(flipkartDetails)
864
            temp.append(val)
11615 kshitij.so 865
            secondLowestTp=0 if flipkartDetails.totalAvailableSeller==1 else getOtherTp(flipkartDetails,val,spm,False)
11571 kshitij.so 866
            prefSellerTp=0 if flipkartDetails.totalAvailableSeller < 2 else getOtherTp(flipkartDetails,val,spm,True)  
11615 kshitij.so 867
            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 868
            temp.append(flipkartPricing)
869
            temp.append(mpItem)
870
            cheapButNotPref.append(temp)
871
            continue
872
 
873
        lowestTp = getOtherTp(flipkartDetails,val,spm,False)
874
        ourTp = getOurTp(flipkartDetails,val,spm,mpItem)
875
        lowestPossibleTp = getLowestPossibleTp(flipkartDetails,val,spm,mpItem)
876
        lowestPossibleSp = getLowestPossibleSp(flipkartDetails,val,spm,mpItem)
877
        prefSellerTp = getOtherTp(flipkartDetails,val,spm,True)
878
 
879
        if (ourTp<lowestPossibleTp):
880
            temp=[]
881
            temp.append(flipkartDetails)
882
            temp.append(val)
883
            flipkartPricing = __FlipkartPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,None,None)
884
            temp.append(flipkartPricing)
885
            negativeMargin.append(temp)
886
            continue
887
 
888
        if (flipkartDetails.lowestSellerSp > lowestPossibleSp) and val.ourFlipkartInventory!=0:
889
            type(val.ourFlipkartInventory)
890
            temp=[]
891
            temp.append(flipkartDetails)
892
            temp.append(val)
893
            flipkartPricing = __FlipkartPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,lowestPossibleSp,prefSellerTp)
894
            temp.append(flipkartPricing)
895
            temp.append(mpItem)
896
            competitive.append(temp)
897
            continue
898
 
899
        if (flipkartDetails.lowestSellerSp) > lowestPossibleSp and val.ourFlipkartInventory==0:
900
            temp=[]
901
            temp.append(flipkartDetails)
902
            temp.append(val)
903
            flipkartPricing = __FlipkartPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,lowestPossibleSp,prefSellerTp)
904
            temp.append(flipkartPricing)
905
            temp.append(mpItem)
906
            competitiveNoInventory.append(temp)
907
            continue
908
 
11193 kshitij.so 909
        temp=[]
910
        temp.append(flipkartDetails)
911
        temp.append(val)
912
        flipkartPricing = __FlipkartPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,lowestPossibleSp,prefSellerTp)
913
        temp.append(flipkartPricing)
914
        temp.append(mpItem)
11571 kshitij.so 915
        cantCompete.append(temp)
11193 kshitij.so 916
 
11571 kshitij.so 917
    return cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap
11193 kshitij.so 918
 
919
def getOtherTp(flipkartDetails,val,spm,prefferedSeller):
920
    if val.parent_category==10011 or val.parent_category==12001:
921
        commissionPercentage = spm.competitorCommissionAccessory
922
    else:
923
        commissionPercentage = spm.competitorCommissionOther
924
    if flipkartDetails.rank==1 and not prefferedSeller:
925
        otherTp = flipkartDetails.secondLowestSellerSp- flipkartDetails.secondLowestSellerSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100))
926
        return round(otherTp,2)
927
    if prefferedSeller:
928
        otherTp = flipkartDetails.prefSellerSp- flipkartDetails.prefSellerSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100))
929
        return round(otherTp,2)
930
    otherTp = flipkartDetails.lowestSellerSp- flipkartDetails.lowestSellerSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100))
931
    return round(otherTp,2)
11618 kshitij.so 932
 
933
def getSecondLowestSellerTp(flipkartDetails,val,spm,prefferedSeller):
934
    if val.parent_category==10011 or val.parent_category==12001:
935
        commissionPercentage = spm.competitorCommissionAccessory
936
    else:
937
        commissionPercentage = spm.competitorCommissionOther
938
    otherTp = flipkartDetails.secondLowestSellerSp- flipkartDetails.secondLowestSellerSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100))
939
    return round(otherTp,2)
11193 kshitij.so 940
 
941
def getLowestPossibleTp(flipkartDetails,val,spm,mpItem):
942
    if flipkartDetails.rank==0:
943
        return mpItem.minimumPossibleTp
944
    vat = (flipkartDetails.ourSp/(1+(val.vatRate/100))-(val.nlc/(1+(val.vatRate/100))))*(val.vatRate/100);
945
    inHouseCost = 15+vat+(mpItem.returnProvision/100)*flipkartDetails.ourSp+mpItem.otherCost;
946
    lowest_possible_tp = val.nlc+inHouseCost;
947
    return round(lowest_possible_tp,2)
948
 
949
def getOurTp(flipkartDetails,val,spm,mpItem):
950
    if flipkartDetails.rank==0:
951
        return mpItem.currentTp
952
    ourTp = flipkartDetails.ourSp- flipkartDetails.ourSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(val.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))
953
    return round(ourTp,2)
954
 
955
def getLowestPossibleSp(flipkartDetails,val,spm,mpItem):
956
    if flipkartDetails.rank==0:
957
        return mpItem.minimumPossibleSp
958
    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));
959
    return round(lowestPossibleSp,2)
960
 
961
def getTargetTp(targetSp,mpItem):
962
    targetTp = targetSp- targetSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))
963
    return round(targetTp,2)
964
 
965
def getTargetSp(targetTp,mpItem,ourSp):
966
    targetSp = float(targetTp+(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100)))/(1-((mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))))
967
    return round(targetSp,2)
968
 
11623 kshitij.so 969
def getNewLowestPossibleTp(mpItem,nlc,vatRate,proposedSellingPrice):
970
    vat = (proposedSellingPrice/(1+(vatRate/100))-(nlc/(1+(vatRate/100))))*(vatRate/100);
971
    inHouseCost = 15+vat+(mpItem.returnProvision/100)*proposedSellingPrice+mpItem.otherCost;
972
    lowest_possible_tp = nlc+inHouseCost;
973
    return round(lowest_possible_tp,2)
974
 
975
def getNewOurTp(mpItem,proposedSellingPrice):
11624 kshitij.so 976
    ourTp = proposedSellingPrice- proposedSellingPrice*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))
11623 kshitij.so 977
    return round(ourTp,2)
978
 
979
def getNewLowestPossibleSp(mpItem,nlc,vatRate):
11624 kshitij.so 980
    lowestPossibleSp = (nlc+(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))*(1+(vatRate/100))+(15+mpItem.otherCost)*(1+(vatRate)/100))/(1-(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))*(1+(vatRate)/100)-(mpItem.returnProvision/100)*(1+(vatRate)/100));
11623 kshitij.so 981
    return round(lowestPossibleSp,2)    
982
 
983
 
11193 kshitij.so 984
def markAutoFavourite():
985
    previouslyAutoFav = []
986
    nowAutoFav = []
987
    marketplaceItems = session.query(MarketplaceItems).filter(MarketplaceItems.source==OrderSource.FLIPKART).all()
988
    fromDate = datetime.now()-timedelta(days = 3, hours=datetime.now().hour, minutes=datetime.now().minute, seconds=datetime.now().second)
989
    toDate = datetime.now()-timedelta(days = 0, hours=datetime.now().hour, minutes=datetime.now().minute, seconds=datetime.now().second)
11615 kshitij.so 990
    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 991
    toUpdate = [key for key, value in itemSaleMap.items() if value[5] >= 1]
992
    buyBoxLast3days = []
993
    for item in items:
994
        buyBoxLast3days.append(item[0])
995
    for marketplaceItem in marketplaceItems:
996
        reason = ""
997
        toMark = False
998
        if marketplaceItem.itemId in toUpdate:
999
            toMark = True
1000
            reason+="Total sale is greater than 1 for last five days (Flipkart)."
1001
        if marketplaceItem.itemId in buyBoxLast3days:
1002
            toMark = True
1003
            reason+="Item is present in buy box in last 3 days"
1004
        if not marketplaceItem.autoFavourite:
1005
            print "Item is not under auto favourite"
1006
        if toMark:
1007
            temp=[]
1008
            temp.append(marketplaceItem.itemId)
1009
            temp.append(reason)
1010
            nowAutoFav.append(temp)
1011
        if (not toMark) and marketplaceItem.autoFavourite:
1012
            previouslyAutoFav.append(marketplaceItem.itemId)
1013
        marketplaceItem.autoFavourite = toMark
1014
    session.commit()
1015
    return previouslyAutoFav, nowAutoFav
1016
 
11615 kshitij.so 1017
def write_report(previousAutoFav, nowAutoFav,timestamp, runType):
11193 kshitij.so 1018
    wbk = xlwt.Workbook()
1019
    sheet = wbk.add_sheet('Can\'t Compete')
1020
    xstr = lambda s: s or ""
1021
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1022
 
1023
    excel_integer_format = '0'
1024
    integer_style = xlwt.XFStyle()
1025
    integer_style.num_format_str = excel_integer_format
1026
 
1027
    sheet.write(0, 0, "Item ID", heading_xf)
1028
    sheet.write(0, 1, "Category", heading_xf)
1029
    sheet.write(0, 2, "Product Group.", heading_xf)
1030
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1031
    sheet.write(0, 4, "Brand", heading_xf)
1032
    sheet.write(0, 5, "Product Name", heading_xf)
1033
    sheet.write(0, 6, "Weight", heading_xf)
1034
    sheet.write(0, 7, "Courier Cost", heading_xf)
1035
    sheet.write(0, 8, "Risky", heading_xf)
11790 kshitij.so 1036
    sheet.write(0, 9, "Commission Rate", heading_xf)
1037
    sheet.write(0, 10, "Return Provision", heading_xf)
1038
    sheet.write(0, 11, "Our Rating", heading_xf)
1039
    sheet.write(0, 12, "Our Shipping Time", heading_xf)
1040
    sheet.write(0, 13, "Our Rank", heading_xf)
1041
    sheet.write(0, 14, "Our SP", heading_xf)
1042
    sheet.write(0, 15, "Our TP", heading_xf)
1043
    sheet.write(0, 16, "Lowest Seller", heading_xf)
1044
    sheet.write(0, 17, "Lowest Seller Rating", heading_xf)
1045
    sheet.write(0, 18, "Lowest Seller Shipping Time", heading_xf)
1046
    sheet.write(0, 19, "Lowest Seller SP", heading_xf)
1047
    sheet.write(0, 20, "Lowest Seller TP", heading_xf)
1048
    sheet.write(0, 21, "Preffered Seller", heading_xf)
1049
    sheet.write(0, 22, "Preffered Seller Rating", heading_xf)
1050
    sheet.write(0, 23, "Preffered Seller Shipping Time", heading_xf)
1051
    sheet.write(0, 24, "Preffer Seller SP", heading_xf)
1052
    sheet.write(0, 25, "Preffered Seller TP", heading_xf)
1053
    sheet.write(0, 26, "Our Flipkart Inventory", heading_xf)
1054
    sheet.write(0, 27, "Our Net Availability",heading_xf)
1055
    sheet.write(0, 28, "Last Five Day Sale", heading_xf)
1056
    sheet.write(0, 29, "Average Sale", heading_xf)
1057
    sheet.write(0, 30, "Our NLC", heading_xf)
1058
    sheet.write(0, 31, "Lowest Possible SP", heading_xf)
1059
    sheet.write(0, 32, "Lowest Possible TP", heading_xf)
1060
    sheet.write(0, 33, "Target SP", heading_xf)
1061
    sheet.write(0, 34, "Target TP", heading_xf)  
1062
    sheet.write(0, 35, "Target NLC", heading_xf)
1063
    sheet.write(0, 36, "Sales Potential", heading_xf)
1064
    sheet.write(0, 37, "Total Seller", heading_xf)
11193 kshitij.so 1065
    sheet_iterator = 1
11620 kshitij.so 1066
    canCompeteItems = session.query(MarketPlaceHistory,FlipkartItem,MarketplaceItems,Item)\
11622 kshitij.so 1067
    .join((FlipkartItem,MarketPlaceHistory.item_id==FlipkartItem.item_id))\
1068
    .join((MarketplaceItems,MarketPlaceHistory.item_id==MarketplaceItems.itemId))\
1069
    .join((Item,MarketPlaceHistory.item_id==Item.id))\
11615 kshitij.so 1070
    .filter(MarketplaceItems.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.source==OrderSource.FLIPKART)\
1071
    .filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.CANT_COMPETE).all()
1072
    for item in canCompeteItems:
1073
        mpHistory = item[0]
1074
        flipkartItem = item[1]
1075
        mpItem = item[2]
1076
        catItem = item[3]
1077
        sheet.write(sheet_iterator,0,mpHistory.item_id)
1078
        sheet.write(sheet_iterator,1,categoryMap.get(catItem.category)[0])
1079
        sheet.write(sheet_iterator,2,categoryMap.get(catItem.category)[1])
1080
        sheet.write(sheet_iterator,3,flipkartItem.flipkartSerialNumber)
1081
        sheet.write(sheet_iterator,4,catItem.brand)
1082
        sheet.write(sheet_iterator,5,xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color))
1083
        sheet.write(sheet_iterator,6,catItem.weight)
1084
        sheet.write(sheet_iterator,7,mpItem.courierCost)
1085
        sheet.write(sheet_iterator,8,catItem.risky)
11790 kshitij.so 1086
        sheet.write(sheet_iterator,9,mpItem.commission)
1087
        sheet.write(sheet_iterator,10,mpItem.returnProvision)
1088
        sheet.write(sheet_iterator,11,mpHistory.ourRating)
11615 kshitij.so 1089
#        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1090
#        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
11790 kshitij.so 1091
        sheet.write(sheet_iterator,12,mpHistory.ourShippingTime)
1092
        sheet.write(sheet_iterator,13,mpHistory.ourRank)
1093
        sheet.write(sheet_iterator,14,mpHistory.ourSellingPrice)
1094
        sheet.write(sheet_iterator,15,mpHistory.ourTp)
1095
        sheet.write(sheet_iterator,16,mpHistory.lowestSellerName)
1096
        sheet.write(sheet_iterator,17,mpHistory.lowestSellerRating)
11615 kshitij.so 1097
#       lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1098
#       else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
11790 kshitij.so 1099
        sheet.write(sheet_iterator,18,mpHistory.lowestSellerShippingTime)
1100
        sheet.write(sheet_iterator,19,mpHistory.lowestSellingPrice)
1101
        sheet.write(sheet_iterator,20,mpHistory.lowestTp)
1102
        sheet.write(sheet_iterator,21,mpHistory.prefferedSellerName)
1103
        sheet.write(sheet_iterator,22,mpHistory.prefferedSellerRating)
11615 kshitij.so 1104
#        prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1105
#        else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
11790 kshitij.so 1106
        sheet.write(sheet_iterator,23,mpHistory.prefferedSellerShippingTime)
1107
        sheet.write(sheet_iterator,24,mpHistory.prefferedSellerSellingPrice)
1108
        sheet.write(sheet_iterator,25,mpHistory.prefferedSellerTp)
1109
        sheet.write(sheet_iterator,26,mpHistory.ourInventory)
11615 kshitij.so 1110
        if (not inventoryMap.has_key(mpHistory.item_id)):
11790 kshitij.so 1111
            sheet.write(sheet_iterator, 27, 'Info not available')
11193 kshitij.so 1112
        else:
11790 kshitij.so 1113
            sheet.write(sheet_iterator, 27, getNetAvailability(inventoryMap.get(mpHistory.item_id)))
1114
        sheet.write(sheet_iterator, 28, getOosString((itemSaleMap.get(mpHistory.item_id))[1]))
1115
        sheet.write(sheet_iterator, 29, (itemSaleMap.get(mpHistory.item_id))[3])
1116
        sheet.write(sheet_iterator, 30, mpHistory.ourNlc)
1117
        sheet.write(sheet_iterator, 31, mpHistory.lowestPossibleSp)
1118
        sheet.write(sheet_iterator, 32, mpHistory.lowestPossibleTp)
11615 kshitij.so 1119
        proposed_sp = mpHistory.lowestSellingPrice - max(10, mpHistory.lowestSellingPrice*0.001)
11193 kshitij.so 1120
        proposed_tp = getTargetTp(proposed_sp,mpItem)
11615 kshitij.so 1121
        target_nlc = proposed_tp - mpHistory.lowestPossibleTp + mpHistory.ourNlc
11790 kshitij.so 1122
        sheet.write(sheet_iterator, 33, proposed_sp)
1123
        sheet.write(sheet_iterator, 34, proposed_tp)
1124
        sheet.write(sheet_iterator, 35, target_nlc)
1125
        sheet.write(sheet_iterator, 36, getSalesPotential(mpHistory.lowestSellingPrice,mpHistory.ourNlc))
1126
        sheet.write(sheet_iterator, 37, mpHistory.totalSeller)
11193 kshitij.so 1127
        sheet_iterator+=1
11615 kshitij.so 1128
 
1129
    canCompeteItems[:] = []
1130
 
11193 kshitij.so 1131
 
1132
    sheet = wbk.add_sheet('Pref and Cheap')
1133
 
1134
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1135
 
1136
    excel_integer_format = '0'
1137
    integer_style = xlwt.XFStyle()
1138
    integer_style.num_format_str = excel_integer_format
1139
    xstr = lambda s: s or ""
1140
 
1141
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1142
 
1143
    excel_integer_format = '0'
1144
    integer_style = xlwt.XFStyle()
1145
    integer_style.num_format_str = excel_integer_format
1146
 
1147
    sheet.write(0, 0, "Item ID", heading_xf)
1148
    sheet.write(0, 1, "Category", heading_xf)
1149
    sheet.write(0, 2, "Product Group.", heading_xf)
1150
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1151
    sheet.write(0, 4, "Brand", heading_xf)
1152
    sheet.write(0, 5, "Product Name", heading_xf)
1153
    sheet.write(0, 6, "Weight", heading_xf)
1154
    sheet.write(0, 7, "Courier Cost", heading_xf)
1155
    sheet.write(0, 8, "Risky", heading_xf)
11790 kshitij.so 1156
    sheet.write(0, 9, "Commission Rate", heading_xf)
1157
    sheet.write(0, 10, "Return Provision", heading_xf)
1158
    sheet.write(0, 11, "Our Rating", heading_xf)
1159
    sheet.write(0, 12, "Our Shipping Time", heading_xf)
1160
    sheet.write(0, 13, "Our Rank", heading_xf)
1161
    sheet.write(0, 14, "Our SP", heading_xf)
1162
    sheet.write(0, 15, "Our TP", heading_xf)
1163
    sheet.write(0, 16, "Lowest Seller", heading_xf)
1164
    sheet.write(0, 17, "Lowest Seller Rating", heading_xf)
1165
    sheet.write(0, 18, "Lowest Seller Shipping Time", heading_xf)
1166
    sheet.write(0, 19, "Lowest Seller SP", heading_xf)
1167
    sheet.write(0, 20, "Lowest Seller TP", heading_xf)
1168
    sheet.write(0, 21, "Second Lowest Seller", heading_xf)
1169
    sheet.write(0, 22, "Second Lowest Seller Rating", heading_xf)
1170
    sheet.write(0, 23, "Second Lowest Seller Shipping Time", heading_xf)
1171
    sheet.write(0, 24, "Second Lowest Seller SP", heading_xf)
1172
    sheet.write(0, 25, "Second Lowest Seller TP", heading_xf)
1173
    sheet.write(0, 26, "Our Flipkart Inventory", heading_xf)
1174
    sheet.write(0, 27, "Our Net Availability",heading_xf)
1175
    sheet.write(0, 28, "Last Five Day Sale", heading_xf)
1176
    sheet.write(0, 29, "Average Sale", heading_xf)
1177
    sheet.write(0, 30, "Our NLC", heading_xf)
1178
    sheet.write(0, 31, "Lowest Possible SP", heading_xf)
1179
    sheet.write(0, 32, "Lowest Possible TP", heading_xf)
1180
    sheet.write(0, 33, "Target SP", heading_xf)
1181
    sheet.write(0, 34, "Target TP", heading_xf)  
1182
    sheet.write(0, 35, "Margin Increased Potential", heading_xf)
1183
    sheet.write(0, 36, "Total Seller", heading_xf)
1184
    sheet.write(0, 37, "Auto Pricing Decision", heading_xf)
1185
    sheet.write(0, 38, "Reason", heading_xf)
1186
    sheet.write(0, 39, "Updated Price", heading_xf)
11193 kshitij.so 1187
    sheet_iterator = 1
11615 kshitij.so 1188
 
11622 kshitij.so 1189
    buyBoxItems = session.query(MarketPlaceHistory,FlipkartItem,MarketplaceItems,Item)\
1190
    .join((FlipkartItem,MarketPlaceHistory.item_id==FlipkartItem.item_id))\
1191
    .join((MarketplaceItems,MarketPlaceHistory.item_id==MarketplaceItems.itemId))\
1192
    .join((Item,MarketPlaceHistory.item_id==Item.id))\
11615 kshitij.so 1193
    .filter(MarketplaceItems.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.source==OrderSource.FLIPKART)\
1194
    .filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.BUY_BOX).all()
1195
 
1196
 
11193 kshitij.so 1197
    for item in buyBoxItems:
11615 kshitij.so 1198
        mpHistory = item[0]
1199
        flipkartItem = item[1]
1200
        mpItem = item[2]
1201
        catItem = item[3]
1202
        sheet.write(sheet_iterator,0,mpHistory.item_id)
1203
        sheet.write(sheet_iterator,1,categoryMap.get(catItem.category)[0])
1204
        sheet.write(sheet_iterator,2,categoryMap.get(catItem.category)[1])
1205
        sheet.write(sheet_iterator,3,flipkartItem.flipkartSerialNumber)
1206
        sheet.write(sheet_iterator,4,catItem.brand)
1207
        sheet.write(sheet_iterator,5,xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color))
1208
        sheet.write(sheet_iterator,6,catItem.weight)
1209
        sheet.write(sheet_iterator,7,mpItem.courierCost)
1210
        sheet.write(sheet_iterator,8,catItem.risky)
11790 kshitij.so 1211
        sheet.write(sheet_iterator,9,mpItem.commission)
1212
        sheet.write(sheet_iterator,10,mpItem.returnProvision)
1213
        sheet.write(sheet_iterator,11,mpHistory.ourRating)
11615 kshitij.so 1214
#        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1215
#        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
11790 kshitij.so 1216
        sheet.write(sheet_iterator,12,mpHistory.ourShippingTime)
1217
        sheet.write(sheet_iterator,13,mpHistory.ourRank)
1218
        sheet.write(sheet_iterator,14,mpHistory.ourSellingPrice)
1219
        sheet.write(sheet_iterator,15,mpHistory.ourTp)
1220
        sheet.write(sheet_iterator,16,mpHistory.lowestSellerName)
1221
        sheet.write(sheet_iterator,17,mpHistory.lowestSellerRating)
11615 kshitij.so 1222
#        lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1223
#        else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
11790 kshitij.so 1224
        sheet.write(sheet_iterator,18,mpHistory.lowestSellerShippingTime)
1225
        sheet.write(sheet_iterator,19,mpHistory.lowestSellingPrice)
1226
        sheet.write(sheet_iterator,20,mpHistory.lowestTp)
1227
        sheet.write(sheet_iterator,21,mpHistory.secondLowestSellerName)
1228
        sheet.write(sheet_iterator,22,mpHistory.secondLowestSellerRating)
11615 kshitij.so 1229
#        secondLowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitSecondLowestSeller) if flipkartDetails.shippingTimeUpperLimitSecondLowestSeller==0\
1230
#        else str(flipkartDetails.shippingTimeLowerLimitSecondLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitSecondLowestSeller)
11790 kshitij.so 1231
        sheet.write(sheet_iterator,23,mpHistory.secondLowestSellerShippingTime)
1232
        sheet.write(sheet_iterator,24,mpHistory.secondLowestSellingPrice)
1233
        sheet.write(sheet_iterator,25,mpHistory.secondLowestTp)
1234
        sheet.write(sheet_iterator,26,mpHistory.ourInventory)
11615 kshitij.so 1235
        if (not inventoryMap.has_key(mpHistory.item_id)):
11790 kshitij.so 1236
            sheet.write(sheet_iterator, 27, 'Info not available')
11193 kshitij.so 1237
        else:
11790 kshitij.so 1238
            sheet.write(sheet_iterator, 27, getNetAvailability(inventoryMap.get(mpHistory.item_id)))
1239
        sheet.write(sheet_iterator, 28, getOosString((itemSaleMap.get(mpHistory.item_id))[1]))
1240
        sheet.write(sheet_iterator, 29, (itemSaleMap.get(mpHistory.item_id))[3])
1241
        sheet.write(sheet_iterator, 30, mpHistory.ourNlc)
1242
        sheet.write(sheet_iterator, 31, mpHistory.lowestPossibleSp)
1243
        sheet.write(sheet_iterator, 32, mpHistory.lowestPossibleTp)
11615 kshitij.so 1244
        proposed_sp = max(mpHistory.secondLowestSellingPrice - max((20, mpHistory.secondLowestSellingPrice*0.002)), mpHistory.lowestPossibleSp)
11193 kshitij.so 1245
        proposed_tp = getTargetTp(proposed_sp,mpItem)
11615 kshitij.so 1246
        target_nlc = proposed_tp -  mpHistory.lowestPossibleTp + mpHistory.ourNlc
11790 kshitij.so 1247
        sheet.write(sheet_iterator, 33, proposed_sp)
1248
        sheet.write(sheet_iterator, 34, proposed_tp)
1249
        sheet.write(sheet_iterator, 35, proposed_tp -mpHistory.ourTp )
1250
        sheet.write(sheet_iterator, 36, mpHistory.totalSeller)
11775 kshitij.so 1251
        if mpHistory.decision is None:
11790 kshitij.so 1252
            sheet.write(sheet_iterator, 37, 'Auto Pricing Inactive')
11775 kshitij.so 1253
            sheet_iterator+=1
1254
            continue
11790 kshitij.so 1255
        sheet.write(sheet_iterator, 37, Decision._VALUES_TO_NAMES.get(mpHistory.decision))
1256
        sheet.write(sheet_iterator, 38, mpHistory.reason)
11776 kshitij.so 1257
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_DECREMENT_SUCCESS":
11790 kshitij.so 1258
            sheet.write(sheet_iterator, 39, math.ceil(mpHistory.proposedSellingPrice))
11776 kshitij.so 1259
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_INCREMENT_SUCCESS":
11790 kshitij.so 1260
            sheet.write(sheet_iterator, 39, math.ceil(mpHistory.ourSellingPrice+max(10,.01*mpHistory.ourSellingPrice)))
11776 kshitij.so 1261
 
11193 kshitij.so 1262
        sheet_iterator+=1
1263
 
11615 kshitij.so 1264
    buyBoxItems[:] = []
11193 kshitij.so 1265
 
11615 kshitij.so 1266
    sheet = wbk.add_sheet('Pref Not Cheap')
11193 kshitij.so 1267
 
1268
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1269
 
1270
    excel_integer_format = '0'
1271
    integer_style = xlwt.XFStyle()
1272
    integer_style.num_format_str = excel_integer_format
1273
    xstr = lambda s: s or ""
1274
 
1275
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1276
 
1277
    excel_integer_format = '0'
1278
    integer_style = xlwt.XFStyle()
1279
    integer_style.num_format_str = excel_integer_format
1280
 
1281
    sheet.write(0, 0, "Item ID", heading_xf)
1282
    sheet.write(0, 1, "Category", heading_xf)
1283
    sheet.write(0, 2, "Product Group.", heading_xf)
1284
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1285
    sheet.write(0, 4, "Brand", heading_xf)
1286
    sheet.write(0, 5, "Product Name", heading_xf)
1287
    sheet.write(0, 6, "Weight", heading_xf)
1288
    sheet.write(0, 7, "Courier Cost", heading_xf)
1289
    sheet.write(0, 8, "Risky", heading_xf)
11790 kshitij.so 1290
    sheet.write(0, 9, "Commission Rate", heading_xf)
1291
    sheet.write(0, 10, "Return Provision", heading_xf)
1292
    sheet.write(0, 11, "Our Rating", heading_xf)
1293
    sheet.write(0, 12, "Our Shipping Time", heading_xf)
1294
    sheet.write(0, 13, "Our Rank", heading_xf)
1295
    sheet.write(0, 14, "Our SP", heading_xf)
1296
    sheet.write(0, 15, "Our TP", heading_xf)
1297
    sheet.write(0, 16, "Lowest Seller", heading_xf)
1298
    sheet.write(0, 17, "Lowest Seller Rating", heading_xf)
1299
    sheet.write(0, 18, "Lowest Seller Shipping Time", heading_xf)
1300
    sheet.write(0, 19, "Lowest Seller SP", heading_xf)
1301
    sheet.write(0, 20, "Lowest Seller TP", heading_xf)
1302
    sheet.write(0, 21, "Preffered Seller", heading_xf)
1303
    sheet.write(0, 22, "Preffered Seller Rating", heading_xf)
1304
    sheet.write(0, 23, "Preffered Seller Shipping Time", heading_xf)
1305
    sheet.write(0, 24, "Preffered Seller SP", heading_xf)
1306
    sheet.write(0, 25, "Preffered Seller TP", heading_xf)
1307
    sheet.write(0, 26, "Our Flipkart Inventory", heading_xf)
1308
    sheet.write(0, 27, "Our Net Availability",heading_xf)
1309
    sheet.write(0, 28, "Last Five Day Sale", heading_xf)
1310
    sheet.write(0, 29, "Average Sale", heading_xf)
1311
    sheet.write(0, 30, "Our NLC", heading_xf)
1312
    sheet.write(0, 31, "Lowest Possible SP", heading_xf)
1313
    sheet.write(0, 32, "Lowest Possible TP", heading_xf)
1314
    sheet.write(0, 33, "Target SP", heading_xf)
1315
    sheet.write(0, 34, "Target TP", heading_xf)  
1316
    sheet.write(0, 35, "Total Seller", heading_xf)
1317
    sheet.write(0, 36, "Auto Pricing Decision", heading_xf)
1318
    sheet.write(0, 37, "Reason", heading_xf)
1319
    sheet.write(0, 38, "Updated Price", heading_xf)
11775 kshitij.so 1320
 
11193 kshitij.so 1321
    sheet_iterator = 1
11615 kshitij.so 1322
 
11622 kshitij.so 1323
    prefNotCheapItems = session.query(MarketPlaceHistory,FlipkartItem,MarketplaceItems,Item)\
1324
    .join((FlipkartItem,MarketPlaceHistory.item_id==FlipkartItem.item_id))\
1325
    .join((MarketplaceItems,MarketPlaceHistory.item_id==MarketplaceItems.itemId))\
1326
    .join((Item,MarketPlaceHistory.item_id==Item.id))\
11615 kshitij.so 1327
    .filter(MarketplaceItems.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.source==OrderSource.FLIPKART)\
1328
    .filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.PREF_BUT_NOT_CHEAP).all()
1329
 
1330
 
1331
    for item in prefNotCheapItems:
1332
        mpHistory = item[0]
1333
        flipkartItem = item[1]
1334
        mpItem = item[2]
1335
        catItem = item[3]
1336
        sheet.write(sheet_iterator,0,mpHistory.item_id)
1337
        sheet.write(sheet_iterator,1,categoryMap.get(catItem.category)[0])
1338
        sheet.write(sheet_iterator,2,categoryMap.get(catItem.category)[1])
1339
        sheet.write(sheet_iterator,3,flipkartItem.flipkartSerialNumber)
1340
        sheet.write(sheet_iterator,4,catItem.brand)
1341
        sheet.write(sheet_iterator,5,xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color))
1342
        sheet.write(sheet_iterator,6,catItem.weight)
1343
        sheet.write(sheet_iterator,7,mpItem.courierCost)
1344
        sheet.write(sheet_iterator,8,catItem.risky)
11790 kshitij.so 1345
        sheet.write(sheet_iterator,9,mpItem.commission)
1346
        sheet.write(sheet_iterator,10,mpItem.returnProvision)
1347
        sheet.write(sheet_iterator,11,mpHistory.ourRating)
11615 kshitij.so 1348
#        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1349
#        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
11790 kshitij.so 1350
        sheet.write(sheet_iterator,12,mpHistory.ourShippingTime)
1351
        sheet.write(sheet_iterator,13,mpHistory.ourRank)
1352
        sheet.write(sheet_iterator,14,mpHistory.ourSellingPrice)
1353
        sheet.write(sheet_iterator,15,mpHistory.ourTp)
1354
        sheet.write(sheet_iterator,16,mpHistory.lowestSellerName)
1355
        sheet.write(sheet_iterator,17,mpHistory.lowestSellerRating)
11615 kshitij.so 1356
#        lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1357
#        else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
11790 kshitij.so 1358
        sheet.write(sheet_iterator,18,mpHistory.lowestSellerShippingTime)
1359
        sheet.write(sheet_iterator,19,mpHistory.lowestSellingPrice)
1360
        sheet.write(sheet_iterator,20,mpHistory.lowestTp)
1361
        sheet.write(sheet_iterator,21,mpHistory.prefferedSellerName)
1362
        sheet.write(sheet_iterator,22,mpHistory.prefferedSellerRating)
11615 kshitij.so 1363
#        secondLowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitSecondLowestSeller) if flipkartDetails.shippingTimeUpperLimitSecondLowestSeller==0\
1364
#        else str(flipkartDetails.shippingTimeLowerLimitSecondLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitSecondLowestSeller)
11790 kshitij.so 1365
        sheet.write(sheet_iterator,23,mpHistory.prefferedSellerShippingTime)
1366
        sheet.write(sheet_iterator,24,mpHistory.prefferedSellerSellingPrice)
1367
        sheet.write(sheet_iterator,25,mpHistory.prefferedSellerTp)
1368
        sheet.write(sheet_iterator,26,mpHistory.ourInventory)
11615 kshitij.so 1369
        if (not inventoryMap.has_key(mpHistory.item_id)):
11790 kshitij.so 1370
            sheet.write(sheet_iterator, 27, 'Info not available')
11193 kshitij.so 1371
        else:
11790 kshitij.so 1372
            sheet.write(sheet_iterator, 27, getNetAvailability(inventoryMap.get(mpHistory.item_id)))
1373
        sheet.write(sheet_iterator, 28, getOosString((itemSaleMap.get(mpHistory.item_id))[1]))
1374
        sheet.write(sheet_iterator, 29, (itemSaleMap.get(mpHistory.item_id))[3])
1375
        sheet.write(sheet_iterator, 30, mpHistory.ourNlc)
1376
        sheet.write(sheet_iterator, 31, mpHistory.lowestPossibleSp)
1377
        sheet.write(sheet_iterator, 32, mpHistory.lowestPossibleTp)
11775 kshitij.so 1378
        proposed_sp = max(mpHistory.lowestSellingPrice - max((10, mpHistory.lowestSellingPrice*0.001)), mpHistory.lowestPossibleSp)
11615 kshitij.so 1379
        proposed_tp = getTargetTp(proposed_sp,mpItem)
1380
        target_nlc = proposed_tp -  mpHistory.lowestPossibleTp + mpHistory.ourNlc
11790 kshitij.so 1381
        sheet.write(sheet_iterator, 33, proposed_sp)
1382
        sheet.write(sheet_iterator, 34, proposed_tp)
1383
        sheet.write(sheet_iterator, 35, mpHistory.totalSeller)
11775 kshitij.so 1384
        if mpHistory.decision is None:
11790 kshitij.so 1385
            sheet.write(sheet_iterator, 36, 'Auto Pricing Inactive')
11775 kshitij.so 1386
            sheet_iterator+=1
1387
            continue
11790 kshitij.so 1388
        sheet.write(sheet_iterator, 36, Decision._VALUES_TO_NAMES.get(mpHistory.decision))
1389
        sheet.write(sheet_iterator, 37, mpHistory.reason)
11776 kshitij.so 1390
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_DECREMENT_SUCCESS":
11790 kshitij.so 1391
            sheet.write(sheet_iterator, 38, math.ceil(mpHistory.proposedSellingPrice))
11776 kshitij.so 1392
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_INCREMENT_SUCCESS":
11790 kshitij.so 1393
            sheet.write(sheet_iterator, 38, math.ceil(mpHistory.ourSellingPrice+max(10,.01*mpHistory.ourSellingPrice)))
11775 kshitij.so 1394
 
11193 kshitij.so 1395
        sheet_iterator+=1
11615 kshitij.so 1396
 
1397
    prefNotCheapItems[:] = []
11193 kshitij.so 1398
 
1399
    sheet = wbk.add_sheet('Cheap But Not Pref')
1400
 
1401
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1402
 
1403
    excel_integer_format = '0'
1404
    integer_style = xlwt.XFStyle()
1405
    integer_style.num_format_str = excel_integer_format
1406
    xstr = lambda s: s or ""
1407
 
1408
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1409
 
1410
    excel_integer_format = '0'
1411
    integer_style = xlwt.XFStyle()
1412
    integer_style.num_format_str = excel_integer_format
1413
 
1414
    sheet.write(0, 0, "Item ID", heading_xf)
1415
    sheet.write(0, 1, "Category", heading_xf)
1416
    sheet.write(0, 2, "Product Group.", heading_xf)
1417
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1418
    sheet.write(0, 4, "Brand", heading_xf)
1419
    sheet.write(0, 5, "Product Name", heading_xf)
1420
    sheet.write(0, 6, "Weight", heading_xf)
1421
    sheet.write(0, 7, "Courier Cost", heading_xf)
1422
    sheet.write(0, 8, "Risky", heading_xf)
11790 kshitij.so 1423
    sheet.write(0, 9, "Commission Rate", heading_xf)
1424
    sheet.write(0, 10, "Return Provision", heading_xf)
1425
    sheet.write(0, 11, "Our Rank", heading_xf)
1426
    sheet.write(0, 12, "Lowest Seller", heading_xf)
1427
    sheet.write(0, 13, "Our Rating", heading_xf)
1428
    sheet.write(0, 14, "Our Shipping Time", heading_xf)
1429
    sheet.write(0, 15, "Our SP", heading_xf)
1430
    sheet.write(0, 16, "Our TP", heading_xf)
1431
    sheet.write(0, 17, "Preffered Seller", heading_xf)
1432
    sheet.write(0, 18, "Preffered Seller Rating", heading_xf)
1433
    sheet.write(0, 19, "Preffered Seller Shipping Time", heading_xf)
1434
    sheet.write(0, 20, "Preffered Seller SP", heading_xf)
1435
    sheet.write(0, 21, "Preffered Seller TP", heading_xf)
1436
    sheet.write(0, 22, "Our Flipkart Inventory", heading_xf)
1437
    sheet.write(0, 23, "Our Net Availability",heading_xf)
1438
    sheet.write(0, 24, "Last Five Day Sale", heading_xf)
1439
    sheet.write(0, 25, "Average Sale", heading_xf)
1440
    sheet.write(0, 26, "Our NLC", heading_xf)
1441
    sheet.write(0, 27, "Lowest Possible SP", heading_xf)
1442
    sheet.write(0, 28, "Lowest Possible TP", heading_xf)
1443
    sheet.write(0, 29, "Total Seller", heading_xf)
11193 kshitij.so 1444
    sheet_iterator = 1
11615 kshitij.so 1445
 
11622 kshitij.so 1446
    cheapNotPrefferedItems = session.query(MarketPlaceHistory,FlipkartItem,MarketplaceItems,Item)\
1447
    .join((FlipkartItem,MarketPlaceHistory.item_id==FlipkartItem.item_id))\
1448
    .join((MarketplaceItems,MarketPlaceHistory.item_id==MarketplaceItems.itemId))\
1449
    .join((Item,MarketPlaceHistory.item_id==Item.id))\
11615 kshitij.so 1450
    .filter(MarketplaceItems.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.source==OrderSource.FLIPKART)\
1451
    .filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.CHEAP_BUT_NOT_PREF).all()
1452
 
1453
    for item in cheapNotPrefferedItems:
1454
        mpHistory = item[0]
1455
        flipkartItem = item[1]
1456
        mpItem = item[2]
1457
        catItem = item[3]
1458
        sheet.write(sheet_iterator,0,mpHistory.item_id)
1459
        sheet.write(sheet_iterator,1,categoryMap.get(catItem.category)[0])
1460
        sheet.write(sheet_iterator,2,categoryMap.get(catItem.category)[1])
1461
        sheet.write(sheet_iterator,3,flipkartItem.flipkartSerialNumber)
1462
        sheet.write(sheet_iterator,4,catItem.brand)
1463
        sheet.write(sheet_iterator,5,xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color))
1464
        sheet.write(sheet_iterator,6,catItem.weight)
1465
        sheet.write(sheet_iterator,7,mpItem.courierCost)
1466
        sheet.write(sheet_iterator,8,catItem.risky)
11790 kshitij.so 1467
        sheet.write(sheet_iterator,9,mpItem.commission)
1468
        sheet.write(sheet_iterator,10,mpItem.returnProvision)
1469
        sheet.write(sheet_iterator,11,mpHistory.ourRank)
1470
        sheet.write(sheet_iterator,12,mpHistory.lowestSellerName)
1471
        sheet.write(sheet_iterator,13,mpHistory.ourRating)
11615 kshitij.so 1472
#        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1473
#        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
11790 kshitij.so 1474
        sheet.write(sheet_iterator,14,mpHistory.lowestSellerShippingTime)
1475
        sheet.write(sheet_iterator,15,mpHistory.lowestSellingPrice)
1476
        sheet.write(sheet_iterator,16,mpHistory.lowestTp)
1477
        sheet.write(sheet_iterator,17,mpHistory.prefferedSellerName)
1478
        sheet.write(sheet_iterator,18,mpHistory.prefferedSellerRating)
11615 kshitij.so 1479
#        prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1480
#        else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
11790 kshitij.so 1481
        sheet.write(sheet_iterator,19,mpHistory.prefferedSellerShippingTime)
1482
        sheet.write(sheet_iterator,20,mpHistory.prefferedSellerSellingPrice)
1483
        sheet.write(sheet_iterator,21,mpHistory.prefferedSellerTp)
1484
        sheet.write(sheet_iterator,22,mpHistory.ourInventory)
11615 kshitij.so 1485
        if (not inventoryMap.has_key(mpHistory.item_id)):
11790 kshitij.so 1486
            sheet.write(sheet_iterator, 23, 'Info not available')
11193 kshitij.so 1487
        else:
11790 kshitij.so 1488
            sheet.write(sheet_iterator, 23, getNetAvailability(inventoryMap.get(mpHistory.item_id)))
1489
        sheet.write(sheet_iterator, 24, getOosString((itemSaleMap.get(mpHistory.item_id))[1]))
1490
        sheet.write(sheet_iterator, 25, (itemSaleMap.get(mpHistory.item_id))[3])
1491
        sheet.write(sheet_iterator, 26, mpHistory.ourNlc)
1492
        sheet.write(sheet_iterator, 27, mpHistory.lowestPossibleSp)
1493
        sheet.write(sheet_iterator, 28, mpHistory.lowestPossibleTp)
11193 kshitij.so 1494
        #proposed_sp = max(flipkartDetails.secondLowestSellerSp - max((20, flipkartDetails.secondLowestSellerSp*0.002)), flipkartPricing.lowestPossibleSp)
1495
        #proposed_tp = getTargetTp(proposed_sp,mpItem)
1496
        #target_nlc = proposed_tp - flipkartPricing.lowestPossibleTp + flipkartItemInfo.nlc
11790 kshitij.so 1497
        sheet.write(sheet_iterator, 29, mpHistory.totalSeller)
11193 kshitij.so 1498
        sheet_iterator+=1
11615 kshitij.so 1499
 
1500
    cheapNotPrefferedItems[:]=[]
11193 kshitij.so 1501
 
1502
    sheet = wbk.add_sheet('Can Compete-With Inventory')
1503
    xstr = lambda s: s or ""
1504
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1505
 
1506
    excel_integer_format = '0'
1507
    integer_style = xlwt.XFStyle()
1508
    integer_style.num_format_str = excel_integer_format
1509
 
1510
    sheet.write(0, 0, "Item ID", heading_xf)
1511
    sheet.write(0, 1, "Category", heading_xf)
1512
    sheet.write(0, 2, "Product Group.", heading_xf)
1513
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1514
    sheet.write(0, 4, "Brand", heading_xf)
1515
    sheet.write(0, 5, "Product Name", heading_xf)
1516
    sheet.write(0, 6, "Weight", heading_xf)
1517
    sheet.write(0, 7, "Courier Cost", heading_xf)
1518
    sheet.write(0, 8, "Risky", heading_xf)
11790 kshitij.so 1519
    sheet.write(0, 9, "Commission Rate", heading_xf)
1520
    sheet.write(0, 10, "Return Provision", heading_xf)
1521
    sheet.write(0, 11, "Our Rating", heading_xf)
1522
    sheet.write(0, 12, "Our Shipping Time", heading_xf)
1523
    sheet.write(0, 13, "Our Rank", heading_xf)
1524
    sheet.write(0, 14, "Our SP", heading_xf)
1525
    sheet.write(0, 15, "Our TP", heading_xf)
1526
    sheet.write(0, 16, "Lowest Seller", heading_xf)
1527
    sheet.write(0, 17, "Lowest Seller Rating", heading_xf)
1528
    sheet.write(0, 18, "Lowest Seller Shipping Time", heading_xf)
1529
    sheet.write(0, 19, "Lowest Seller SP", heading_xf)
1530
    sheet.write(0, 20, "Lowest Seller TP", heading_xf)
1531
    sheet.write(0, 21, "Preffered Seller", heading_xf)
1532
    sheet.write(0, 22, "Preffered Seller Rating", heading_xf)
1533
    sheet.write(0, 23, "Preffered Seller Shipping Time", heading_xf)
1534
    sheet.write(0, 24, "Preffer Seller SP", heading_xf)
1535
    sheet.write(0, 25, "Preffered Seller TP", heading_xf)
1536
    sheet.write(0, 26, "Our Flipkart Inventory", heading_xf)
1537
    sheet.write(0, 27, "Our Net Availability",heading_xf)
1538
    sheet.write(0, 28, "Last Five Day Sale", heading_xf)
1539
    sheet.write(0, 29, "Average Sale", heading_xf)
1540
    sheet.write(0, 30, "Our NLC", heading_xf)
1541
    sheet.write(0, 31, "Lowest Possible SP", heading_xf)
1542
    sheet.write(0, 32, "Lowest Possible TP", heading_xf)
1543
    sheet.write(0, 33, "Target SP", heading_xf)
1544
    sheet.write(0, 34, "Target TP", heading_xf)  
1545
    sheet.write(0, 35, "Target NLC", heading_xf)
1546
    sheet.write(0, 36, "Sales Potential", heading_xf)
1547
    sheet.write(0, 37, "Total Seller", heading_xf)
1548
    sheet.write(0, 38, "Auto Pricing Decision", heading_xf)
1549
    sheet.write(0, 39, "Reason", heading_xf)
1550
    sheet.write(0, 40, "Updated Price", heading_xf)
11193 kshitij.so 1551
    sheet_iterator = 1
11615 kshitij.so 1552
 
11622 kshitij.so 1553
    competitiveItems = session.query(MarketPlaceHistory,FlipkartItem,MarketplaceItems,Item)\
1554
    .join((FlipkartItem,MarketPlaceHistory.item_id==FlipkartItem.item_id))\
1555
    .join((MarketplaceItems,MarketPlaceHistory.item_id==MarketplaceItems.itemId))\
1556
    .join((Item,MarketPlaceHistory.item_id==Item.id))\
11615 kshitij.so 1557
    .filter(MarketplaceItems.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.source==OrderSource.FLIPKART)\
1558
    .filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.COMPETITIVE).all()
1559
 
1560
    for item in competitiveItems:
1561
        mpHistory = item[0]
1562
        flipkartItem = item[1]
1563
        mpItem = item[2]
1564
        catItem = item[3]
1565
        sheet.write(sheet_iterator,0,mpHistory.item_id)
1566
        sheet.write(sheet_iterator,1,categoryMap.get(catItem.category)[0])
1567
        sheet.write(sheet_iterator,2,categoryMap.get(catItem.category)[1])
1568
        sheet.write(sheet_iterator,3,flipkartItem.flipkartSerialNumber)
1569
        sheet.write(sheet_iterator,4,catItem.brand)
1570
        sheet.write(sheet_iterator,5,xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color))
1571
        sheet.write(sheet_iterator,6,catItem.weight)
1572
        sheet.write(sheet_iterator,7,mpItem.courierCost)
1573
        sheet.write(sheet_iterator,8,catItem.risky)
11790 kshitij.so 1574
        sheet.write(sheet_iterator,9,mpItem.commission)
1575
        sheet.write(sheet_iterator,10,mpItem.returnProvision)
1576
        sheet.write(sheet_iterator,11,mpHistory.ourRating)
11615 kshitij.so 1577
#        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1578
#        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
11790 kshitij.so 1579
        sheet.write(sheet_iterator,12,mpHistory.ourShippingTime)
1580
        sheet.write(sheet_iterator,13,mpHistory.ourRank)
1581
        sheet.write(sheet_iterator,14,mpHistory.ourSellingPrice)
1582
        sheet.write(sheet_iterator,15,mpHistory.ourTp)
1583
        sheet.write(sheet_iterator,16,mpHistory.lowestSellerName)
1584
        sheet.write(sheet_iterator,17,mpHistory.lowestSellerRating)
11615 kshitij.so 1585
#        lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1586
#        else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
11790 kshitij.so 1587
        sheet.write(sheet_iterator,18,mpHistory.lowestSellerShippingTime)
1588
        sheet.write(sheet_iterator,19,mpHistory.lowestSellingPrice)
1589
        sheet.write(sheet_iterator,20,mpHistory.lowestTp)
1590
        sheet.write(sheet_iterator,21,mpHistory.prefferedSellerName)
1591
        sheet.write(sheet_iterator,22,mpHistory.prefferedSellerRating)
11615 kshitij.so 1592
#        prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1593
#        else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
11790 kshitij.so 1594
        sheet.write(sheet_iterator,23,mpHistory.prefferedSellerShippingTime)
1595
        sheet.write(sheet_iterator,24,mpHistory.prefferedSellerSellingPrice)
1596
        sheet.write(sheet_iterator,25,mpHistory.prefferedSellerTp)
1597
        sheet.write(sheet_iterator,26,mpHistory.ourInventory)
11615 kshitij.so 1598
        if (not inventoryMap.has_key(mpHistory.item_id)):
11790 kshitij.so 1599
            sheet.write(sheet_iterator, 27, 'Info not available')
11193 kshitij.so 1600
        else:
11790 kshitij.so 1601
            sheet.write(sheet_iterator, 27, getNetAvailability(inventoryMap.get(mpHistory.item_id)))
1602
        sheet.write(sheet_iterator, 28, getOosString((itemSaleMap.get(mpHistory.item_id))[1]))
1603
        sheet.write(sheet_iterator, 29, (itemSaleMap.get(mpHistory.item_id))[3])
1604
        sheet.write(sheet_iterator, 30, mpHistory.ourNlc)
1605
        sheet.write(sheet_iterator, 31, mpHistory.lowestPossibleSp)
1606
        sheet.write(sheet_iterator, 32, mpHistory.lowestPossibleTp)
11775 kshitij.so 1607
        proposed_sp = max(mpHistory.lowestSellingPrice - max((10, mpHistory.lowestSellingPrice*0.001)), mpHistory.lowestPossibleSp)
11193 kshitij.so 1608
        proposed_tp = getTargetTp(proposed_sp,mpItem)
11615 kshitij.so 1609
        target_nlc = proposed_tp - mpHistory.lowestPossibleTp + mpHistory.ourNlc
11790 kshitij.so 1610
        sheet.write(sheet_iterator, 33, proposed_sp)
1611
        sheet.write(sheet_iterator, 34, proposed_tp)
1612
        sheet.write(sheet_iterator, 35, target_nlc)
1613
        sheet.write(sheet_iterator, 36, getSalesPotential(mpHistory.lowestSellingPrice,mpHistory.ourNlc))
1614
        sheet.write(sheet_iterator, 37, mpHistory.totalSeller)
11775 kshitij.so 1615
        if mpHistory.decision is None:
11790 kshitij.so 1616
            sheet.write(sheet_iterator, 38, 'Auto Pricing Inactive')
11775 kshitij.so 1617
            sheet_iterator+=1
1618
            continue
11790 kshitij.so 1619
        sheet.write(sheet_iterator, 38, Decision._VALUES_TO_NAMES.get(mpHistory.decision))
1620
        sheet.write(sheet_iterator, 39, mpHistory.reason)
11776 kshitij.so 1621
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_DECREMENT_SUCCESS":
11790 kshitij.so 1622
            sheet.write(sheet_iterator, 40, math.ceil(mpHistory.proposedSellingPrice))
11776 kshitij.so 1623
        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_INCREMENT_SUCCESS":
11790 kshitij.so 1624
            sheet.write(sheet_iterator, 40, math.ceil(mpHistory.ourSellingPrice+max(10,.01*mpHistory.ourSellingPrice)))
11775 kshitij.so 1625
 
11193 kshitij.so 1626
        sheet_iterator+=1
11615 kshitij.so 1627
 
1628
    competitiveItems[:]=[]
1629
 
11193 kshitij.so 1630
    sheet = wbk.add_sheet('Negative Margin')
1631
    xstr = lambda s: s or ""
1632
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1633
 
1634
    excel_integer_format = '0'
1635
    integer_style = xlwt.XFStyle()
1636
    integer_style.num_format_str = excel_integer_format
1637
 
1638
    sheet.write(0, 0, "Item ID", heading_xf)
1639
    sheet.write(0, 1, "Category", heading_xf)
1640
    sheet.write(0, 2, "Product Group.", heading_xf)
1641
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1642
    sheet.write(0, 4, "Brand", heading_xf)
1643
    sheet.write(0, 5, "Product Name", heading_xf)
1644
    sheet.write(0, 6, "Weight", heading_xf)
1645
    sheet.write(0, 7, "Courier Cost", heading_xf)
1646
    sheet.write(0, 8, "Risky", heading_xf)
11790 kshitij.so 1647
    sheet.write(0, 9, "Commission Rate", heading_xf)
1648
    sheet.write(0, 10, "Return Provision", heading_xf)
1649
    sheet.write(0, 11, "Our Rating", heading_xf)
1650
    sheet.write(0, 12, "Our Shipping Time", heading_xf)
1651
    sheet.write(0, 13, "Our Rank", heading_xf)
1652
    sheet.write(0, 14, "Our SP", heading_xf)
1653
    sheet.write(0, 15, "Our TP", heading_xf)
1654
    sheet.write(0, 16, "Lowest Seller", heading_xf)
1655
    sheet.write(0, 17, "Lowest Seller Rating", heading_xf)
1656
    sheet.write(0, 18, "Lowest Seller Shipping Time", heading_xf)
1657
    sheet.write(0, 19, "Lowest Seller SP", heading_xf)
1658
    sheet.write(0, 20, "Lowest Seller TP", heading_xf)
1659
    sheet.write(0, 21, "Preffered Seller", heading_xf)
1660
    sheet.write(0, 22, "Preffered Seller Rating", heading_xf)
1661
    sheet.write(0, 23, "Preffered Seller Shipping Time", heading_xf)
1662
    sheet.write(0, 24, "Preffer Seller SP", heading_xf)
1663
    sheet.write(0, 25, "Preffered Seller TP", heading_xf)
1664
    sheet.write(0, 26, "Our Flipkart Inventory", heading_xf)
1665
    sheet.write(0, 27, "Our Net Availability",heading_xf)
1666
    sheet.write(0, 28, "Last Five Day Sale", heading_xf)
1667
    sheet.write(0, 29, "Average Sale", heading_xf)
1668
    sheet.write(0, 30, "Our NLC", heading_xf)
1669
    sheet.write(0, 31, "Lowest Possible SP", heading_xf)
1670
    sheet.write(0, 32, "Lowest Possible TP", heading_xf)
1671
    sheet.write(0, 33, "Margin", heading_xf)
1672
    sheet.write(0, 34, "Total Seller", heading_xf)
11193 kshitij.so 1673
    sheet_iterator = 1
11615 kshitij.so 1674
 
11622 kshitij.so 1675
    negativeMargin = session.query(MarketPlaceHistory,FlipkartItem,MarketplaceItems,Item)\
1676
    .join((FlipkartItem,MarketPlaceHistory.item_id==FlipkartItem.item_id))\
1677
    .join((MarketplaceItems,MarketPlaceHistory.item_id==MarketplaceItems.itemId))\
1678
    .join((Item,MarketPlaceHistory.item_id==Item.id))\
11615 kshitij.so 1679
    .filter(MarketplaceItems.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.source==OrderSource.FLIPKART)\
1680
    .filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.NEGATIVE_MARGIN).all()
1681
 
11193 kshitij.so 1682
    for item in negativeMargin:
11615 kshitij.so 1683
        mpHistory = item[0]
1684
        flipkartItem = item[1]
1685
        mpItem = item[2]
1686
        catItem = item[3]
1687
        sheet.write(sheet_iterator,0,mpHistory.item_id)
1688
        sheet.write(sheet_iterator,1,categoryMap.get(catItem.category)[0])
1689
        sheet.write(sheet_iterator,2,categoryMap.get(catItem.category)[1])
1690
        sheet.write(sheet_iterator,3,flipkartItem.flipkartSerialNumber)
1691
        sheet.write(sheet_iterator,4,catItem.brand)
1692
        sheet.write(sheet_iterator,5,xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color))
1693
        sheet.write(sheet_iterator,6,catItem.weight)
1694
        sheet.write(sheet_iterator,7,mpItem.courierCost)
1695
        sheet.write(sheet_iterator,8,catItem.risky)
11790 kshitij.so 1696
        sheet.write(sheet_iterator,9,mpItem.commission)
1697
        sheet.write(sheet_iterator,10,mpItem.returnProvision)
1698
        sheet.write(sheet_iterator,11,mpHistory.ourRating)
11615 kshitij.so 1699
#        ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1700
#        else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
11790 kshitij.so 1701
        sheet.write(sheet_iterator,12,mpHistory.ourShippingTime)
1702
        sheet.write(sheet_iterator,13,mpHistory.ourRank)
1703
        sheet.write(sheet_iterator,14,mpHistory.ourSellingPrice)
1704
        sheet.write(sheet_iterator,15,mpHistory.ourTp)
1705
        sheet.write(sheet_iterator,16,mpHistory.lowestSellerName)
1706
        sheet.write(sheet_iterator,17,mpHistory.lowestSellerRating)
11615 kshitij.so 1707
#        lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1708
#        else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
11790 kshitij.so 1709
        sheet.write(sheet_iterator,18,mpHistory.lowestSellerShippingTime)
1710
        sheet.write(sheet_iterator,19,mpHistory.lowestSellingPrice)
1711
        sheet.write(sheet_iterator,20,mpHistory.lowestTp)
1712
        sheet.write(sheet_iterator,21,mpHistory.prefferedSellerName)
1713
        sheet.write(sheet_iterator,22,mpHistory.prefferedSellerRating)
11615 kshitij.so 1714
#        prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1715
#        else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
11790 kshitij.so 1716
        sheet.write(sheet_iterator,23,mpHistory.prefferedSellerShippingTime)
1717
        sheet.write(sheet_iterator,24,mpHistory.prefferedSellerSellingPrice)
1718
        sheet.write(sheet_iterator,25,mpHistory.prefferedSellerTp)
1719
        sheet.write(sheet_iterator,26,mpHistory.ourInventory)
11615 kshitij.so 1720
        if (not inventoryMap.has_key(mpHistory.item_id)):
11790 kshitij.so 1721
            sheet.write(sheet_iterator, 27, 'Info not available')
11193 kshitij.so 1722
        else:
11790 kshitij.so 1723
            sheet.write(sheet_iterator, 27, getNetAvailability(inventoryMap.get(mpHistory.item_id)))
1724
        sheet.write(sheet_iterator, 28, getOosString((itemSaleMap.get(mpHistory.item_id))[1]))
1725
        sheet.write(sheet_iterator, 29, (itemSaleMap.get(mpHistory.item_id))[3])
1726
        sheet.write(sheet_iterator, 30, mpHistory.ourNlc)
1727
        sheet.write(sheet_iterator, 31, mpHistory.lowestPossibleSp)
1728
        sheet.write(sheet_iterator, 32, mpHistory.lowestPossibleTp)
1729
        sheet.write(sheet_iterator, 33, round((mpHistory.ourTp - mpHistory.lowestPossibleTp),2))
1730
        sheet.write(sheet_iterator, 34, mpHistory.totalSeller)
11193 kshitij.so 1731
        sheet_iterator+=1
11615 kshitij.so 1732
 
1733
    negativeMargin[:]=[]
11193 kshitij.so 1734
 
1735
    if (runType=='FULL'):    
1736
        sheet = wbk.add_sheet('Auto Favorites')
1737
 
1738
        heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1739
 
1740
        excel_integer_format = '0'
1741
        integer_style = xlwt.XFStyle()
1742
        integer_style.num_format_str = excel_integer_format
1743
        xstr = lambda s: s or ""
1744
 
1745
        sheet.write(0, 0, "Item ID", heading_xf)
1746
        sheet.write(0, 1, "Brand", heading_xf)
1747
        sheet.write(0, 2, "Product Name", heading_xf)
1748
        sheet.write(0, 3, "Auto Favourite", heading_xf)
1749
        sheet.write(0, 4, "Reason", heading_xf)
1750
 
1751
        sheet_iterator=1
1752
        for autoFav in nowAutoFav:
1753
            itemId = autoFav[0]
1754
            reason = autoFav[1]
1755
            it = Item.query.filter_by(id=itemId).one()
1756
            sheet.write(sheet_iterator, 0, itemId)
1757
            sheet.write(sheet_iterator, 1, it.brand)
1758
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1759
            sheet.write(sheet_iterator, 3, "True")
1760
            sheet.write(sheet_iterator, 4, reason)
1761
            sheet_iterator+=1
1762
        for prevFav in previousAutoFav:
1763
            it = Item.query.filter_by(id=prevFav).one()
1764
            sheet.write(sheet_iterator, 0, prevFav)
1765
            sheet.write(sheet_iterator, 1, it.brand)
1766
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1767
            sheet.write(sheet_iterator, 3, "False")
1768
            sheet_iterator+=1
1769
 
1770
    sheet = wbk.add_sheet('Exception Item List')
1771
 
1772
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1773
 
1774
    excel_integer_format = '0'
1775
    integer_style = xlwt.XFStyle()
1776
    integer_style.num_format_str = excel_integer_format
1777
    xstr = lambda s: s or ""
1778
 
1779
    sheet.write(0, 0, "Item ID", heading_xf)
1780
    sheet.write(0, 1, "FK Serial number", heading_xf)
1781
    sheet.write(0, 2, "Brand", heading_xf)
1782
    sheet.write(0, 3, "Product Name", heading_xf)
1783
    sheet.write(0, 4, "Reason", heading_xf)
1784
    sheet_iterator=1
11615 kshitij.so 1785
 
11622 kshitij.so 1786
    exeptionItems = session.query(MarketPlaceHistory,FlipkartItem,MarketplaceItems,Item)\
1787
    .join((FlipkartItem,MarketPlaceHistory.item_id==FlipkartItem.item_id))\
1788
    .join((MarketplaceItems,MarketPlaceHistory.item_id==MarketplaceItems.itemId))\
1789
    .join((Item,MarketPlaceHistory.item_id==Item.id))\
11615 kshitij.so 1790
    .filter(MarketplaceItems.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.source==OrderSource.FLIPKART)\
1791
    .filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.EXCEPTION).all()
1792
 
1793
    for item in exeptionItems:
1794
        mpHistory = item[0]
1795
        flipkartItem = item[1]
1796
        mpItem = item[2]
1797
        catItem = item[3]
1798
        sheet.write(sheet_iterator, 0, mpHistory.item_id)
1799
        sheet.write(sheet_iterator, 1, flipkartItem.flipkartSerialNumber)
1800
        sheet.write(sheet_iterator, 2, catItem.brand)
1801
        sheet.write(sheet_iterator, 3, xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color))
11193 kshitij.so 1802
        try:
11615 kshitij.so 1803
            if mpHistory.totalSeller is None:
11193 kshitij.so 1804
                pass
1805
        except:
1806
            sheet.write(sheet_iterator, 4, "Unable to fetch info from Flipkart")
1807
            sheet_iterator+=1
1808
            continue
1809
        sheet.write(sheet_iterator, 4, "No Seller Available")
1810
        sheet_iterator+=1
11615 kshitij.so 1811
 
1812
    exeptionItems[:]=[]
11193 kshitij.so 1813
 
1814
    sheet = wbk.add_sheet('Can Compete-No Inv')
1815
    xstr = lambda s: s or ""
1816
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1817
 
1818
    excel_integer_format = '0'
1819
    integer_style = xlwt.XFStyle()
1820
    integer_style.num_format_str = excel_integer_format
1821
 
1822
    sheet.write(0, 0, "Item ID", heading_xf)
1823
    sheet.write(0, 1, "Category", heading_xf)
1824
    sheet.write(0, 2, "Product Group.", heading_xf)
1825
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1826
    sheet.write(0, 4, "Brand", heading_xf)
1827
    sheet.write(0, 5, "Product Name", heading_xf)
1828
    sheet.write(0, 6, "Weight", heading_xf)
1829
    sheet.write(0, 7, "Courier Cost", heading_xf)
1830
    sheet.write(0, 8, "Risky", heading_xf)
11790 kshitij.so 1831
    sheet.write(0, 9, "Commission Rate", heading_xf)
1832
    sheet.write(0, 10, "Return Provision", heading_xf)
1833
    sheet.write(0, 11, "Our Rating", heading_xf)
1834
    sheet.write(0, 12, "Our Shipping Time", heading_xf)
1835
    sheet.write(0, 13, "Our Rank", heading_xf)
1836
    sheet.write(0, 14, "Our SP", heading_xf)
1837
    sheet.write(0, 15, "Our TP", heading_xf)
1838
    sheet.write(0, 16, "Lowest Seller", heading_xf)
1839
    sheet.write(0, 17, "Lowest Seller Rating", heading_xf)
1840
    sheet.write(0, 18, "Lowest Seller Shipping Time", heading_xf)
1841
    sheet.write(0, 19, "Lowest Seller SP", heading_xf)
1842
    sheet.write(0, 20, "Lowest Seller TP", heading_xf)
1843
    sheet.write(0, 21, "Preffered Seller", heading_xf)
1844
    sheet.write(0, 22, "Preffered Seller Rating", heading_xf)
1845
    sheet.write(0, 23, "Preffered Seller Shipping Time", heading_xf)
1846
    sheet.write(0, 24, "Preffer Seller SP", heading_xf)
1847
    sheet.write(0, 25, "Preffered Seller TP", heading_xf)
1848
    sheet.write(0, 26, "Our Flipkart Inventory", heading_xf)
1849
    sheet.write(0, 27, "Our Net Availability",heading_xf)
1850
    sheet.write(0, 28, "Last Five Day Sale", heading_xf)
1851
    sheet.write(0, 29, "Average Sale", heading_xf)
1852
    sheet.write(0, 30, "Our NLC", heading_xf)
1853
    sheet.write(0, 31, "Lowest Possible SP", heading_xf)
1854
    sheet.write(0, 32, "Lowest Possible TP", heading_xf)
1855
    sheet.write(0, 33, "Target SP", heading_xf)
1856
    sheet.write(0, 34, "Target TP", heading_xf)  
1857
    sheet.write(0, 35, "Sales Potential", heading_xf)
1858
    sheet.write(0, 36, "Total Seller", heading_xf)
11193 kshitij.so 1859
    sheet_iterator = 1
11615 kshitij.so 1860
 
11622 kshitij.so 1861
    competitiveNoInventory = session.query(MarketPlaceHistory,FlipkartItem,MarketplaceItems,Item)\
1862
    .join((FlipkartItem,MarketPlaceHistory.item_id==FlipkartItem.item_id))\
1863
    .join((MarketplaceItems,MarketPlaceHistory.item_id==MarketplaceItems.itemId))\
1864
    .join((Item,MarketPlaceHistory.item_id==Item.id))\
11615 kshitij.so 1865
    .filter(MarketplaceItems.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.source==OrderSource.FLIPKART)\
1866
    .filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.COMPETITIVE_NO_INVENTORY).all()
1867
 
11193 kshitij.so 1868
    for item in competitiveNoInventory:
11615 kshitij.so 1869
        mpHistory = item[0]
1870
        flipkartItem = item[1]
1871
        mpItem = item[2]
1872
        catItem = item[3]
1873
        if ((not inventoryMap.has_key(mpHistory.item_id)) or getNetAvailability(inventoryMap.get(mpHistory.item_id))<=0):
1874
            sheet.write(sheet_iterator,0,mpHistory.item_id)
1875
            sheet.write(sheet_iterator,1,categoryMap.get(catItem.category)[0])
1876
            sheet.write(sheet_iterator,2,categoryMap.get(catItem.category)[1])
1877
            sheet.write(sheet_iterator,3,flipkartItem.flipkartSerialNumber)
1878
            sheet.write(sheet_iterator,4,catItem.brand)
1879
            sheet.write(sheet_iterator,5,xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color))
1880
            sheet.write(sheet_iterator,6,catItem.weight)
1881
            sheet.write(sheet_iterator,7,mpItem.courierCost)
1882
            sheet.write(sheet_iterator,8,catItem.risky)
11790 kshitij.so 1883
            sheet.write(sheet_iterator,9,mpItem.commission)
1884
            sheet.write(sheet_iterator,10,mpItem.returnProvision)
1885
            sheet.write(sheet_iterator,11,mpHistory.ourRating)
11615 kshitij.so 1886
#            ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1887
#            else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
11790 kshitij.so 1888
            sheet.write(sheet_iterator,12,mpHistory.ourShippingTime)
1889
            sheet.write(sheet_iterator,13,mpHistory.ourRank)
1890
            sheet.write(sheet_iterator,14,mpHistory.ourSellingPrice)
1891
            sheet.write(sheet_iterator,15,mpHistory.ourTp)
1892
            sheet.write(sheet_iterator,16,mpHistory.lowestSellerName)
1893
            sheet.write(sheet_iterator,17,mpHistory.lowestSellerRating)
11615 kshitij.so 1894
#            lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1895
#            else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
11790 kshitij.so 1896
            sheet.write(sheet_iterator,18,mpHistory.lowestSellerShippingTime)
1897
            sheet.write(sheet_iterator,19,mpHistory.lowestSellingPrice)
1898
            sheet.write(sheet_iterator,20,mpHistory.lowestTp)
1899
            sheet.write(sheet_iterator,21,mpHistory.prefferedSellerName)
1900
            sheet.write(sheet_iterator,22,mpHistory.prefferedSellerRating)
11615 kshitij.so 1901
#            prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
1902
#            else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
11790 kshitij.so 1903
            sheet.write(sheet_iterator,23,mpHistory.prefferedSellerShippingTime)
1904
            sheet.write(sheet_iterator,24,mpHistory.prefferedSellerSellingPrice)
1905
            sheet.write(sheet_iterator,25,mpHistory.prefferedSellerTp)
1906
            sheet.write(sheet_iterator,26,mpHistory.ourInventory)
11615 kshitij.so 1907
            if (not inventoryMap.has_key(mpHistory.item_id)):
11790 kshitij.so 1908
                sheet.write(sheet_iterator, 27, 'Info not available')
11193 kshitij.so 1909
            else:
11790 kshitij.so 1910
                sheet.write(sheet_iterator, 27, getNetAvailability(inventoryMap.get(mpHistory.item_id)))
1911
            sheet.write(sheet_iterator, 28, getOosString((itemSaleMap.get(mpHistory.item_id))[1]))
1912
            sheet.write(sheet_iterator, 29, (itemSaleMap.get(mpHistory.item_id))[3])
1913
            sheet.write(sheet_iterator, 30, mpHistory.ourNlc)
1914
            sheet.write(sheet_iterator, 31, mpHistory.lowestPossibleSp)
1915
            sheet.write(sheet_iterator, 32, mpHistory.lowestPossibleTp)
11615 kshitij.so 1916
            proposed_sp = max(mpHistory.lowestSellingPrice - max((10, mpHistory.lowestSellingPrice*0.001)), mpHistory.lowestPossibleSp)
11193 kshitij.so 1917
            proposed_tp = getTargetTp(proposed_sp,mpItem)
11790 kshitij.so 1918
            sheet.write(sheet_iterator, 33, proposed_sp)
1919
            sheet.write(sheet_iterator, 34, proposed_tp)
1920
            sheet.write(sheet_iterator, 35, getSalesPotential(mpHistory.lowestPossibleSp,mpHistory.ourNlc))
1921
            sheet.write(sheet_iterator, 36, mpHistory.totalSeller)
11193 kshitij.so 1922
            sheet_iterator+=1
1923
 
11615 kshitij.so 1924
 
11193 kshitij.so 1925
    sheet = wbk.add_sheet('Can Compete-No Inv On FK')
1926
    xstr = lambda s: s or ""
1927
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1928
 
1929
    excel_integer_format = '0'
1930
    integer_style = xlwt.XFStyle()
1931
    integer_style.num_format_str = excel_integer_format
1932
 
1933
    sheet.write(0, 0, "Item ID", heading_xf)
1934
    sheet.write(0, 1, "Category", heading_xf)
1935
    sheet.write(0, 2, "Product Group.", heading_xf)
1936
    sheet.write(0, 3, "FK Serial Number", heading_xf)
1937
    sheet.write(0, 4, "Brand", heading_xf)
1938
    sheet.write(0, 5, "Product Name", heading_xf)
1939
    sheet.write(0, 6, "Weight", heading_xf)
1940
    sheet.write(0, 7, "Courier Cost", heading_xf)
1941
    sheet.write(0, 8, "Risky", heading_xf)
11790 kshitij.so 1942
    sheet.write(0, 9, "Commission Rate", heading_xf)
1943
    sheet.write(0, 10, "Return Provision", heading_xf)
1944
    sheet.write(0, 11, "Our Rating", heading_xf)
1945
    sheet.write(0, 12, "Our Shipping Time", heading_xf)
1946
    sheet.write(0, 13, "Our Rank", heading_xf)
1947
    sheet.write(0, 14, "Our SP", heading_xf)
1948
    sheet.write(0, 15, "Our TP", heading_xf)
1949
    sheet.write(0, 16, "Lowest Seller", heading_xf)
1950
    sheet.write(0, 17, "Lowest Seller Rating", heading_xf)
1951
    sheet.write(0, 18, "Lowest Seller Shipping Time", heading_xf)
1952
    sheet.write(0, 19, "Lowest Seller SP", heading_xf)
1953
    sheet.write(0, 20, "Lowest Seller TP", heading_xf)
1954
    sheet.write(0, 21, "Preffered Seller", heading_xf)
1955
    sheet.write(0, 22, "Preffered Seller Rating", heading_xf)
1956
    sheet.write(0, 23, "Preffered Seller Shipping Time", heading_xf)
1957
    sheet.write(0, 24, "Preffer Seller SP", heading_xf)
1958
    sheet.write(0, 25, "Preffered Seller TP", heading_xf)
1959
    sheet.write(0, 26, "Our Flipkart Inventory", heading_xf)
1960
    sheet.write(0, 27, "Our Net Availability",heading_xf)
1961
    sheet.write(0, 28, "Last Five Day Sale", heading_xf)
1962
    sheet.write(0, 29, "Average Sale", heading_xf)
1963
    sheet.write(0, 30, "Our NLC", heading_xf)
1964
    sheet.write(0, 31, "Lowest Possible SP", heading_xf)
1965
    sheet.write(0, 32, "Lowest Possible TP", heading_xf)
1966
    sheet.write(0, 33, "Target SP", heading_xf)
1967
    sheet.write(0, 34, "Target TP", heading_xf)  
1968
    sheet.write(0, 35, "Sales Potential", heading_xf)
1969
    sheet.write(0, 36, "Total Seller", heading_xf)
11193 kshitij.so 1970
    sheet_iterator = 1
1971
    for item in competitiveNoInventory:
11615 kshitij.so 1972
        mpHistory = item[0]
1973
        flipkartItem = item[1]
1974
        mpItem = item[2]
1975
        catItem = item[3]
1976
        if (inventoryMap.has_key(mpHistory.item_id) and getNetAvailability(inventoryMap.get(mpHistory.item_id))>0):
1977
            sheet.write(sheet_iterator,0,mpHistory.item_id)
1978
            sheet.write(sheet_iterator,1,categoryMap.get(catItem.category)[0])
1979
            sheet.write(sheet_iterator,2,categoryMap.get(catItem.category)[1])
1980
            sheet.write(sheet_iterator,3,flipkartItem.flipkartSerialNumber)
1981
            sheet.write(sheet_iterator,4,catItem.brand)
1982
            sheet.write(sheet_iterator,5,xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color))
1983
            sheet.write(sheet_iterator,6,catItem.weight)
1984
            sheet.write(sheet_iterator,7,mpItem.courierCost)
1985
            sheet.write(sheet_iterator,8,catItem.risky)
11790 kshitij.so 1986
            sheet.write(sheet_iterator,9,mpItem.commission)
1987
            sheet.write(sheet_iterator,10,mpItem.returnProvision)
1988
            sheet.write(sheet_iterator,11,mpHistory.ourRating)
11615 kshitij.so 1989
#            ourShippingTime= str(flipkartDetails.shippingTimeLowerLimitOur) if flipkartDetails.shippingTimeUpperLimitOur==0\
1990
#            else str(flipkartDetails.shippingTimeLowerLimitOur)+'-'+str(flipkartDetails.shippingTimeUpperLimitOur)
11790 kshitij.so 1991
            sheet.write(sheet_iterator,12,mpHistory.ourShippingTime)
1992
            sheet.write(sheet_iterator,13,mpHistory.ourRank)
1993
            sheet.write(sheet_iterator,14,mpHistory.ourSellingPrice)
1994
            sheet.write(sheet_iterator,15,mpHistory.ourTp)
1995
            sheet.write(sheet_iterator,16,mpHistory.lowestSellerName)
1996
            sheet.write(sheet_iterator,17,mpHistory.lowestSellerRating)
11615 kshitij.so 1997
#            lowestSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitLowestSeller) if flipkartDetails.shippingTimeUpperLimitLowestSeller==0\
1998
#            else str(flipkartDetails.shippingTimeLowerLimitLowestSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitLowestSeller)
11790 kshitij.so 1999
            sheet.write(sheet_iterator,18,mpHistory.lowestSellerShippingTime)
2000
            sheet.write(sheet_iterator,19,mpHistory.lowestSellingPrice)
2001
            sheet.write(sheet_iterator,20,mpHistory.lowestTp)
2002
            sheet.write(sheet_iterator,21,mpHistory.prefferedSellerName)
2003
            sheet.write(sheet_iterator,22,mpHistory.prefferedSellerRating)
11615 kshitij.so 2004
#            prefferedSellerShippingTime= str(flipkartDetails.shippingTimeLowerLimitPrefSeller) if flipkartDetails.shippingTimeUpperLimitPrefSeller==0\
2005
#            else str(flipkartDetails.shippingTimeLowerLimitPrefSeller)+'-'+str(flipkartDetails.shippingTimeUpperLimitPrefSeller)
11790 kshitij.so 2006
            sheet.write(sheet_iterator,23,mpHistory.prefferedSellerShippingTime)
2007
            sheet.write(sheet_iterator,24,mpHistory.prefferedSellerSellingPrice)
2008
            sheet.write(sheet_iterator,25,mpHistory.prefferedSellerTp)
2009
            sheet.write(sheet_iterator,26,mpHistory.ourInventory)
11615 kshitij.so 2010
            if (not inventoryMap.has_key(mpHistory.item_id)):
11790 kshitij.so 2011
                sheet.write(sheet_iterator, 27, 'Info not available')
11193 kshitij.so 2012
            else:
11790 kshitij.so 2013
                sheet.write(sheet_iterator, 27, getNetAvailability(inventoryMap.get(mpHistory.item_id)))
2014
            sheet.write(sheet_iterator, 28, getOosString((itemSaleMap.get(mpHistory.item_id))[1]))
2015
            sheet.write(sheet_iterator, 29, (itemSaleMap.get(mpHistory.item_id))[3])
2016
            sheet.write(sheet_iterator, 30, mpHistory.ourNlc)
2017
            sheet.write(sheet_iterator, 31, mpHistory.lowestPossibleSp)
2018
            sheet.write(sheet_iterator, 32, mpHistory.lowestPossibleTp)
11615 kshitij.so 2019
            proposed_sp = max(mpHistory.lowestSellingPrice - max((10, mpHistory.lowestSellingPrice*0.001)), mpHistory.lowestPossibleSp)
11193 kshitij.so 2020
            proposed_tp = getTargetTp(proposed_sp,mpItem)
11790 kshitij.so 2021
            sheet.write(sheet_iterator, 33, proposed_sp)
2022
            sheet.write(sheet_iterator, 34, proposed_tp)
2023
            sheet.write(sheet_iterator, 35, getSalesPotential(mpHistory.lowestPossibleSp,mpHistory.ourNlc))
2024
            sheet.write(sheet_iterator, 36, mpHistory.totalSeller)
11193 kshitij.so 2025
            sheet_iterator+=1
11615 kshitij.so 2026
    competitiveNoInventory[:]=[]
11193 kshitij.so 2027
 
11775 kshitij.so 2028
#    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()
2029
#    sheet = wbk.add_sheet('Auto Inc and Dec')
2030
#
2031
#    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
2032
#    
2033
#    excel_integer_format = '0'
2034
#    integer_style = xlwt.XFStyle()
2035
#    integer_style.num_format_str = excel_integer_format
2036
#    xstr = lambda s: s or ""
2037
#    
2038
#    sheet.write(0, 0, "Item ID", heading_xf)
2039
#    sheet.write(0, 1, "Brand", heading_xf)
2040
#    sheet.write(0, 2, "Product Name", heading_xf)
2041
#    sheet.write(0, 3, "Decision", heading_xf)
2042
#    sheet.write(0, 4, "Reason", heading_xf)
2043
#    sheet.write(0, 5, "Old Selling Price", heading_xf)
2044
#    sheet.write(0, 6, "Selling Price Updated",heading_xf)
2045
#    
2046
#    sheet_iterator=1
2047
#    for autoPricingItem in autoPricingItems:
2048
#        mpHistory = autoPricingItem[0]
2049
#        item = autoPricingItem[1]
2050
#        it = Item.query.filter_by(id=item.id).one()
2051
#        sheet.write(sheet_iterator, 0, item.id)
2052
#        sheet.write(sheet_iterator, 1, it.brand)
2053
#        sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
2054
#        sheet.write(sheet_iterator, 3, Decision._VALUES_TO_NAMES.get(mpHistory.decision))
2055
#        sheet.write(sheet_iterator, 4, mpHistory.reason)
2056
#        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_DECREMENT_SUCCESS":
2057
#            sheet.write(sheet_iterator, 5, mpHistory.ourSellingPrice)
2058
#            sheet.write(sheet_iterator, 6, math.ceil(mpHistory.proposedSellingPrice))
2059
#        if Decision._VALUES_TO_NAMES.get(mpHistory.decision) == "AUTO_INCREMENT_SUCCESS":
2060
#            sheet.write(sheet_iterator, 5, mpHistory.ourSellingPrice)
2061
#            sheet.write(sheet_iterator, 6, math.ceil(mpHistory.ourSellingPrice+max(10,.01*mpHistory.ourSellingPrice)))
2062
#        sheet_iterator+=1
11193 kshitij.so 2063
 
2064
    filename = "/tmp/flipkart-report-"+runType+" " + str(timestamp) + ".xls"
2065
    wbk.save(filename)
2066
    try:
11765 kshitij.so 2067
        EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["kshitij.sood@saholic.com"], " Flipkart Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], [""], [])
2068
        #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 2069
    except Exception as e:
2070
        print e
2071
        print "Unable to send report.Trying with local SMTP"
2072
        smtpServer = smtplib.SMTP('localhost')
2073
        smtpServer.set_debuglevel(1)
11779 kshitij.so 2074
        sender = 'build@shop2020.in'
11791 kshitij.so 2075
        #recipients = ["kshitij.sood@saholic.com"]
11193 kshitij.so 2076
        msg = MIMEMultipart()
11228 kshitij.so 2077
        msg['Subject'] = "Flipkart Scraping" + ' '+runType+' - ' + str(datetime.now())
11193 kshitij.so 2078
        msg['From'] = sender
11791 kshitij.so 2079
        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 2080
        msg['To'] = ",".join(recipients)
2081
        fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
2082
        fileMsg.set_payload(file(filename).read())
2083
        email.encoders.encode_base64(fileMsg)
2084
        fileMsg.add_header('Content-Disposition','attachment;filename=flipkart.xls')
2085
        msg.attach(fileMsg)
2086
        try:
2087
            smtpServer.sendmail(sender, recipients, msg.as_string())
2088
            print "Successfully sent email"
2089
        except:
2090
            print "Error: unable to send email."
11560 kshitij.so 2091
 
11571 kshitij.so 2092
def populateScrapingResults(val):
2093
    try:
2094
        flipkartDetails = fetchDetails(val.fkSerialNumber,scraper)
2095
        val.flipkartDetails = flipkartDetails 
2096
    except Exception as e:
2097
        print "Unable to fetch details of",val.fkSerialNumber
2098
        print e
2099
        val.flipkartDetails = None
2100
        return
2101
 
2102
    try:
2103
        request_url = "https://api.flipkart.net/sellers/skus/%s/listings"%(str(val.skuAtFlipkart))
2104
        r = requests.get(request_url, auth=('m2z93iskuj81qiid', '0c7ab6a5-98c0-4cdc-8be3-72c591e0add4'))
2105
        print "Inventory info",r.json()
2106
        stock_count = int((r.json()['attributeValues'])['stock_count'])
2107
    except:
2108
        stock_count = 0
2109
 
2110
    val.ourFlipkartInventory = stock_count
11560 kshitij.so 2111
 
2112
def threadsToSpawn(runType,itemInfo,scraper,itemPopulated):
2113
    if runType == RunType.FAVOURITE:
11615 kshitij.so 2114
        count = 0
2115
        pool = ThreadPool(3)
2116
        startOffset = 0
11560 kshitij.so 2117
        endOffset = startOffset
11615 kshitij.so 2118
        while(count<3 and endOffset<len(itemInfo)):
11560 kshitij.so 2119
            endOffset = startOffset + 20
2120
            if (endOffset >= len(itemInfo)):
2121
                endOffset = len(itemInfo)
11615 kshitij.so 2122
            print "pool offset start end count"+str(startOffset)+" "+str(endOffset)+" "+str(count)
2123
            pool.map(populateScrapingResults,itemInfo[startOffset:endOffset])
2124
            #t = Process(target=decideCategory,args=(itemInfo[startOffset:endOffset], scraper))
2125
            #t = threading.Thread(target=partial(decideCategory, itemInfo[startOffset:endOffset], scraper))
11560 kshitij.so 2126
            #t = threading.Thread(target=partial(test, startOffset, endOffset))
11615 kshitij.so 2127
            #threads.append(t)
11560 kshitij.so 2128
            startOffset = startOffset + 20
11615 kshitij.so 2129
            count+=1
2130
        #[t.start() for t in threads]
2131
        #[t.join() for t in threads] 
2132
        #threads = []
2133
        pool.close()
2134
        pool.join()
11560 kshitij.so 2135
        return endOffset
2136
    else:
11561 kshitij.so 2137
        count = 0
11571 kshitij.so 2138
        pool = ThreadPool(5)
11581 kshitij.so 2139
        startOffset = 0
11560 kshitij.so 2140
        endOffset = startOffset
11571 kshitij.so 2141
        while(count<5 and endOffset<len(itemInfo)):
11581 kshitij.so 2142
            endOffset = startOffset + 20
11560 kshitij.so 2143
            if (endOffset >= len(itemInfo)):
2144
                endOffset = len(itemInfo)
11581 kshitij.so 2145
            print "pool offset start end count"+str(startOffset)+" "+str(endOffset)+" "+str(count)
2146
            time.sleep(10)
11571 kshitij.so 2147
            pool.map(populateScrapingResults,itemInfo[startOffset:endOffset])
11561 kshitij.so 2148
            #t = Process(target=decideCategory,args=(itemInfo[startOffset:endOffset], scraper))
11560 kshitij.so 2149
            #t = threading.Thread(target=partial(decideCategory, itemInfo[startOffset:endOffset], scraper))
2150
            #t = threading.Thread(target=partial(test, startOffset, endOffset))
11561 kshitij.so 2151
            #threads.append(t)
11581 kshitij.so 2152
            startOffset = startOffset + 20
11561 kshitij.so 2153
            count+=1
2154
        #[t.start() for t in threads]
2155
        #[t.join() for t in threads] 
2156
        #threads = []
11581 kshitij.so 2157
        print "terminating while"
11563 kshitij.so 2158
        pool.close()
2159
        pool.join()
11581 kshitij.so 2160
        print "joining threads"
2161
        time.sleep(5)
2162
        print "returning offset******"
11571 kshitij.so 2163
        time.sleep(5) 
11560 kshitij.so 2164
        return endOffset
2165
 
11623 kshitij.so 2166
def sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease):
2167
    if len(successfulAutoDecrease)==0 and len(successfulAutoIncrease)==0 :
2168
        return
2169
    xstr = lambda s: s or ""
2170
    catalog_client = CatalogClient().get_client()
2171
    inventory_client = InventoryClient().get_client()
2172
    message="""<html>
2173
            <body>
11625 kshitij.so 2174
            <h3 style="color:red;font-weight:bold;">This is test run.Prices are not being updated by system.</h3>
11623 kshitij.so 2175
            <h3>Auto Decrease Items</h3>
2176
            <table border="1" style="width:100%;">
2177
            <thead>
2178
            <tr><th>Item Id</th>
2179
            <th>Product Name</th>
2180
            <th>Old Price</th>
2181
            <th>New Price</th>
2182
            <th>Old Margin</th>
2183
            <th>New Margin</th>
11790 kshitij.so 2184
            <th>Commission %</th>
2185
            <th>Return Provision %</th>
11623 kshitij.so 2186
            <th>Flipkart Inventory</th>
2187
            <th>Sales History</th>
2188
            </tr></thead>
2189
            <tbody>"""
2190
    for item in successfulAutoDecrease:
2191
        it = Item.query.filter_by(id=item.item_id).one()
2192
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.FLIPKART)
2193
        fkItem = FlipkartItem.get_by(item_id=item.item_id)
2194
        warehouse = inventory_client.getWarehouse(fkItem.warehouseId)
2195
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, item.proposedSellingPrice)
2196
        newMargin = round(getNewOurTp(mpItem,item.proposedSellingPrice) - getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,item.proposedSellingPrice))  
2197
        message+="""<tr>
2198
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
2199
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
2200
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
2201
                <td style="text-align:center">"""+str(math.ceil(item.proposedSellingPrice))+"""</td>
2202
                <td style="text-align:center">"""+str(round(item.margin))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
2203
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/item.proposedSellingPrice)*100,1))+"%)"+"""</td>
11806 kshitij.so 2204
                <td style="text-align:center">"""+str(mpItem.commission)+" %"+"""</td>
11790 kshitij.so 2205
                <td style="text-align:center">"""+str(mpItem.returnProvision)+" %"+"""</td>
11806 kshitij.so 2206
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
11623 kshitij.so 2207
                <td style="text-align:center">"""+getOosString((itemSaleMap.get(item.item_id))[1])+"""</td>
2208
                </tr>"""
2209
    message+="""</tbody></table><h3>Auto Increase Items</h3><table border="1" style="width:100%;">
2210
            <thead>
2211
            <tr><th>Item Id</th>
2212
            <th>Product Name</th>
2213
            <th>Old Price</th>
2214
            <th>New Price</th>
2215
            <th>Old Margin</th>
2216
            <th>New Margin</th>
11790 kshitij.so 2217
            <th>Commission %</th>
2218
            <th>Return Provision %</th>
11623 kshitij.so 2219
            <th>Flipkart Inventory</th>
2220
            <th>Sales History</th>
2221
            </tr></thead>
2222
            <tbody>"""
2223
    for item in successfulAutoIncrease:
2224
        it = Item.query.filter_by(id=item.item_id).one()
2225
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.FLIPKART)
2226
        fkItem = FlipkartItem.get_by(item_id=item.item_id)
2227
        warehouse = inventory_client.getWarehouse(fkItem.warehouseId)
2228
        vatRate = catalog_client.getVatPercentageForItem(item.item_id, warehouse.stateId, math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
2229
        newMargin = round(getNewOurTp(mpItem,item.ourSellingPrice+max(10,.01*item.ourSellingPrice)) - getNewLowestPossibleTp(mpItem,item.ourNlc,vatRate,item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))  
2230
        message+="""<tr>
2231
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
2232
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
2233
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
2234
                <td style="text-align:center">"""+str(math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))+"""</td>
2235
                <td style="text-align:center">"""+str(round((item.margin),1))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
2236
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))*100,1))+"%)"+"""</td>
11806 kshitij.so 2237
                <td style="text-align:center">"""+str(mpItem.commission)+" %"+"""</td>
11790 kshitij.so 2238
                <td style="text-align:center">"""+str(mpItem.returnProvision)+" %"+"""</td>
11623 kshitij.so 2239
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
2240
                <td style="text-align:center">"""+getOosString((itemSaleMap.get(item.item_id))[1])+"""</td>
2241
                </tr>"""
2242
    message+="""</tbody></table></body></html>"""
2243
    print message
2244
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
2245
    mailServer.ehlo()
2246
    mailServer.starttls()
2247
    mailServer.ehlo()
2248
 
11791 kshitij.so 2249
    #recipients = ['kshitij.sood@saholic.com']
2250
    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']
11623 kshitij.so 2251
    msg = MIMEMultipart()
2252
    msg['Subject'] = "Flipkart Auto Pricing" + ' - ' + str(datetime.now())
2253
    msg['From'] = ""
2254
    msg['To'] = ",".join(recipients)
2255
    msg.preamble = "Flipkart Auto Pricing" + ' - ' + str(datetime.now())
2256
    html_msg = MIMEText(message, 'html')
2257
    msg.attach(html_msg)
2258
    try:
2259
        mailServer.login("build@shop2020.in", "cafe@nes")
2260
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
2261
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
2262
    except Exception as e:
2263
        print e
2264
        print "Unable to send pricing mail.Lets try with local SMTP."
2265
        smtpServer = smtplib.SMTP('localhost')
2266
        smtpServer.set_debuglevel(1)
11779 kshitij.so 2267
        sender = 'build@shop2020.in'
11623 kshitij.so 2268
        try:
2269
            smtpServer.sendmail(sender, recipients, msg.as_string())
2270
            print "Successfully sent email"
2271
        except:
2272
            print "Error: unable to send email."
2273
 
2274
def processLostBuyBoxItems(previousProcessingTimestamp,currentTimestamp):
2275
    previous_buy_box = session.query(MarketPlaceHistory.item_id).filter(MarketPlaceHistory.timestamp==previousProcessingTimestamp).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).filter(or_(MarketPlaceHistory.competitiveCategory==CompetitionCategory.BUY_BOX,MarketPlaceHistory.competitiveCategory==CompetitionCategory.PREF_BUT_NOT_CHEAP)).all()
2276
    cant_compete = session.query(MarketPlaceHistory.item_id).filter(MarketPlaceHistory.timestamp==currentTimestamp).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.CANT_COMPETE).all()
2277
    if previous_buy_box is None:
2278
        print "No item in buy box for last run"
2279
        return
2280
    lost_buy_box = list(set(list(zip(*previous_buy_box)[0]))&set(list(zip(*cant_compete)[0])))
2281
    if len(lost_buy_box)==0:
2282
        return
2283
    xstr = lambda s: s or ""
2284
    message="""<html>
2285
            <body>
2286
            <h3>Lost Buy Box</h3>
2287
            <table border="1" style="width:100%;">
2288
            <thead>
2289
            <tr><th>Item Id</th>
2290
            <th>Product Name</th>
2291
            <th>Current Price</th>
2292
            <th>Current Margin</th>
11844 kshitij.so 2293
            <th>Lowest Seller</th>
2294
            <th>Lowest Selling Price</th>
2295
            <th>Preffered Seller</th>
2296
            <th>Preffered Selling Price</th>
11623 kshitij.so 2297
            <th>NLC</th>
2298
            <th>Target NLC</th>
11790 kshitij.so 2299
            <th>Commission %</th>
2300
            <th>Return Provision %</th>
11623 kshitij.so 2301
            <th>Flipkart Inventory</th>
2302
            <th>Total Inventory</th>
2303
            <th>Sales History</th>
2304
            </tr></thead>
2305
            <tbody>"""
2306
    items = session.query(MarketPlaceHistory).filter(MarketPlaceHistory.timestamp==currentTimestamp).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.item_id.in_(lost_buy_box)).all()
2307
    for item in items:
2308
        it = Item.query.filter_by(id=item.item_id).one()
11790 kshitij.so 2309
        mpItem = MarketplaceItems.get_by(itemId=item.item_id,source=OrderSource.FLIPKART)
11623 kshitij.so 2310
        netInventory=''
2311
        if not inventoryMap.has_key(item.item_id):
2312
            netInventory='Info Not Available'
2313
        else:
2314
            netInventory = str(getNetAvailability(inventoryMap.get(item.item_id)))
2315
        message+="""<tr>
2316
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
2317
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
2318
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
2319
                <td style="text-align:center">"""+str(round(item.margin))+" ("+str(round((item.margin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
11844 kshitij.so 2320
                <td style="text-align:center">"""+str(item.lowestSellerName)+"""</td>
2321
                <td style="text-align:center">"""+str(item.lowestSellingPrice)+"""</td>
2322
                <td style="text-align:center">"""+str(item.prefferedSellerName)+"""</td>
2323
                <td style="text-align:center">"""+str(item.prefferedSellerSellingPrice)+"""</td>
11623 kshitij.so 2324
                <td style="text-align:center">"""+str(item.ourNlc)+"""</td>
2325
                <td style="text-align:center">"""+str(item.targetNlc)+"""</td>
11790 kshitij.so 2326
                <td style="text-align:center">"""+str(mpItem.commission)+"""</td>
2327
                <td style="text-align:center">"""+str(mpItem.returnProvision)+" %"+"""</td>
11623 kshitij.so 2328
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
2329
                <td style="text-align:center">"""+netInventory+"""</td>
2330
                <td style="text-align:center">"""+getOosString((itemSaleMap.get(item.item_id))[1])+"""</td>
2331
                </tr>"""
2332
    message+="""</tbody></table></body></html>"""
2333
    print message
2334
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
2335
    mailServer.ehlo()
2336
    mailServer.starttls()
2337
    mailServer.ehlo()
2338
 
11791 kshitij.so 2339
    #recipients = ['kshitij.sood@saholic.com']
2340
    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']
11623 kshitij.so 2341
    msg = MIMEMultipart()
2342
    msg['Subject'] = "Flipkart Lost Buy Box" + ' - ' + str(datetime.now())
2343
    msg['From'] = ""
2344
    msg['To'] = ",".join(recipients)
2345
    msg.preamble = "Flipkart Lost Buy Box" + ' - ' + str(datetime.now())
2346
    html_msg = MIMEText(message, 'html')
2347
    msg.attach(html_msg)
2348
    try:
2349
        mailServer.login("build@shop2020.in", "cafe@nes")
2350
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
2351
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
2352
    except Exception as e:
2353
        print e
2354
        print "Unable to send lost buy box mail.Lets try local SMTP"
2355
        smtpServer = smtplib.SMTP('localhost')
2356
        smtpServer.set_debuglevel(1)
11779 kshitij.so 2357
        sender = 'build@shop2020.in'
11623 kshitij.so 2358
        try:
2359
            smtpServer.sendmail(sender, recipients, msg.as_string())
2360
            print "Successfully sent email"
2361
        except:
2362
            print "Error: unable to send email."
2363
 
2364
def cheapButNotPrefAlert(timestamp):
11626 kshitij.so 2365
    cheap_but_not_pref = session.query(MarketPlaceHistory,Item).join((Item,MarketPlaceHistory.item_id==Item.id)).filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.CHEAP_BUT_NOT_PREF).all()
11758 kshitij.so 2366
    if len(cheap_but_not_pref)==0:
11623 kshitij.so 2367
        return
2368
    xstr = lambda s: s or ""
2369
    message="""<html>
2370
            <body>
2371
            <h3>Cheap But Not Preferred</h3>
2372
            <table border="1" style="width:100%;">
2373
            <thead>
2374
            <tr><th>Item Id</th>
2375
            <th>Product Name</th>
2376
            <th>Current Price</th>
11670 kshitij.so 2377
            <th>Our Rating</th>
2378
            <th>Our Shipping Time</th>
11623 kshitij.so 2379
            <th>Preffered Seller</th>
2380
            <th>Preffered Seller SP</th>
11670 kshitij.so 2381
            <th>Preffered Seller Rating</th>
2382
            <th>Preffered Seller Shipping Time</th>
2383
            <th>Price Variance %</th>
11792 kshitij.so 2384
            <th>Commission %</th>
2385
            <th>Return Provision %</th>
11623 kshitij.so 2386
            <th>Flipkart Inventory</th>
2387
            <th>Total Inventory</th>
2388
            <th>Sales History</th>
2389
            </tr></thead>
2390
            <tbody>"""
2391
    for item in cheap_but_not_pref:
2392
        mpHistory = item[0]
2393
        catItem = item[1]
2394
        netInventory=''
2395
        if not inventoryMap.has_key(mpHistory.item_id):
2396
            netInventory='Info Not Available'
2397
        else:
2398
            netInventory = str(getNetAvailability(inventoryMap.get(mpHistory.item_id)))
11670 kshitij.so 2399
        ourSt = mpHistory.ourShippingTime.split('-')
2400
        pfSt = mpHistory.prefferedSellerShippingTime.split('-')
11792 kshitij.so 2401
        mpItem = MarketplaceItems.get_by(itemId=mpHistory.item_id,source=OrderSource.FLIPKART)
11670 kshitij.so 2402
        if mpHistory.prefferedSellerName=='WS Retail' and mpHistory.ourRating > mpHistory.prefferedSellerRating and int(ourSt[0])<=int(pfSt[0]):
11623 kshitij.so 2403
            style="""background-color:red;\""""
2404
        else:
2405
            style="\""
11754 kshitij.so 2406
        message+="""<tr>
2407
            <td style="text-align:center;"""+str(style)+""">"""+str(mpHistory.item_id)+"""</td>
2408
            <td style="text-align:center;"""+str(style)+""">"""+xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color)+"""</td>
2409
            <td style="text-align:center;"""+str(style)+""">"""+str(mpHistory.ourSellingPrice)+"""</td>
2410
            <td style="text-align:center;"""+str(style)+""">"""+str(mpHistory.ourRating)+"""</td>
2411
            <td style="text-align:center;"""+str(style)+""">"""+str(mpHistory.ourShippingTime)+"""</td>
2412
            <td style="text-align:center;"""+str(style)+""">"""+str(mpHistory.prefferedSellerName)+"""</td>
2413
            <td style="text-align:center;"""+str(style)+""">"""+str(mpHistory.prefferedSellerSellingPrice)+"""</td>
2414
            <td style="text-align:center;"""+str(style)+""">"""+str(mpHistory.prefferedSellerRating)+"""</td>
2415
            <td style="text-align:center;"""+str(style)+""">"""+str(mpHistory.prefferedSellerShippingTime)+"""</td>
2416
            <td style="text-align:center;"""+str(style)+""">"""+str(round(((mpHistory.prefferedSellerSellingPrice-mpHistory.ourSellingPrice)/mpHistory.ourSellingPrice)*100))+"%"+"""</td>
11806 kshitij.so 2417
            <td style="text-align:center">"""+str(mpItem.commission)+" %"+"""</td>
11792 kshitij.so 2418
            <td style="text-align:center">"""+str(mpItem.returnProvision)+" %"+"""</td>
11754 kshitij.so 2419
            <td style="text-align:center;"""+str(style)+""">"""+str(mpHistory.ourInventory)+"""</td>
2420
            <td style="text-align:center;"""+str(style)+""">"""+netInventory+"""</td>
2421
            <td style="text-align:center;"""+str(style)+""">"""+getOosString((itemSaleMap.get(mpHistory.item_id))[1])+"""</td>
2422
            </tr>"""
11623 kshitij.so 2423
    message+="""</tbody></table></body></html>"""
2424
    print message
2425
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
2426
    mailServer.ehlo()
2427
    mailServer.starttls()
2428
    mailServer.ehlo()
2429
 
11791 kshitij.so 2430
    #recipients = ['kshitij.sood@saholic.com']
2431
    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']
11623 kshitij.so 2432
    msg = MIMEMultipart()
2433
    msg['Subject'] = "Flipkart Cheap But Not In BuyBox Items" + ' - ' + str(datetime.now())
2434
    msg['From'] = ""
2435
    msg['To'] = ",".join(recipients)
2436
    msg.preamble = "Flipkart Cheap But Not In BuyBox Items" + ' - ' + str(datetime.now())
2437
    html_msg = MIMEText(message, 'html')
2438
    msg.attach(html_msg)
2439
    try:
2440
        mailServer.login("build@shop2020.in", "cafe@nes")
2441
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
2442
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
2443
    except Exception as e:
2444
        print e
2445
        print "Unable to send Flipkart Cheap But Not In BuyBox Items mail.Lets try local SMTP"
2446
        smtpServer = smtplib.SMTP('localhost')
2447
        smtpServer.set_debuglevel(1)
11779 kshitij.so 2448
        sender = 'build@shop2020.in'
11623 kshitij.so 2449
        try:
2450
            smtpServer.sendmail(sender, recipients, msg.as_string())
2451
            print "Successfully sent email"
2452
        except:
2453
            print "Error: unable to send email."
11754 kshitij.so 2454
 
2455
def sendPricingMismatch(timestamp):
2456
    xstr = lambda s: s or ""
2457
    message="""<html>
2458
            <body>
2459
            <h3>Flipkart Pricing Mismatch</h3>
2460
            <table border="1" style="width:100%;">
2461
            <thead>
2462
            <tr><th>Item Id</th>
2463
            <th>Product Name</th>
2464
            <th>Our System Price</th>
2465
            <th>Flipkart Price</th>
2466
            <th>Flipkart Inventory</th>
2467
            <th>Total Inventory</th>
2468
            <th>Sales History</th>
2469
            </tr></thead>
2470
            <tbody>"""
2471
    flipkartPricing = {}
2472
    saholicPricing = {}
2473
    mpHistoryItems = session.query(MarketPlaceHistory,Item).join((Item,MarketPlaceHistory.item_id==Item.id)).filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).all()
2474
    for val in mpHistoryItems:
2475
        temp = []
2476
        temp.append(val[0].ourSellingPrice)
2477
        temp.append(xstr(val[1].brand)+" "+xstr(val[1].model_name)+" "+xstr(val[1].model_number)+" "+xstr(val[1].color))
11755 kshitij.so 2478
        temp.append(val[0].ourInventory)
11754 kshitij.so 2479
        flipkartPricing[val[0].item_id] = temp
2480
    mpHistoryItems[:] = []
2481
    mpItems = session.query(MarketplaceItems).filter(MarketplaceItems.source==OrderSource.FLIPKART).all()
2482
    for val in mpItems:
2483
        saholicPricing[val.itemId] = val.currentSp
2484
    mpItems[:] = []
2485
    mismatches = []
2486
    for k,v in flipkartPricing.iteritems():
2487
        flipkartSellingPrice = v[0]
2488
        ourSellingPrice = saholicPricing.get(k)
11771 kshitij.so 2489
        if flipkartSellingPrice is not None and not((ourSellingPrice - flipkartSellingPrice >= -3) and (ourSellingPrice - flipkartSellingPrice <=3)):
11754 kshitij.so 2490
            mismatches.append(k)
2491
    print "mismatches are ",mismatches
11755 kshitij.so 2492
    if len(mismatches)==0:
2493
        return
11754 kshitij.so 2494
    for item in mismatches:
2495
        netInventory=''
2496
        if not inventoryMap.has_key(item):
2497
            netInventory='Info Not Available'
2498
        else:
2499
            netInventory = str(getNetAvailability(inventoryMap.get(item)))
2500
        message+="""<tr>
11756 kshitij.so 2501
            <td style="text-align:center">"""+str(item)+"""</td>
2502
            <td style="text-align:center">"""+str((flipkartPricing.get(item))[1])+"""</td>
2503
            <td style="text-align:center">"""+str(saholicPricing.get(item))+"""</td>
2504
            <td style="text-align:center">"""+str((flipkartPricing.get(item))[0])+"""</td>
2505
            <td style="text-align:center">"""+str((flipkartPricing.get(item))[2])+"""</td>
2506
            <td style="text-align:center">"""+netInventory+"""</td>
2507
            <td style="text-align:center">"""+getOosString((itemSaleMap.get(item))[1])+"""</td>
11754 kshitij.so 2508
            </tr>"""
2509
    message+="""</tbody></table></body></html>"""
2510
    print message
2511
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
2512
    mailServer.ehlo()
2513
    mailServer.starttls()
2514
    mailServer.ehlo()
2515
 
11791 kshitij.so 2516
    #recipients = ['kshitij.sood@saholic.com']
2517
    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']
11754 kshitij.so 2518
    msg = MIMEMultipart()
2519
    msg['Subject'] = "Flipkart Price Mismatch" + ' - ' + str(datetime.now())
2520
    msg['From'] = ""
2521
    msg['To'] = ",".join(recipients)
2522
    msg.preamble = "Flipkart Price Mismatch" + ' - ' + str(datetime.now())
2523
    html_msg = MIMEText(message, 'html')
2524
    msg.attach(html_msg)
2525
    try:
2526
        mailServer.login("build@shop2020.in", "cafe@nes")
2527
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
2528
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
2529
    except Exception as e:
2530
        print e
2531
        print "Unable to send Flipkart Price Mismatch mail.Lets try local SMTP"
2532
        smtpServer = smtplib.SMTP('localhost')
2533
        smtpServer.set_debuglevel(1)
11779 kshitij.so 2534
        sender = 'build@shop2020.in'
11754 kshitij.so 2535
        try:
2536
            smtpServer.sendmail(sender, recipients, msg.as_string())
2537
            print "Successfully sent email"
2538
        except:
2539
            print "Error: unable to send email."
11775 kshitij.so 2540
 
2541
def sendAlertForNegativeMargins(timestamp):
2542
    xstr = lambda s: s or ""
2543
    negativeMargins = session.query(MarketPlaceHistory,Item).join((Item,MarketPlaceHistory.item_id==Item.id)).filter(MarketPlaceHistory.timestamp==timestamp).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).filter(MarketPlaceHistory.competitiveCategory==CompetitionCategory.NEGATIVE_MARGIN).all()
2544
    if len(negativeMargins) == 0:
2545
        return
2546
    message="""<html>
2547
            <body>
2548
            <h3 style="color:red;font-weight:bold;">Flipkart Negative Margins</h3>
2549
            <table border="1" style="width:100%;">
2550
            <thead>
2551
            <tr><th>Item Id</th>
2552
            <th>Product Name</th>
2553
            <th>SP</th>
2554
            <th>TP</th>
2555
            <th>Lowest Possible SP</th>
2556
            <th>Lowest Possible TP</th>
2557
            <th>Margin</th>
2558
            <th>Margin %</th>
11790 kshitij.so 2559
            <th>Commission %</th>
2560
            <th>Return Provision %</th>
11775 kshitij.so 2561
            <th>Flipkart Inventory</th>
2562
            <th>Total Inventory</th>
2563
            <th>Sales History</th>
2564
            </tr></thead>
2565
            <tbody>"""
2566
    for item in negativeMargins:
2567
        mpHistory = item[0]
2568
        catItem = item[1]
2569
        netInventory=''
11776 kshitij.so 2570
        if not inventoryMap.has_key(mpHistory.item_id):
11775 kshitij.so 2571
            netInventory='Info Not Available'
2572
        else:
11776 kshitij.so 2573
            netInventory = str(getNetAvailability(inventoryMap.get(mpHistory.item_id)))
11790 kshitij.so 2574
        mpItem = MarketplaceItems.get_by(itemId=mpHistory.item_id,source=OrderSource.FLIPKART)
11775 kshitij.so 2575
        message+="""<tr>
2576
            <td style="text-align:center">"""+str(mpHistory.item_id)+"""</td>
2577
            <td style="text-align:center">"""+xstr(catItem.brand)+" "+xstr(catItem.model_name)+" "+xstr(catItem.model_number)+" "+xstr(catItem.color)+"""</td>
2578
            <td style="text-align:center">"""+str(mpHistory.ourSellingPrice)+"""</td>
2579
            <td style="text-align:center">"""+str(mpHistory.ourTp)+"""</td>
2580
            <td style="text-align:center">"""+str(mpHistory.lowestPossibleSp)+"""</td>
2581
            <td style="text-align:center">"""+str(mpHistory.lowestPossibleTp)+"""</td>
2582
            <td style="text-align:center">"""+str(mpHistory.margin)+"""</td>
11952 kshitij.so 2583
            <td style="text-align:center">"""+str(round((mpHistory.margin/mpHistory.ourSellingPrice)*100,1))+" %"+"""</td>
11790 kshitij.so 2584
            <td style="text-align:center">"""+str(mpItem.commission)+"""</td>
2585
            <td style="text-align:center">"""+str(mpItem.returnProvision)+" %"+"""</td>
11775 kshitij.so 2586
            <td style="text-align:center">"""+str(mpHistory.ourInventory)+"""</td>
2587
            <td style="text-align:center">"""+netInventory+"""</td>
11776 kshitij.so 2588
            <td style="text-align:center">"""+getOosString((itemSaleMap.get(mpHistory.item_id))[1])+"""</td>
11775 kshitij.so 2589
            </tr>"""
2590
    message+="""</tbody></table></body></html>"""
2591
    print message
2592
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
2593
    mailServer.ehlo()
2594
    mailServer.starttls()
2595
    mailServer.ehlo()
2596
 
11791 kshitij.so 2597
    #recipients = ['kshitij.sood@saholic.com']
2598
    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']
11775 kshitij.so 2599
    msg = MIMEMultipart()
2600
    msg['Subject'] = "Flipkart Negative Margin" + ' - ' + str(datetime.now())
2601
    msg['From'] = ""
2602
    msg['To'] = ",".join(recipients)
2603
    msg.preamble = "Flipkart Negative Margin" + ' - ' + str(datetime.now())
2604
    html_msg = MIMEText(message, 'html')
2605
    msg.attach(html_msg)
2606
    try:
2607
        mailServer.login("build@shop2020.in", "cafe@nes")
2608
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
2609
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
2610
    except Exception as e:
2611
        print e
2612
        print "Unable to send Flipkart Negative margin mail.Lets try local SMTP"
2613
        smtpServer = smtplib.SMTP('localhost')
2614
        smtpServer.set_debuglevel(1)
11779 kshitij.so 2615
        sender = 'build@shop2020.in'
11775 kshitij.so 2616
        try:
2617
            smtpServer.sendmail(sender, recipients, msg.as_string())
2618
            print "Successfully sent email"
2619
        except:
2620
            print "Error: unable to send email."
11560 kshitij.so 2621
 
11623 kshitij.so 2622
 
11775 kshitij.so 2623
 
2624
 
11193 kshitij.so 2625
def main():
2626
    parser = optparse.OptionParser()
2627
    parser.add_option("-t", "--type", dest="runType",
2628
                   default="FULL", type="string",
2629
                   help="Run type FULL or FAVOURITE")
2630
    (options, args) = parser.parse_args()
2631
    if options.runType not in ('FULL','FAVOURITE'):
2632
        print "Run type argument illegal."
2633
        sys.exit(1)
2634
    timestamp = datetime.now()
11581 kshitij.so 2635
    previousProcessingTimestamp = session.query(func.max(MarketPlaceHistory.timestamp)).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).one()
11193 kshitij.so 2636
    itemInfo= populateStuff(options.runType,timestamp)
11560 kshitij.so 2637
    itemsPopulated = 0
11615 kshitij.so 2638
    while (len(itemInfo)>0):
11560 kshitij.so 2639
        itemsPopulated = threadsToSpawn(options.runType,itemInfo,scraper,itemsPopulated)
11581 kshitij.so 2640
        cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap = decideCategory(itemInfo[0:itemsPopulated])
2641
        itemInfo[0:itemsPopulated] = []
2642
        commitExceptionList(exceptionItems,timestamp)
2643
        commitCantCompete(cantCompete,timestamp)
2644
        commitBuyBox(buyBoxItems,timestamp)
2645
        commitCompetitive(competitive,timestamp)
2646
        commitCompetitiveNoInventory(competitiveNoInventory,timestamp)
2647
        commitNegativeMargin(negativeMargin,timestamp)
2648
        commitCheapButNotPref(cheapButNotPref,timestamp)
2649
        commitPrefButNotCheap(prefButNotCheap, timestamp)
2650
        cantCompete[:], buyBoxItems[:], competitive[:], competitiveNoInventory[:], exceptionItems[:], negativeMargin[:], cheapButNotPref[:], prefButNotCheap[:] =[],[],[],[],[],[],[],[]
2651
 
11615 kshitij.so 2652
    successfulAutoDecrease = fetchItemsForAutoDecrease(timestamp)
2653
    successfulAutoIncrease = fetchItemsForAutoIncrease(timestamp)
2654
    if options.runType=='FULL':
2655
        previousAutoFav, nowAutoFav = markAutoFavourite()
11621 kshitij.so 2656
    if options.runType =='FULL':
2657
        write_report(previousAutoFav,nowAutoFav,timestamp,options.runType)
2658
    else:
2659
        write_report(None,None,timestamp,options.runType)
11623 kshitij.so 2660
    sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease)
11625 kshitij.so 2661
    if previousProcessingTimestamp[0] is not None:
2662
        processLostBuyBoxItems(previousProcessingTimestamp[0],timestamp)
11623 kshitij.so 2663
    if options.runType=='FULL':
2664
        cheapButNotPrefAlert(timestamp)
11754 kshitij.so 2665
        sendPricingMismatch(timestamp)
11775 kshitij.so 2666
        sendAlertForNegativeMargins(timestamp)
11193 kshitij.so 2667
 
2668
if __name__ == '__main__':
2669
    main()