Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
22307 amit.gupta 1
from elixir import *
2
from shop2020.clients.InventoryClient import InventoryClient
3
from shop2020.model.v1.catalog.impl import DataService
4
from shop2020.model.v1.catalog.impl.DataService import Item, Tag_Listing, \
5
    Tag_Ranking, PrivateDeals
6
from shop2020.thriftpy.model.v1.catalog.ttypes import status
7
from sqlalchemy.sql.expression import or_, desc
8
from sqlalchemy.sql.functions import now
9
import json
10
import optparse
11
import os
12
import pymongo
13
import pysolr
14
import shutil
15
import traceback
24028 amit.gupta 16
from dtr.utils.utils import to_java_date
22307 amit.gupta 17
#import pymongo
18
#import pysolr
19
 
20
 
21
parser = optparse.OptionParser()
22308 amit.gupta 22
parser.add_option("-d", "--d", dest="dbHost",
23
                      default="127.0.0.1",
22307 amit.gupta 24
                      type="string", help="The HOST where the mysql server is running",
22308 amit.gupta 25
                      metavar="DBHOST")
22307 amit.gupta 26
parser.add_option("-s", "--s", dest="solrPath",
24028 amit.gupta 27
                      default="http://localhost:8984/solr/                1",
22307 amit.gupta 28
                      type="string", help="Complete solr path",
22308 amit.gupta 29
                      metavar="SOLRHOST")
30
parser.add_option("-m", "--m", dest="mongoHost",
22311 amit.gupta 31
                      default="localhost",
22308 amit.gupta 32
                      type="string", help="Complete solr path",
22307 amit.gupta 33
                      metavar="HOST")
34
 
35
(options, args) = parser.parse_args()
36
 
22312 amit.gupta 37
con=None
22307 amit.gupta 38
 
22310 amit.gupta 39
DataService.initialize(db_hostname=options.dbHost)
22307 amit.gupta 40
solr = pysolr.Solr(options.solrPath, timeout=10)
41
 
22308 amit.gupta 42
def get_mongo_connection(host='localhost', port=27017):
43
    global con
44
    if con is None:
45
        print "Establishing connection %s host and port %d" %(host,port)
46
        try:
47
            con = pymongo.MongoClient(host, port)
48
        except Exception, e:
49
            print e
50
            return None
51
    return con
22307 amit.gupta 52
 
53
class __SkuInfo:
54
 
55
    def __init__(self, id, ids, brand, model_name, category_id, subCategoryId,thumbnail, title, brand_synonyms, model_name_synonyms, source_product_names, \
56
                 category, subCategory):
57
        #Skubundle id
58
        self.id = id
59
        #_id of skus
60
        self.ids = ids
61
        self.brand = brand
62
        self.model_name = model_name
63
        self.category_id = category_id
64
        self.subCategoryId = subCategoryId
65
        self.thumbnail = thumbnail 
66
        self.title= title
67
        self.brand_synonyms = brand_synonyms
68
        self.model_name_synonyms = model_name_synonyms
69
        self.source_product_names = source_product_names
70
        self.category = category
71
        self.subCategory = subCategory
72
 
73
    def toJSON(self):
74
        return json.dumps(self, default=lambda o: o.__dict__, 
75
            sort_keys=True, indent=4)
76
 
77
class __Catalog:
78
 
79
    def __init__(self, id, rank, title, items):
80
        #Skubundle id
81
        self.id = id
82
        self.rank = rank
83
        self.title = title
84
        self._childDocuments_ = items
85
    def toJSON(self):
86
        return json.dumps(self, default=lambda o: o.__dict__)
87
 
88
class __Item:
89
    def __init__(self, id, color, tags):
90
        self.id = id
91
        self.color = color
92
        self._childDocuments_ = tags
93
        def toJSON(self):
94
            return json.dumps(self, default=lambda o: o.__dict__)
95
class __Tag:
96
    def __init__(self, id, sellingPrice, mop):
97
        self.id = id
98
        self.sellingPrice = sellingPrice
99
        self.mop = mop
