Subversion Repositories SmartDukaan

Rev

Rev 26888 | Rev 28197 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 26888 Rev 27375
Line 1... Line 1...
1
from elixir import *
1
from elixir import *
2
from shop2020.clients.InventoryClient import InventoryClient
-
 
3
from shop2020.model.v1.catalog.impl import DataService
2
from shop2020.model.v1.catalog.impl import DataService
4
from shop2020.model.v1.catalog.impl.DataService import Item, Tag_Listing, \
3
from shop2020.model.v1.catalog.impl.DataService import Item, Tag_Listing, \
5
    Tag_Ranking, PrivateDeals
4
    Tag_Ranking, PrivateDeals
6
from shop2020.thriftpy.model.v1.catalog.ttypes import status
5
from shop2020.thriftpy.model.v1.catalog.ttypes import status
7
from sqlalchemy.sql.expression import or_, desc
6
from sqlalchemy.sql.expression import or_, desc
Line 11... Line 10...
11
import os
10
import os
12
import pymongo
11
import pymongo
13
import pysolr
12
import pysolr
14
import shutil
13
import shutil
15
import traceback
14
import traceback
-
 
15
import urllib2
16
from dtr.utils.utils import to_java_date
16
from dtr.utils.utils import to_java_date
-
 
17
import urllib2
-
 
18
import StringIO
17
#import pymongo
19
# import pymongo
18
#import pysolr
20
# import pysolr
19
 
21
 
20
CATEGORY_MASTER = [10006, 10010, 14202, 14203]
22
CATEGORY_MASTER = [10006, 10010, 14202, 14203]
21
parser = optparse.OptionParser()
23
parser = optparse.OptionParser()
22
parser.add_option("-d", "--d", dest="dbHost",
24
parser.add_option("-d", "--d", dest="dbHost",
23
                      default="127.0.0.1",
25
                      default="127.0.0.1",
Line 32... Line 34...
32
                      type="string", help="Complete solr path",
34
                      type="string", help="Complete solr path",
33
                      metavar="HOST")
35
                      metavar="HOST")
34
 
36
 
35
(options, args) = parser.parse_args()
37
(options, args) = parser.parse_args()
36
 
38
 
37
con=None
39
con = None
38
 
40
 
39
DataService.initialize(db_hostname=options.dbHost)
41
DataService.initialize(db_hostname=options.dbHost)
40
solr = pysolr.Solr(options.solrPath, always_commit=True, timeout=10)
42
solr = pysolr.Solr(options.solrPath, always_commit=True, timeout=10)
41
 
43
 
-
 
44
 
42
def get_mongo_connection(host='localhost', port=27017):
45
def get_mongo_connection(host='localhost', port=27017):
43
    global con
46
    global con
44
    if con is None:
47
    if con is None:
45
        print "Establishing connection %s host and port %d" %(host,port)
48
        print "Establishing connection %s host and port %d" % (host, port)
46
        try:
49
        try:
47
            con = pymongo.MongoClient(host, port)
50
            con = pymongo.MongoClient(host, port)
48
        except Exception, e:
51
        except Exception, e:
49
            print e
52
            print e
50
            return None
53
            return None
51
    return con
54
    return con
52
 
55
 
-
 
56
 
53
class __SkuInfo:
57
class __SkuInfo:
54
    
58
    
55
    def __init__(self, id, ids, brand, model_name, category_id, subCategoryId,thumbnail, title, brand_synonyms, model_name_synonyms, source_product_names, \
59
    def __init__(self, id, ids, brand, model_name, category_id, subCategoryId, thumbnail, title, brand_synonyms, model_name_synonyms, source_product_names, \
56
                 category, subCategory):
60
                 category, subCategory):
57
        #Skubundle id
61
        # Skubundle id
58
        self.id = id
62
        self.id = id
59
        #_id of skus
63
        # _id of skus
60
        self.ids = ids
64
        self.ids = ids
61
        self.brand = brand
65
        self.brand = brand
