Subversion Repositories SmartDukaan

Rev

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

Rev 5065 Rev 5440
Line 1... Line 1...
1
#!/usr/bin/python
1
#!/usr/bin/python
-
 
2
# coding: ascii
2
'''
3
'''
3
This script is used to load item details in the catalog database.
4
This script is used to load item details in the catalog database.
4
It's now mostly used for Accessories since they come in huge numbers.
5
It's now mostly used for Accessories since they come in huge numbers.
5
 
6
 
6
@author: Chandranshu
7
@author: Chandranshu
Line 13... Line 14...
13
if __name__ == '__main__' and __package__ is None:
14
if __name__ == '__main__' and __package__ is None:
14
    import sys
15
    import sys
15
    import os
16
    import os
16
    sys.path.insert(0, os.getcwd())
17
    sys.path.insert(0, os.getcwd())
17
 
18
 
18
from shop2020.thriftpy.model.v1.catalog.ttypes import status
19
from shop2020.thriftpy.model.v1.catalog.ttypes import status, ItemType
19
from shop2020.model.v1.catalog.impl import DataService
20
from shop2020.model.v1.catalog.impl import DataService
20
from shop2020.model.v1.catalog.impl.DataService import Item, EntityIDGenerator,\
21
from shop2020.model.v1.catalog.impl.DataService import Item, EntityIDGenerator,\
21
    ItemChangeLog, Vendor, VendorItemPricing, VendorItemMapping
22
    ItemChangeLog, Vendor, VendorItemPricing, VendorItemMapping
22
from elixir import *
23
from elixir import *
23
 
24
 
24
def load_item_data(filename, vendorId, full_update, dry_run, supplied_product_group):
25
def load_item_data(filename, vendorId, full_update, dry_run):
25
    DataService.initialize('catalog')
26
    DataService.initialize('catalog')
26
    
27
    
27
    vendor = Vendor.get_by(id=vendorId)
28
    vendor = Vendor.get_by(id=vendorId)
28
    if vendor is None:
29
    if vendor is None:
29
        raise Exception("No vendor found for the id: " + str(vendorId))
30
        raise Exception("No vendor found for the id: " + str(vendorId))
30
 
31
    
31
    workbook = xlrd.open_workbook(filename)
32
    workbook = xlrd.open_workbook(filename)
32
    sheet = workbook.sheet_by_index(0)
33
    sheet = workbook.sheet_by_index(0)
33
    num_rows = sheet.nrows
34
    num_rows = sheet.nrows
34
    updatedOn = datetime.datetime.now()
35
    updatedOn = datetime.datetime.now()
35
    new_items = []
36
    new_items = []
36
    updated_items = []
37
    updated_items = []
37
    not_created_items = []
38
    not_created_items = []
38
    
39
    
39
    existing_vendor_item_mappings = VendorItemMapping.query.filter_by(vendor=vendor).all()
-
 
40
    existing_vendor_item_mappings_set = set([mapping.item_key for mapping in existing_vendor_item_mappings])
-
 
41
 
-
 
42
    for rownum in range(1, num_rows):
40
    for rownum in range(1, num_rows):
43
        print sheet.row_values(rownum)
41
        print sheet.row_values(rownum)
44
        
42
        
45
        if supplied_product_group != None and supplied_product_group != '':
-
 
46
            our_brand, our_model_number, our_model_name, our_color,\
43
        our_brand, our_model_number, our_model_name, our_color,\
47
            brand, model_number, model_name, color,\
44
        product_group, brand, model_number, model_name, color,\
48
            dp, mrp, mop, sp, xfer_price,\
45
        dp, mrp, mop, sp, xfer_price,\
49
            comments, weight, start_date, deal_text, deal_value,\
46
        comments, weight, start_date, deal_text, deal_value,\
50
            warranty_period, defaultWarehouse, preferredWarehouse, preferredVendor = sheet.row_values(rownum)[0:22]
47
        warranty_period, serialized, hasItemNo, preferredVendor = sheet.row_values(rownum)[0:23]
51
            product_group = supplied_product_group
-
 
52
        else:
48
        
53
            our_brand, our_model_number, our_model_name, our_color,\
-
 
54
            product_group, brand, model_number, model_name, color,\
-
 
55
            dp, mrp, mop, sp, xfer_price,\
-
 
56
            comments, weight, start_date, deal_text, deal_value,\
-
 
