Subversion Repositories SmartDukaan

Rev

Rev 12195 | Rev 12201 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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