62
        self.model_name = model_name
66
        self.model_name = model_name
63
        self.category_id = category_id
67
        self.category_id = category_id
64
        self.subCategoryId = subCategoryId
68
        self.subCategoryId = subCategoryId
65
        self.thumbnail = thumbnail 
69
        self.thumbnail = thumbnail 
66
        self.title= title
70
        self.title = title
67
        self.brand_synonyms = brand_synonyms
71
        self.brand_synonyms = brand_synonyms
68
        self.model_name_synonyms = model_name_synonyms
72
        self.model_name_synonyms = model_name_synonyms
69
        self.source_product_names = source_product_names
73
        self.source_product_names = source_product_names
70
        self.category = category
74
        self.category = category
71
        self.subCategory = subCategory
75
        self.subCategory = subCategory
72
        
76
        
73
    def toJSON(self):
77
    def toJSON(self):
74
        return json.dumps(self, default=lambda o: o.__dict__, 
78
        return json.dumps(self, default=lambda o: o.__dict__,
75
            sort_keys=True, indent=4)
79
            sort_keys=True, indent=4)
-
 
80
 
76
        
81
        
77
class __Catalog:
82
class __Catalog:
78
    
83
    
79
    def __init__(self, id, rank, title, items):
84
    def __init__(self, id, rank, title, items):
80
        #Skubundle id
85
        # Skubundle id
81
        self.id = id
86
        self.id = id
82
        self.rank = rank
87
        self.rank = rank
83
        self.title = title
88
        self.title = title
84
        self._childDocuments_ = items
89
        self._childDocuments_ = items
-
 
90
 
85
    def toJSON(self):
91
    def toJSON(self):
86
        return json.dumps(self, default=lambda o: o.__dict__)
92
        return json.dumps(self, default=lambda o: o.__dict__)
-
 
93
 
87
        
94
        
88
class __Item:
95
class __Item:
-
 
96
 
89
    def __init__(self, id, color, tags):
97
    def __init__(self, id, color, tags):
90
        self.id = id
98
        self.id = id
91
        self.color = color
99
        self.color = color
92
        self._childDocuments_ = tags
100
        self._childDocuments_ = tags
-
 
101
 
93
        def toJSON(self):
102
        def toJSON(self):
94
            return json.dumps(self, default=lambda o: o.__dict__)
103
            return json.dumps(self, default=lambda o: o.__dict__)
-
 
104
 
-
 
105
 
95
class __Tag:
106
class __Tag:
-
 
107
 
96
    def __init__(self, id, sellingPrice, mop):
108
    def __init__(self, id, sellingPrice, mop):
97
        self.id = id
109
        self.id = id
98
        self.sellingPrice = sellingPrice
110
        self.sellingPrice = sellingPrice
99
        self.mop = mop
111
        self.mop = mop
100
        
112
        
101
        
-
 
102
#solr = pysolr.Solr(options.solrPath, timeout=10)
113
# solr = pysolr.Solr(options.solrPath, timeout=10)
103
 
114
 
104
 
115
 
105
def todict(obj, classkey=None):
116
def todict(obj, classkey=None):
106
    if isinstance(obj, dict):
117
    if isinstance(obj, dict):
107
        data = {}
118
        data = {}
Line 119... Line 130...
119
        if classkey is not None and hasattr(obj, "__class__"):
130
        if classkey is not None and hasattr(obj, "__class__"):
120
            data[classkey] = obj.__class__.__name__
131
            data[classkey] = obj.__class__.__name__
121
        return data
132
        return data
122
    else:
133
    else:
123
        return obj
134
        return obj
-
 
135
 
-
 
136
    
-
 
137
def ungzipResponse(r):
-
 
138
    headers = r.info()
-
 
139
    if headers.get('Content-Encoding') == 'gzip':
-
 
140
        url_f = StringIO.StringIO(r.read())
-
 
141
        gz = gzip.GzipFile(fileobj=url_f)
-
 
142
        html = gz.read()