100
 
101
 
102
#solr = pysolr.Solr(options.solrPath, timeout=10)
103
 
104
 
105
def todict(obj, classkey=None):
106
    if isinstance(obj, dict):
107
        data = {}
108
        for (k, v) in obj.items():
109
            data[k] = todict(v, classkey)
110
        return data
111
    elif hasattr(obj, "_ast"):
112
        return todict(obj._ast())
113
    elif hasattr(obj, "__iter__"):
114
        return [todict(v, classkey) for v in obj]
115
    elif hasattr(obj, "__dict__"):
116
        data = dict([(key, todict(value, classkey)) 
117
            for key, value in obj.__dict__.iteritems() 
118
            if not callable(value) and not key.startswith('_')])
119
        if classkey is not None and hasattr(obj, "__class__"):
120
            data[classkey] = obj.__class__.__name__
121
        return data
122
    else:
123
        return obj
124
 
125
 
126
def populateTagItems():
127
 
128
 
24109 amit.gupta 129
    tagRankingList = session.query(Tag_Ranking).order_by(desc(Tag_Ranking.rankPoints)).all()
130
    rankingList = []
131
    featureMap = {}
132
    for tagRanking in tagRankingList:
133
        rankingList.append(tagRanking.catalogItemId)
134
        featureMap[tagRanking.catalogItemId]=tagRanking.feature
22307 amit.gupta 135
    catalogMap = {}
136
    #stmt = session.query(PrivateDeals).filter_by(isActive=1).filter(now().between(PrivateDeals.startDate, PrivateDeals.endDate)).subquery()
137
    #query = session.query(Item, privateDealAlias.dealPrice).outerjoin((privateDealAlias, Item.id==privateDealAlias.item_id)).filter(Item.status != status.PHASED_OUT)
24008 amit.gupta 138
    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))
23802 amit.gupta 139
    projection={'defaultImageUrl':1}
22307 amit.gupta 140
    for tag, item in tuples:
24071 amit.gupta 141
        if item.brand == "Live Demo":
142
            continue
22307 amit.gupta 143
        if not catalogMap.has_key(item.catalog_item_id):
144
            catalogObj = {}
145
            catalogObj['title'] = " ".join(filter(None, [item.brand, item.model_name,  item.model_number]))
24053 amit.gupta 146
            catalogObj['brand'] = (item.brand)
147
            if item.brand == 'Huawei' or item.brand == 'Honor':
148
                catalogObj['brand'] = ('Huawei', 'Honor')
22307 amit.gupta 149
            catalogObj['identifier'] = item.catalog_item_id
150
            catalogObj['items'] = {}
23807 amit.gupta 151
            catalogObj['hot_deals'] = "False"
22307 amit.gupta 152
            filterMap = {"_id":item.catalog_item_id}
153
            #Dont include it catalog not available
154
            try:
23802 amit.gupta 155
                catalogObj['imageUrl'] = get_mongo_connection(options.mongoHost).CONTENT.siteContent.find_one(filterMap, projection)['defaultImageUrl']
22317 amit.gupta 156
                print catalogObj['imageUrl']
22307 amit.gupta 157
            except:
23354 amit.gupta 158
                try:
24103 amit.gupta 159
                    catalogObj['imageUrl'] = 'http://api.profittill.com/uploads/campaigns/' + str(item.catalog_item_id )+ '.jpg'
23354 amit.gupta 160
                except:
161
                    traceback.print_exc()
22307 amit.gupta 162
            try: 
24109 amit.gupta 163
                catalogObj['rank'] = rankingList.index(item.catalog_item_id)
22307 amit.gupta 164
            except:
165
                #A very big number
24109 amit.gupta 166
                traceback.print_exc()
23354 amit.gupta 167
                catalogObj['rank'] = 50000000
24113 amit.gupta 168
            if featureMap.has_key(item.catalog_item_id):
24114 amit.gupta 169
                if featureMap.get(item.catalog_item_id) is None:
170
                    catalogObj['feature'] = ""
24115 amit.gupta 171
                else:
