Subversion Repositories SmartDukaan

Rev

Rev 23807 | Rev 24008 | 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
16
#import pymongo
17
#import pysolr
18
 
19
 
20
parser = optparse.OptionParser()
22308 amit.gupta 21
parser.add_option("-d", "--d", dest="dbHost",
22
                      default="127.0.0.1",
22307 amit.gupta 23
                      type="string", help="The HOST where the mysql server is running",
22308 amit.gupta 24
                      metavar="DBHOST")
22307 amit.gupta 25
parser.add_option("-s", "--s", dest="solrPath",
22318 amit.gupta 26
                      default="http://localhost:8984/solr/demo1",
22307 amit.gupta 27
                      type="string", help="Complete solr path",
22308 amit.gupta 28
                      metavar="SOLRHOST")
29
parser.add_option("-m", "--m", dest="mongoHost",
22311 amit.gupta 30
                      default="localhost",
22308 amit.gupta 31
                      type="string", help="Complete solr path",
22307 amit.gupta 32
                      metavar="HOST")
33
 
34
(options, args) = parser.parse_args()
35
 
22312 amit.gupta 36
con=None
22307 amit.gupta 37
 
22310 amit.gupta 38
DataService.initialize(db_hostname=options.dbHost)
22307 amit.gupta 39
solr = pysolr.Solr(options.solrPath, timeout=10)
40
 
22308 amit.gupta 41
def get_mongo_connection(host='localhost', port=27017):
42
    global con
43
    if con is None:
44
        print "Establishing connection %s host and port %d" %(host,port)
45
        try:
46
            con = pymongo.MongoClient(host, port)
47
        except Exception, e:
48
            print e
49
            return None
50
    return con
22307 amit.gupta 51
 
52
class __SkuInfo:
53
 
54
    def __init__(self, id, ids, brand, model_name, category_id, subCategoryId,thumbnail, title, brand_synonyms, model_name_synonyms, source_product_names, \
55
                 category, subCategory):
56
        #Skubundle id
57
        self.id = id
58
        #_id of skus
59
        self.ids = ids
60
        self.brand = brand
61
        self.model_name = model_name
62
        self.category_id = category_id
63
        self.subCategoryId = subCategoryId
64
        self.thumbnail = thumbnail 
65
        self.title= title
66
        self.brand_synonyms = brand_synonyms
67
        self.model_name_synonyms = model_name_synonyms
68
        self.source_product_names = source_product_names
69
        self.category = category
70
        self.subCategory = subCategory
71
 
72
    def toJSON(self):
73
        return json.dumps(self, default=lambda o: o.__dict__, 
74
            sort_keys=True, indent=4)
75
 
76
class __Catalog:
77
 
78
    def __init__(self, id, rank, title, items):
79
        #Skubundle id
80
        self.id = id
81
        self.rank = rank
82
        self.title = title
83
        self._childDocuments_ = items
84
    def toJSON(self):
85
        return json.dumps(self, default=lambda o: o.__dict__)
86
 
87
class __Item:
88
    def __init__(self, id, color, tags):
89
        self.id = id
90
        self.color = color
91
        self._childDocuments_ = tags
92
        def toJSON(self):
93
            return json.dumps(self, default=lambda o: o.__dict__)
94
class __Tag:
95
    def __init__(self, id, sellingPrice, mop):
96
        self.id = id
97
        self.sellingPrice = sellingPrice
98
        self.mop = mop
99
 
100
 
101
#solr = pysolr.Solr(options.solrPath, timeout=10)
102
 
103
 
104
def todict(obj, classkey=None):
105
    if isinstance(obj, dict):
106
        data = {}
107
        for (k, v) in obj.items():
108
            data[k] = todict(v, classkey)
109
        return data
110
    elif hasattr(obj, "_ast"):
111
        return todict(obj._ast())
112
    elif hasattr(obj, "__iter__"):
113
        return [todict(v, classkey) for v in obj]
114
    elif hasattr(obj, "__dict__"):
115
        data = dict([(key, todict(value, classkey)) 
116
            for key, value in obj.__dict__.iteritems() 
117
            if not callable(value) and not key.startswith('_')])
118
        if classkey is not None and hasattr(obj, "__class__"):
119
            data[classkey] = obj.__class__.__name__
120
        return data
121
    else:
122
        return obj
123
 
124
 
125
def populateTagItems():
126
 
127
 
128
    tagRankingList = session.query(Tag_Ranking.catalogItemId).order_by(desc(Tag_Ranking.rankPoints)).all()
22318 amit.gupta 129
    tagRankingList = [catalogId for (catalogId,) in tagRankingList]
22307 amit.gupta 130
 
131
    catalogMap = {}
132
    #stmt = session.query(PrivateDeals).filter_by(isActive=1).filter(now().between(PrivateDeals.startDate, PrivateDeals.endDate)).subquery()