-
 
143
        gz.close()
-
 
144
        return html
-
 
145
    return r.read()
-
 
146
 
-
 
147
 
-
 
148
def getAvailabilityJSON():
-
 
149
    url = "http://50.116.10.120/reports/run.php?execute_mode=EXECUTE&xmlin=warehousecisnew.xml&project=FOCOR&project_password=focor&target_format=JSON"
-
 
150
    req = urllib2.Request(url, headers={})
-
 
151
    response = urllib2.urlopen(req)
-
 
152
    response_data = ungzipResponse(response)
-
 
153
    response.close()
-
 
154
    return json.loads(response_data)['data']
-
 
155
 
-
 
156
 
-
 
157
def getPendingPOJSON():
-
 
158
    url = "http://50.116.10.120/reports/run.php?execute_mode=EXECUTE&xmlin=UnfulfilledPOItemsNew.xml&project=FOCOR&project_password=focor&target_format=JSON"
-
 
159
    req = urllib2.Request(url, headers={})
-
 
160
    response = urllib2.urlopen(req)
-
 
161
    response_data = ungzipResponse(response)
-
 
162
    response.close()
-
 
163
    return json.loads(response_data)['data']
-
 
164
 
-
 
165
 
-
 
166
def getItemMap():
-
 
167
    rawAvailabilityList = getAvailabilityJSON()
-
 
168
    rawPendingPoList = getPendingPOJSON()
-
 
169
    availabilityItemMap = {}
-
 
170
    # {"Warehouseid":"8468","Warehousefrom":"7573","Itemid":"29591","Availability":"8","Reserved":"0","Netavailability":"8"}
-
 
171
    for rawAvailability in rawAvailabilityList:
-
 
172
        if not availabilityItemMap.has_key(rawAvailability['Itemid']):
-
 
173
            availabilityItemMap[rawAvailability['Itemid']] = {}
-
 
174
        if not availabilityItemMap[rawAvailability['Itemid']].has_key(rawAvailability['Warehouseid']):
-
 
175
            availabilityItemMap[rawAvailability['Itemid']][rawAvailability['Warehouseid']] = {"netAvailability":0, "netPo":0}
-
 
176
        
-
 
177
        availabilityItemMap[rawAvailability['Itemid']][rawAvailability['Warehouseid']]['netAvailability'] += int(rawAvailability['Netavailability'])
124
    
178
    
-
 
179
    for rawPendingPo in rawPendingPoList:
-
 
180
        if not availabilityItemMap.has_key(rawPendingPo['Itemid']):
-
 
181
            availabilityItemMap[rawPendingPo['Itemid']] = {}
-
 
182
        if not availabilityItemMap[rawPendingPo['Itemid']].has_key(rawPendingPo['Warehouseid']):
-
 
183
            availabilityItemMap[rawPendingPo['Itemid']][rawPendingPo['Warehouseid']] = {"netAvailability":0, "netPo":0}
-
 
184
        availabilityItemMap[rawPendingPo['Itemid']][rawPendingPo['Warehouseid']]['netPo'] += int(rawPendingPo['Unfulfilled'])
-
 
185
        
-
 
186
    return availabilityItemMap
-
 
187
 
125
 
188
 
126
def populateTagItems():
189
def populateTagItems():
-
 
190
    availabilityItemMap = getItemMap()
127
    tagRankingList = session.query(Tag_Ranking).order_by(desc(Tag_Ranking.rankPoints)).all()
191
    tagRankingList = session.query(Tag_Ranking).order_by(desc(Tag_Ranking.rankPoints)).all()
128
    rankingList = []
192
    rankingList = []
129
    featureMap = {}
193
    featureMap = {}
130
    for tagRanking in tagRankingList:
194
    for tagRanking in tagRankingList:
131
        rankingList.append(tagRanking.catalogItemId)
195
        rankingList.append(tagRanking.catalogItemId)
132
        featureMap[tagRanking.catalogItemId]=tagRanking.feature