172
                    catalogObj['feature'] = featureMap.get(item.catalog_item_id)
24113 amit.gupta 173
            else:
24112 amit.gupta 174
                catalogObj['feature'] = ""
23354 amit.gupta 175
            #Mobile and tablets are showcased in same category
22307 amit.gupta 176
            catalogObj['categoryId'] = 3 if item.category in [10006, 10009] else 6   
24028 amit.gupta 177
            catalogObj['create_timestamp'] = to_java_date(tag.create_timestamp)
22307 amit.gupta 178
            catalogMap[item.catalog_item_id] = catalogObj
179
 
23808 amit.gupta 180
        catalogObj = catalogMap.get(item.catalog_item_id)
181
 
23807 amit.gupta 182
        if tag.hot_deals:
183
            catalogObj['hot_deals'] = "True"
22307 amit.gupta 184
 
185
        if not  catalogObj['items'].has_key(item.id):
24104 amit.gupta 186
            catalogObj['items'][item.id] = {'color': item.color.replace("f_", ""), 'tagPricing':[]}
22307 amit.gupta 187
 
188
        itemMap = catalogObj['items'].get(item.id)
189
        itemMap['tagPricing'].append(tag)
190
 
191
 
192
    catalogObjs = []
193
    for catalogId, catalogMap in catalogMap.iteritems():
194
        itemsMap = catalogMap['items']
195
        itemObjs = []
196
        for itemId, itemMap in itemsMap.iteritems():
197
            tags = itemMap['tagPricing']
198
            for tag in tags:
22315 amit.gupta 199
                itemObj = {'id':('itemtag-%s-%s'%(itemId, tag.tag_id)), 'color_s':itemMap['color'],  'itemId_i': itemId, 'tagId_i':tag.tag_id, 
200
                           'mop_f': tag.mop, 'sellingPrice_f': tag.selling_price}
22307 amit.gupta 201
            itemObjs.append(itemObj)
24053 amit.gupta 202
        catalogObj = {'id':'catalog' + str(catalogId), 'rank_i':catalogMap['rank'], 'title_s': catalogMap['title'],'hot_deals_b':catalogMap['hot_deals'], 
203
                      '_childDocuments_':itemObjs, 
24110 amit.gupta 204
                      'catalogId_i':catalogId, 'imageUrl_s': catalogMap['imageUrl'], 'feature_s':catalogMap['feature'],
24053 amit.gupta 205
                      'brand_ss': catalogMap['brand'], 'create_s':catalogMap['create_timestamp'], 'categoryId_i':catalogMap['categoryId']}
22307 amit.gupta 206
        catalogObjs.append(catalogObj)
207
    solr.delete(q='*:*')
208
    solr.add(catalogObjs)
209
 
210
 
211
 
212
 
213
 
214
    #items = Item.query.filter(Item.risky==True).filter(or_(Item.status==status.ACTIVE)).all()
215
#    global con
216
#    if con is None:
217
#        print "Establishing connection %s host and port %d" %(host,port)
218
#        try:
219
#            con = pymongo.MongoClient(host, port)
220
#        except Exception, e:
221
#            print e
222
#            return None
223
#    return con
224
 
225
def pushData():
226
    #rankPoints = populateRankPoints()
227
    populateTagItems()
228
    #orderedMap = orderIt
229
    #convertToSolrDoc() 
230
 
231
if __name__=='__main__':
232
    pushData()
22318 amit.gupta 233
    #solr.delete(q='*:*')