133
    #query = session.query(Item, privateDealAlias.dealPrice).outerjoin((privateDealAlias, Item.id==privateDealAlias.item_id)).filter(Item.status != status.PHASED_OUT)
23355 amit.gupta 134
    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)).filter(Tag_Listing.active==True)
23802 amit.gupta 135
    projection={'defaultImageUrl':1}
22307 amit.gupta 136
    for tag, item in tuples:
137
        if not catalogMap.has_key(item.catalog_item_id):
138
            catalogObj = {}
139
            catalogObj['title'] = " ".join(filter(None, [item.brand, item.model_name,  item.model_number]))
22332 amit.gupta 140
            catalogObj['brand'] = item.brand
22307 amit.gupta 141
            catalogObj['identifier'] = item.catalog_item_id
142
            catalogObj['items'] = {}
23807 amit.gupta 143
            catalogObj['hot_deals'] = "False"
22307 amit.gupta 144
            filterMap = {"_id":item.catalog_item_id}
145
            #Dont include it catalog not available
146
            try:
23802 amit.gupta 147
                catalogObj['imageUrl'] = get_mongo_connection(options.mongoHost).CONTENT.siteContent.find_one(filterMap, projection)['defaultImageUrl']
22317 amit.gupta 148
                print catalogObj['imageUrl']
22307 amit.gupta 149
            except:
23354 amit.gupta 150
                try:
23358 amit.gupta 151
                    catalogObj['imageUrl'] = 'http://api.profittill.com/uploads/campaigns/' + str(item.catalog_item_id) + '.jpg'
23354 amit.gupta 152
                except:
153
                    traceback.print_exc()
154
                    continue
22307 amit.gupta 155
            try: 
156
                catalogObj['rank'] = tagRankingList.index(item.catalog_item_id)
157
            except:
158
                #A very big number
23354 amit.gupta 159
                catalogObj['rank'] = 50000000
22318 amit.gupta 160
                traceback.print_exc()
23354 amit.gupta 161
            #Mobile and tablets are showcased in same category
22307 amit.gupta 162
            catalogObj['categoryId'] = 3 if item.category in [10006, 10009] else 6   
163
            catalogMap[item.catalog_item_id] = catalogObj
164
 
23808 amit.gupta 165
        catalogObj = catalogMap.get(item.catalog_item_id)
166
 
23807 amit.gupta 167
        if tag.hot_deals:
168
            catalogObj['hot_deals'] = "True"
22307 amit.gupta 169
 
170
        if not  catalogObj['items'].has_key(item.id):
171
            catalogObj['items'][item.id] = {'color': item.color, 'tagPricing':[]}
172
 
173
        itemMap = catalogObj['items'].get(item.id)
174
        itemMap['tagPricing'].append(tag)
175
 
176
 
177
    catalogObjs = []
178
    for catalogId, catalogMap in catalogMap.iteritems():
179
        itemsMap = catalogMap['items']
180
        itemObjs = []
181
        for itemId, itemMap in itemsMap.iteritems():
182
            tags = itemMap['tagPricing']
183
            for tag in tags:
22315 amit.gupta 184
                itemObj = {'id':('itemtag-%s-%s'%(itemId, tag.tag_id)), 'color_s':itemMap['color'],  'itemId_i': itemId, 'tagId_i':tag.tag_id, 
185
                           'mop_f': tag.mop, 'sellingPrice_f': tag.selling_price}
22307 amit.gupta 186
            itemObjs.append(itemObj)
23806 tejbeer 187
        catalogObj = {'id':'catalog' + str(catalogId), 'rank_i':catalogMap['rank'], 'title_s': catalogMap['title'],'hot_deals_b':catalogMap['hot_deals'], '_childDocuments_':itemObjs, 'catalogId_i':catalogId, 'imageUrl_s': catalogMap['imageUrl'], 
22334 amit.gupta 188
                      'brand_s': catalogMap['brand']}
22307 amit.gupta 189
        catalogObjs.append(catalogObj)
190
    solr.delete(q='*:*')
191
    solr.add(catalogObjs)
192
 
193
 
194
 
195
 
196
 
197
    #items = Item.query.filter(Item.risky==True).filter(or_(Item.status==status.ACTIVE)).all()
198
#    global con
199
#    if con is None:
200
#        print "Establishing connection %s host and port %d" %(host,port)
201
#        try:
202
#            con = pymongo.MongoClient(host, port)
203
#        except Exception, e:
204
#            print e
205
#            return None
206
#    return con
207
 
208
def pushData():
209
    #rankPoints = populateRankPoints()
210
    populateTagItems()
211
    #orderedMap = orderIt
212
    #convertToSolrDoc() 
213
 
214
if __name__=='__main__':
215
    pushData()
22318 amit.gupta 216
    #solr.delete(q='*:*')
217
    #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'}])