Subversion Repositories SmartDukaan

Rev

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