196
        featureMap[tagRanking.catalogItemId] = tagRanking.feature
133
    catalogMap = {}
197
    catalogMap = {}
134
    #stmt = session.query(PrivateDeals).filter_by(isActive=1).filter(now().between(PrivateDeals.startDate, PrivateDeals.endDate)).subquery()
198
    # stmt = session.query(PrivateDeals).filter_by(isActive=1).filter(now().between(PrivateDeals.startDate, PrivateDeals.endDate)).subquery()
135
    #query = session.query(Item, privateDealAlias.dealPrice).outerjoin((privateDealAlias, Item.id==privateDealAlias.item_id)).filter(Item.status != status.PHASED_OUT)
199
    # query = session.query(Item, privateDealAlias.dealPrice).outerjoin((privateDealAlias, Item.id==privateDealAlias.item_id)).filter(Item.status != status.PHASED_OUT)
136
    tuples = session.query(Tag_Listing, Item).join((Item, Item.id==Tag_Listing.item_id)).filter(or_(Item.status==status.ACTIVE, Item.status==status.PAUSED_BY_RISK, Item.status==status.PARTIALLY_ACTIVE))
200
    tuples = session.query(Tag_Listing, Item).join((Item, Item.id == Tag_Listing.item_id)).filter(or_(Item.status == status.ACTIVE, Item.status == status.PAUSED_BY_RISK, Item.status == status.PARTIALLY_ACTIVE))
137
    projection={'defaultImageUrl':1}
201
    projection = {'defaultImageUrl':1}
138
    for tag, item in tuples:
202
    for tag, item in tuples:
139
        if item.brand == "Live Demo":
203
        if item.brand == "Live Demo":
140
            continue
204
            continue
141
        if not catalogMap.has_key(item.catalog_item_id):
205
        if not catalogMap.has_key(item.catalog_item_id):
142
            catalogObj = {}
206
            catalogObj = {}
143
            catalogObj['feature'] = ""
207
            catalogObj['feature'] = ""
144
            catalogObj['title'] = " ".join(filter(None, [item.brand, item.model_name,  item.model_number]))
208
            catalogObj['title'] = " ".join(filter(None, [item.brand, item.model_name, item.model_number]))
145
            catalogObj['brand'] = (item.brand)
209
            catalogObj['brand'] = (item.brand)
146
            if item.brand == 'Huawei' or item.brand == 'Honor':
210
            if item.brand == 'Huawei' or item.brand == 'Honor':
147
                catalogObj['brand'] = ('Huawei', 'Honor')
211
                catalogObj['brand'] = ('Huawei', 'Honor')
148
            if item.brand == 'Mi' or item.brand == 'Xiaomi' or item.brand == 'Redmi':
212
            if item.brand == 'Mi' or item.brand == 'Xiaomi' or item.brand == 'Redmi':
149
                catalogObj['brand'] = ('Mi', 'Xiaomi', 'Redmi')
213
                catalogObj['brand'] = ('Mi', 'Xiaomi', 'Redmi')
150
            catalogObj['identifier'] = item.catalog_item_id
214
            catalogObj['identifier'] = item.catalog_item_id
151
            catalogObj['items'] = {}
215
            catalogObj['items'] = {}
152
            filterMap = {"_id":item.catalog_item_id}
216
            filterMap = {"_id":item.catalog_item_id}
153
            #Dont include it catalog not available
217
            # Dont include it catalog not available
154
            try:
218
            try:
155
                catalogObj['imageUrl'] = get_mongo_connection(options.mongoHost).CONTENT.siteContent.find_one(filterMap, projection)['defaultImageUrl']
219
                catalogObj['imageUrl'] = get_mongo_connection(options.mongoHost).CONTENT.siteContent.find_one(filterMap, projection)['defaultImageUrl']
156
                print catalogObj['imageUrl']
220
                print catalogObj['imageUrl']
157
            except:
221
            except:
158
                try:
222
                try:
