Subversion Repositories SmartDukaan

Rev

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