Subversion Repositories SmartDukaan

Rev

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