159
                    catalogObj['imageUrl'] = 'https://images.smartdukaan.com/uploads/campaigns/' + str(item.catalog_item_id )+ '.jpg'
223
                    catalogObj['imageUrl'] = 'https://images.smartdukaan.com/uploads/campaigns/' + str(item.catalog_item_id) + '.jpg'
160
                except:
224
                except:
161
                    traceback.print_exc()
225
                    traceback.print_exc()
162
            try: 
226
            try: 
163
                catalogObj['rank'] = rankingList.index(item.catalog_item_id)
227
                catalogObj['rank'] = rankingList.index(item.catalog_item_id)
164
            except:
228
            except:
165
                #A very big number
229
                # A very big number
166
                traceback.print_exc()
230
                traceback.print_exc()
167
                catalogObj['rank'] = 50000000
231
                catalogObj['rank'] = 50000000
168
            if featureMap.has_key(item.catalog_item_id) and featureMap.get(item.catalog_item_id) is not None:
232
            if featureMap.has_key(item.catalog_item_id) and featureMap.get(item.catalog_item_id) is not None:
169
                    catalogObj['feature'] = featureMap.get(item.catalog_item_id)
233
                    catalogObj['feature'] = featureMap.get(item.catalog_item_id)
170
            #Mobile and tablets are showcased in same category
234
            # Mobile and tablets are showcased in same category
171
            catalogObj['categoryId'] = item.category if item.category in CATEGORY_MASTER else 6
235
            catalogObj['categoryId'] = item.category if item.category in CATEGORY_MASTER else 6
172
            #Temporay change need to be removed  
236
            # Temporay change need to be removed  
173
            if item.category==10006:
237
            if item.category == 10006:
174
                catalogObj['categoryId'] = 3
238
                catalogObj['categoryId'] = 3
175
            catalogObj['subCategoryId'] = item.category
239
            catalogObj['subCategoryId'] = item.category
176
            catalogObj['create_timestamp'] = to_java_date(tag.create_timestamp)
240
            catalogObj['create_timestamp'] = to_java_date(tag.create_timestamp)
177
            catalogMap[item.catalog_item_id] = catalogObj
241
            catalogMap[item.catalog_item_id] = catalogObj
-
 
242
            catalogObj['avColor'] = {}
178
 
243
 
179
        catalogObj = catalogMap.get(item.catalog_item_id)
244
        catalogObj = catalogMap.get(item.catalog_item_id)
-
 
245
        if availabilityItemMap.has_key(str(item.id)):
-
 
246
            for warehouseId, avMap in availabilityItemMap[str(item.id)].iteritems():
-
 
247
                print warehouseId, avMap, item.color, item.brand, item.model_name, item.model_number, item.catalog_item_id
-
 
248
                if not catalogObj['avColor'].has_key(int(warehouseId)):
-
 
249
                    catalogObj['avColor'][int(warehouseId)] = 0
-
 
250
                
-
 
251
                color = catalogObj['avColor'][int(warehouseId)]
-
 
252
                if avMap['netAvailability'] > 0:
-
 
253
                    color = 2
-
 
254
                elif avMap['netAvailability'] + avMap['netPo']:
-
 
255
                    color = max(color, 1)
-
 
256
                else:
-
 
257
                    color = max(color, 0)
-
 
258
                catalogObj['avColor'][int(warehouseId)] = color
180
 
259
 
181
        if not catalogObj['items'].has_key(item.id):
260
        if not catalogObj['items'].has_key(item.id):
182
            catalogObj['items'][item.id] = {'color': item.color.replace("f_", ""), 'tagPricing':[]}
261
            catalogObj['items'][item.id] = {'color': item.color.replace("f_", ""), 'tagPricing':[]}
183
            itemMap = catalogObj['items'].get(item.id)
262
            itemMap = catalogObj['items'].get(item.id)
184
            itemMap['tagPricing'].append(tag)
263
            itemMap['tagPricing'].append(tag)
185
        
-
 