57
            warranty_period, defaultWarehouse, preferredWarehouse, preferredVendor = sheet.row_values(rownum)[0:23]
-
 
58
 
-
 
59
        print product_group
49
        print product_group
60
 
50
        
61
        if isinstance(model_number, float):
51
        if isinstance(model_number, float):
62
            model_number = str(int(model_number))
52
            model_number = str(int(model_number))
63
        
53
        
64
        if isinstance(our_model_number, float):
54
        if isinstance(our_model_number, float):
65
            our_model_number = str(int(our_model_number))
55
            our_model_number = str(int(our_model_number))
Line 78... Line 68...
78
        item = None
68
        item = None
79
        similar_item = None
69
        similar_item = None
80
        vendor_item_pricing = None
70
        vendor_item_pricing = None
81
        
71
        
82
        key = product_group.strip().lower() + '|' + brand.strip().lower() + '|' + model_number.strip().lower() + '|' + color.strip().lower()
72
        key = product_group.strip().lower() + '|' + brand.strip().lower() + '|' + model_number.strip().lower() + '|' + color.strip().lower()
83
        if key in existing_vendor_item_mappings_set:
-
 
84
            existing_vendor_item_mappings_set.remove(key)
-
 
85
        
73
        
86
        # Check if a similar items already exists in our database
74
        # Check if a similar items already exists in our database
87
        similar_items = Item.query.filter_by(brand=our_brand.strip(), model_number=our_model_number.strip(), model_name=our_model_name.strip()).all()
75
        similar_items = Item.query.filter_by(brand=our_brand.strip(), model_number=our_model_number.strip(), model_name=our_model_name.strip()).all()
88
        
76
        
89
        # Check if a similar item already exists in our database
77
        # Check if a similar item already exists in our database
Line 120... Line 108...
120
            # since for example if their is a item with red color in our database and we are creating a new item with no color for the same product which is wrong.
108
            # since for example if their is a item with red color in our database and we are creating a new item with no color for the same product which is wrong.
121
            if item is None and not check_color_valid(our_color):
109
            if item is None and not check_color_valid(our_color):
122
                not_created_items.append(rownum)
110
                not_created_items.append(rownum)
123
                continue
111
                continue
124
        
112
        
125
        
-
 
126
        if item is None:
113
        if item is None:
127
            #print "[ADDING:]{0} {1} {2} {3} to our catalogue.".format(brand, model_number, model_name, color)
114
            #print "[ADDING:]{0} {1} {2} {3} to our catalogue.".format(brand, model_number, model_name, color)
128
            new_items.append(rownum)
115
            new_items.append(rownum)
129
            item = Item()
116
            item = Item()
130
            item.brand = our_brand.strip()
117
            item.brand = our_brand.strip()
Line 136... Line 123...
136
            item.status_description = "This item is in process"
123
            item.status_description = "This item is in process"
137
            item.addedOn = updatedOn
124
            item.addedOn = updatedOn
138
            
125
            
139
            vendor_item_mapping = VendorItemMapping(vendor=vendor, item=item, item_key=key)
126
            vendor_item_mapping = VendorItemMapping(vendor=vendor, item=item, item_key=key)
140
            vendor_item_pricing = VendorItemPricing(vendor=vendor, item=item)
127
            vendor_item_pricing = VendorItemPricing(vendor=vendor, item=item)
141
 
128
            
142
            session.add(item)
129
            session.add(item)
143
            session.add(vendor_item_mapping)
130
            session.add(vendor_item_mapping)
144
            session.add(vendor_item_pricing)
131
            session.add(vendor_item_pricing)
145
            
132
            
146
            if similar_item is None or similar_item.catalog_item_id is None:
133
            if similar_item is None or similar_item.catalog_item_id is None:
Line 183... Line 170...
183
            if vendor_item_pricing is None:
170
            if vendor_item_pricing is None:
184
                vendor_item_pricing = VendorItemPricing(vendor=vendor, item=item)
171
                vendor_item_pricing = VendorItemPricing(vendor=vendor, item=item)
185
                session.add(vendor_item_pricing)
172
                session.add(vendor_item_pricing)
186
            
173
            
187
            if item.mrp != mrp or vendor_item_pricing.dealerPrice != dp or vendor_item_pricing.transfer_price != xfer_price or item.sellingPrice != sp:
174
            if item.mrp != mrp or vendor_item_pricing.dealerPrice != dp or vendor_item_pricing.transfer_price != xfer_price or item.sellingPrice != sp:
188
                updated_items.append(sheet.row_values(rownum)[0:19] + [item.mrp, vendor_item_pricing.dealerPrice, vendor_item_pricing.transfer_price])
175
                updated_items.append(sheet.row_values(rownum)[0:23] + [item.mrp, vendor_item_pricing.dealerPrice, vendor_item_pricing.transfer_price, item.sellingPrice])
189
        
176
        
190
        if dp != "":
177
        if dp != "":
191
            item.sellingPrice = dp
178
            item.sellingPrice = dp
192
            vendor_item_pricing.dealerPrice = dp
179
            vendor_item_pricing.dealerPrice = dp
193
        
180
        
194
        if mrp != "" and mop != "" and mrp <  mop:
181
        if mrp != "" and mop != "" and mrp <  mop:
195
            raise Exception("[BAD MRP and MOP:] for {0} {1} {2} {3}. MRP={4}. MOP={5}".format(brand, model_number, model_name, color, mrp, mop))
182
            raise Exception("[BAD MRP and MOP:] for {0} {1} {2} {3}. MRP={4}. MOP={5}".format(brand, model_number, model_name, color, mrp, mop))
196
 
183
        
197
        if mrp != "" and sp != "" and mrp < sp:
184
        if mrp != "" and sp != "" and mrp < sp:
198
            raise Exception("[BAD MRP and SP:] for {0} {1} {2} {3}. MRP={4}. SP={5}".format(brand, model_number, model_name, color, mrp, sp))
185
            raise Exception("[BAD MRP and SP:] for {0} {1} {2} {3}. MRP={4}. SP={5}".format(brand, model_number, model_name, color, mrp, sp))
199
 
186
        
200
        if mop != "" and xfer_price != "" and xfer_price > mop:
187
        if mop != "" and xfer_price != "" and xfer_price > mop:
201
            raise Exception("[BAD MOP and TP:] for {0} {1} {2} {3}. TP={4}. MOP={5}".format(brand, model_number, model_name, color, xfer_price, mop))
188
            raise Exception("[BAD MOP and TP:] for {0} {1} {2} {3}. TP={4}. MOP={5}".format(brand, model_number, model_name, color, xfer_price, mop))
202
#        if mrp != "":
-
 
203
#            if item.mrp == None or item.mrp >= mrp:
-
 
204
#                item.mrp = mrp
-
 
205
#            else:
-
 
206
#                raise Exception("[NEW MRP MORE THAN old MRP:] for {0} {1} {2} {3}. Old mrp={4}. New MRP={5}".format(brand, model_number, model_name, color, item.mrp, mrp))
-
 
207
        
-
 
208
        if defaultWarehouse == None or defaultWarehouse == "":
-
 
209
            raise Exception("[Default Warehouse required:] for {0} {1} {2} {3}".format(brand, model_number, model_name, color))
-
 
210
        else:
-
 
211
            try:
-
 
212
                item.defaultWarehouse = int(defaultWarehouse)
-
 
213
            except:
-
 
214
                raise Exception("[Default Warehouse should be number:] for {0} {1} {2} {3}. defaultWarehouse={4}".format(brand, model_number, model_name, color, defaultWarehouse))
-
 
215
        
189
        
216
        if preferredVendor == None or preferredVendor == "":
190
        if preferredVendor == None or preferredVendor == "":
217
            raise Exception("[Preferred Vendor required:] for {0} {1} {2} {3}".format(brand, model_number, model_name, color))
191
            raise Exception("[Preferred Vendor required:] for {0} {1} {2} {3}".format(brand, model_number, model_name, color))
218
        else:
192
        else:
219
            try:
193
            try:
220
                item.preferredVendor = int(preferredVendor)
194
                item.preferredVendor = int(preferredVendor)
221
            except:
195
            except:
222
                raise Exception("[Preferred Vendor should be number:] for {0} {1} {2} {3}. preferredVendor={4}".format(brand, model_number, model_name, color, preferredVendor))
196
                raise Exception("[Preferred Vendor should be number:] for {0} {1} {2} {3}. preferredVendor={4}".format(brand, model_number, model_name, color, preferredVendor))
223
        
197
        
224
        if warranty_period != "":
198
        if serialized == None or serialized == "":
-
 
199
            raise Exception("[Serialized required:] for {0} {1} {2} {3}".format(brand, model_number, model_name, color))
