Subversion Repositories SmartDukaan

Rev

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