234
    #solr.add([{'_childDocuments_': [{'itemId_i': 26564L, 'mop_f': 100.0, 'tagId_i': 2L, 'sellingPrice_f': 2600.0, 'color_s': '', 'id': 'itemtag-26564-2'}, {'itemId_i': 1, 'mop_f': 460.0, 'tagId_i': 2, 'sellingPrice_f': 500.0, 'color_s': 'Black', 'id': 'dummy'}], 'catalogId_i': 1019937L, 'rank_i': 500000, 'id': 'catalog1019937', 'title_s': 'Micromax Spark Vdeo Q415'}, {'_childDocuments_': [{'itemId_i': 26691L, 'mop_f': 4500.0, 'tagId_i': 4L, 'sellingPrice_f': 4299.0, 'color_s': 'Gold', 'id': 'itemtag-26691-4'}], 'catalogId_i': 1020034L, 'rank_i': 500000, 'id': 'catalog1020034', 'title_s': 'Samsung Z2'}, {'_childDocuments_': [{'itemId_i': 21585L, 'mop_f': 33000.0, 'tagId_i': 4L, 'sellingPrice_f': 31990.0, 'color_s': '', 'id': 'itemtag-21585-4'}], 'catalogId_i': 1015720L, 'rank_i': 500000, 'id': 'catalog1015720', 'title_s': 'HTC One A9 16GB'}, {'_childDocuments_': [{'itemId_i': 15663L, 'mop_f': 8000.0, 'tagId_i': 4L, 'sellingPrice_f': 7529.0, 'color_s': 'Black', 'id': 'itemtag-15663-4'}], 'catalogId_i': 1010735L, 'rank_i': 500000, 'id': 'catalog1010735', 'title_s': 'HTC Desire 210 Dual SIM'}, {'_childDocuments_': [{'itemId_i': 15549L, 'mop_f': 11000.0, 'tagId_i': 4L, 'sellingPrice_f': 10599.0, 'color_s': 'Matte Blue', 'id': 'itemtag-15549-4'}], 'catalogId_i': 1010312L, 'rank_i': 500000, 'id': 'catalog1010312', 'title_s': 'HTC Desire 310'}, {'_childDocuments_': [{'itemId_i': 18083L, 'mop_f': 10500.0, 'tagId_i': 4L, 'sellingPrice_f': 9999.0, 'color_s': 'Black', 'id': 'itemtag-18083-4'}], 'catalogId_i': 1012434L, 'rank_i': 500000, 'id': 'catalog1012434', 'title_s': 'HTC Desire 326G'}, {'_childDocuments_': [{'itemId_i': 26864L, 'mop_f': 3500.0, 'tagId_i': 4L, 'sellingPrice_f': 3299.0, 'color_s': 'Black', 'id': 'itemtag-26864-4'}], 'catalogId_i': 1020180L, 'rank_i': 500000, 'id': 'catalog1020180', 'title_s': 'Intex Aqua A4'}, {'_childDocuments_': [{'itemId_i': 26872L, 'mop_f': 4500.0, 'tagId_i': 4L, 'sellingPrice_f': 4299.0, 'color_s': 'Black', 'id': 'itemtag-26872-4'}], 'catalogId_i': 1020185L, 'rank_i': 500000, 'id': 'catalog1020185', 'title_s': 'Karbonn Indian 9 4G VoLTE'}, {'_childDocuments_': [{'itemId_i': 16404L, 'mop_f': 13950.0, 'tagId_i': 4L, 'sellingPrice_f': 13799.0, 'color_s': 'Pearl White', 'id': 'itemtag-16404-4'}], 'catalogId_i': 1011256L, 'rank_i': 500000, 'id': 'catalog1011256', 'title_s': 'HTC Desire 516 Dual SIM'}, {'_childDocuments_': [{'itemId_i': 26860L, 'mop_f': 3300.0, 'tagId_i': 4L, 'sellingPrice_f': 3199.0, 'color_s': 'Black', 'id': 'itemtag-26860-4'}], 'catalogId_i': 1020025L, 'rank_i': 500000, 'id': 'catalog1020025', 'title_s': 'Karbonn A40 Indian'}, {'_childDocuments_': [{'itemId_i': 26614L, 'mop_f': 4000.0, 'tagId_i': 4L, 'sellingPrice_f': 3890.0, 'color_s': 'Champagne', 'id': 'itemtag-26614-4'}], 'catalogId_i': 1019962L, 'rank_i': 500000, 'id': 'catalog1019962', 'title_s': 'Intex Aqua Strong 5.1 Plus'}])