-
 
200
        else:
225
            try:
201
            try:
-
 
202
                if serialized:
226
                item.warranty_period = int(warranty_period)
203
                    item.type = ItemType.SERIALIZED
-
 
204
                else:
-
 
205
                    item.type = ItemType.NON_SERIALIZED
227
            except:
206
            except:
-
 
207
                raise Exception("[Serialized should be either TRUE(SERIALIZED) or FALSE(NON_SERIALIZED):] for {0} {1} {2} {3}. serialized={4}".format(brand, model_number, model_name, color, serialized))
-
 
208
        
-
 
209
        if hasItemNo == None or hasItemNo == "":
-
 
210
            raise Exception("[hasItemNo required:] for {0} {1} {2} {3}".format(brand, model_number, model_name, color))
-
 
211
        else:
-
 
212
            try:
-
 
213
                if hasItemNo:
-
 
214
                    item.hasItemNo = 1
228
                pass
215
                else:
-
 
216
                    item.hasItemNo = 0
-
 
217
            except:
-
 
218
                raise Exception("[hasItemNo should be either TRUE or FALSE:] for {0} {1} {2} {3}. hasItemNo={4}".format(brand, model_number, model_name, color, hasItemNo))
229
        
219
        
230
        if preferredWarehouse != "":
220
        if warranty_period != "":
231
            try:
221
            try:
232
                item.preferredWarehouse = int(preferredWarehouse)
222
                item.warranty_period = int(warranty_period)
233
            except:
223
            except:
234
                pass
224
                pass
235
        
225
        
236
        if mrp != "":
226
        if mrp != "":
237
            item.mrp = mrp
227
            item.mrp = mrp
238
        
228
        
239
        if mop != "":
229
        if mop != "":
240
            vendor_item_pricing.mop = mop
230
            vendor_item_pricing.mop = mop
241
 
231
        
242
        if xfer_price !="":
232
        if xfer_price !="":
243
            vendor_item_pricing.transfer_price = xfer_price
233
            vendor_item_pricing.transfer_price = xfer_price
244
        
234
        
245
        if start_date is not None and start_date != '':
235
        if start_date is not None and start_date != '':
246
            #If a start date has been specified, it takes precedence.
236
            #If a start date has been specified, it takes precedence.
247
            item.startDate = datetime.datetime(*xlrd.xldate_as_tuple(start_date, workbook.datemode))
237
            item.startDate = datetime.datetime(*xlrd.xldate_as_tuple(start_date, workbook.datemode))
248
        elif item.startDate == None or item.startDate == '': 
238
        elif item.startDate == None or item.startDate == '': 
249
            #If start date is not specified and item's start date is not set, set it to current time
239
            #If start date is not specified and item's start date is not set, set it to current time
250
            item.startDate = datetime.datetime.now()
240
            item.startDate = datetime.datetime.now()
251
 
241
        
252
        item.sellingPrice = sp
242
        item.sellingPrice = sp
253
 
243
        
254
        if weight != "":    
244
        if weight != "":    
255
            item.weight = weight
245
            item.weight = weight
256
        
246
        
257
#        item.bestDealText = deal_text
-
 
258
#        if deal_value != "":
-
 
259
#            item.bestDealValue = deal_value
-
 
260
#        item.comments = comments
-
 
261
 
-
 
262
        item.updatedOn = updatedOn
247
        item.updatedOn = updatedOn
263
        
248
        
264
        item_change_log = ItemChangeLog()
249
        item_change_log = ItemChangeLog()
265
        item_change_log.new_status = item.status
250
        item_change_log.new_status = item.status
266
        item_change_log.timestamp = updatedOn
251
        item_change_log.timestamp = updatedOn
267
        item_change_log.item = item
252
        item_change_log.item = item
268
        
253
        
269
        if not dry_run:
254
        if not dry_run:
270
            session.commit()
255
            session.commit()
271
    
256
    
272
    write_report("items_not_created_dueto_color.csv", not_created_items, sheet, False)
257
    write_report("/tmp/items_not_created_dueto_color.csv", not_created_items, sheet, False)
273
    write_report("new_items.csv", new_items, sheet, False)
258
    write_report("/tmp/new_items.csv", new_items, sheet, False)
274
    write_report("updated_items.csv", updated_items, sheet, True)
259
    write_report("/tmp/updated_items.csv", updated_items, sheet, True)