186
    
264
    
187
    catalogObjs = []
265
    catalogObjs = []
188
    for catalogId, catalogMap in catalogMap.iteritems():
266
    for catalogId, catalogMap in catalogMap.iteritems():
-
 
267
        print "catalogMap", catalogMap
189
        itemsMap = catalogMap['items']
268
        itemsMap = catalogMap['items']
190
        itemObjs = []
269
        itemObjs = []
191
        for itemId, itemMap in itemsMap.iteritems():
270
        for itemId, itemMap in itemsMap.iteritems():
192
            tags = itemMap['tagPricing']
271
            tags = itemMap['tagPricing']
193
            for tag in tags:
272
            for tag in tags:
194
                itemObj = {'id':('itemtag-%s-%s'%(itemId, tag.tag_id)), 'color_s':itemMap['color'],  'itemId_i': itemId, 'tagId_i':tag.tag_id, 
273
                itemObj = {'id':('itemtag-%s-%s' % (itemId, tag.tag_id)), 'color_s':itemMap['color'], 'itemId_i': itemId, 'tagId_i':tag.tag_id,
195
                           'mrp_f':tag.mrp, 'mop_f': tag.mop, 'sellingPrice_f': tag.selling_price, 'active_b' : tag.active, 'hot_deal_b': tag.hot_deals}
274
                           'mrp_f':tag.mrp, 'mop_f': tag.mop, 'sellingPrice_f': tag.selling_price, 'active_b' : tag.active, 'hot_deal_b': tag.hot_deals}
196
            itemObjs.append(itemObj)
275
            itemObjs.append(itemObj)
197
        catalogObj = {'id':'catalog' + str(catalogId), 'rank_i':catalogMap['rank'], 'title_s': catalogMap['title'],
276
        catalogObj = {'id':'catalog' + str(catalogId), 'rank_i':catalogMap['rank'], 'title_s': catalogMap['title'],
198
                      '_childDocuments_':itemObjs,
277
                      '_childDocuments_':itemObjs,
199
                      'child_b' : len(itemObjs) > 0, 
278
                      'child_b' : len(itemObjs) > 0,
200
                      'catalogId_i':catalogId, 
279
                      'catalogId_i':catalogId,
201
                      'imageUrl_s': catalogMap['imageUrl'].replace("saholic", "smartdukaan"), 
280
                      'imageUrl_s': catalogMap['imageUrl'].replace("saholic", "smartdukaan"),
202
                      'feature_s':catalogMap['feature'],
281
                      'feature_s':catalogMap['feature'],
203
                      'brand_ss': catalogMap['brand'], 'create_s':catalogMap['create_timestamp'], 
282
                      'brand_ss': catalogMap['brand'], 'create_s':catalogMap['create_timestamp'],
204
                      'categoryId_i':catalogMap['categoryId'], 
283
                      'categoryId_i':catalogMap['categoryId'],
-
 
284
                      'w7573_i':0,
-
 
285
                      'w7678_i':0,
-
 
286
                      'w7720_i':0,
205
                      'subCategoryId_i':catalogMap['subCategoryId']}
287
                      'w8468_i':0,
-
 
288
                      'w8889_i':0
206
        print catalogObj
289
                      }
-
 
290
        for whId, color in catalogMap['avColor'].iteritems():
-
 
291
            print catalogId, whId, color, catalogMap['title']
-
 
292
            catalogObj['w%d_i'%(whId)] = color
207
        catalogObjs.append(catalogObj)
293
        catalogObjs.append(catalogObj)
208
    solr.delete(q='*:*')
294
    solr.delete(q='*:*')
209
    solr.add(catalogObjs)
295
    solr.add(catalogObjs)
210
 
296
 
-
 
297
 
211
def pushData():
298
def pushData():
212
    populateTagItems()
299
    populateTagItems()
-
 
300
 
213
    
301
    
214
if __name__=='__main__':
302
if __name__ == '__main__':
215
    pushData()
303
    pushData()