275
    phased_out_items = [key.split('|') for key in list(existing_vendor_item_mappings_set)]
-
 
276
    write_report("phased_out_items.csv", phased_out_items, sheet, True)
-
 
277
    
260
    
278
    if (not dry_run) and full_update:
261
    if (not dry_run) and full_update:
279
        query_string =  "UPDATE " + str(Item.table) + " SET status=" + str(status.PHASED_OUT) + ", status_description='This item has been phased out'" + ", updatedOn='"+ str(updatedOn) +"'"+\
262
        query_string =  "UPDATE " + str(Item.table) + " SET status=" + str(status.PHASED_OUT) + ", status_description='This item has been phased out'" + ", updatedOn='"+ str(updatedOn) +"'"+\
280
                        " WHERE updatedOn <> '" + str(updatedOn) + "'";
263
                        " WHERE updatedOn <> '" + str(updatedOn) + "'";
281
        session.execute(query_string, mapper=Item)
264
        session.execute(query_string, mapper=Item)
Line 295... Line 278...
295
    Iterates through the items list and writes all the values to the specified
278
    Iterates through the items list and writes all the values to the specified
296
    filename in the CSV format. 'is_item' indicates whether the list consists
279
    filename in the CSV format. 'is_item' indicates whether the list consists
297
    of row numbers or complete row data.
280
    of row numbers or complete row data.
298
    '''
281
    '''
299
    items_writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_ALL)
282
    items_writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_ALL)
300
    items_writer.writerow(sheet.row_values(0) + ['Old MRP', 'Old DP', 'Old TP'])
283
    items_writer.writerow(sheet.row_values(0)[0:23] + ['Old MRP', 'Old DP', 'Old TP', 'Old SP'])
301
    if is_item:
284
    if is_item:
302
        #The list contains the complete rows.
285
        #The list contains the complete rows.
303
        for item in items:
286
        for item in items:
304
            print item
287
            print item
305
            items_writer.writerow([str(value) for value in item])
288
            items_writer.writerow([str(value) for value in item])
306
    else:
289
    else:
307
        #The list only has row numbers. We've to fetch the data ourselves.
290
        #The list only has row numbers. We've to fetch the data ourselves.
308
        for i in items:
291
        for i in items:
309
            print sheet.row_values(i)
292
            print sheet.row_values(i)
310
            items_writer.writerow([str(value) for value in sheet.row_values(i)])
293
            items_writer.writerow([str(value) for value in sheet.row_values(i)[0:23]])
311
 
294
 
312
def main():
295
def main():
313
    parser = optparse.OptionParser()
296
    parser = optparse.OptionParser()
314
    parser.add_option("-f", "--file", dest="filename",
297
    parser.add_option("-f", "--file", dest="filename",
315
                   default="ItemList.xls", type="string",
298
                   default="ItemList.xls", type="string",
Line 326... Line 309...
326
                      action="store_true",
309
                      action="store_true",
327
                      help="In a full update, all older items are marked as PHASED_OUT. Also see -pm.")
310
                      help="In a full update, all older items are marked as PHASED_OUT. Also see -pm.")
328
    parser.add_option("-p", "--partial", dest="full_update",
311
    parser.add_option("-p", "--partial", dest="full_update",
329
                      action="store_false",
312
                      action="store_false",
330
                      help="In a partial update, older items are left as is. Also see -fm.")
313
                      help="In a partial update, older items are left as is. Also see -fm.")
331
    parser.add_option("-g", "--product-group", dest="product_group",
-
 
332
                      type="string",
-
 
333
                      help="Set GROUP as the product group for all items added/updated during this run.",
-
 
334
                      metavar="GROUP")
-
 
335
    parser.set_defaults(full_update=True, dry_run=False, vendor=1)
314
    parser.set_defaults(full_update=True, dry_run=False, vendor=1)
336
    (options, args) = parser.parse_args()
315
    (options, args) = parser.parse_args()
337
    if len(args) != 0:
316
    if len(args) != 0:
338
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
317
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
339
    filename = options.filename
318
    filename = options.filename
340
    load_item_data(filename, options.vendor, options.full_update, options.dry_run, options.product_group)
319
    load_item_data(filename, options.vendor, options.full_update, options.dry_run)
341
 
320
 
342
if __name__ == '__main__':
321
if __name__ == '__main__':
343
    main()
322
    main()