Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
626 chandransh 1
#!/usr/bin/python
1080 chandransh 2
 
626 chandransh 3
import optparse
1080 chandransh 4
import csv
626 chandransh 5
import xlrd
6
import datetime
7
 
8
if __name__ == '__main__' and __package__ is None:
9
    import sys
10
    import os
11
    sys.path.insert(0, os.getcwd())
12
 
13
from shop2020.thriftpy.model.v1.catalog.ttypes import status
14
from shop2020.model.v1.catalog.impl import DataService
724 chandransh 15
from shop2020.model.v1.catalog.impl.DataService import Item, EntityIDGenerator,\
1356 chandransh 16
    ItemChangeLog, Vendor, VendorItemPricing, VendorItemMapping
626 chandransh 17
from elixir import *
18
 
1810 chandransh 19
def load_item_data(filename, vendorId, category, full_update, dry_run, supplied_product_group):
1250 chandransh 20
    DataService.initialize('catalog')
1356 chandransh 21
 
22
    vendor = Vendor.get_by(id=vendorId)
23
    if vendor is None:
24
        raise Exception("No vendor found for the id: " + str(vendorId))
626 chandransh 25
 
26
    workbook = xlrd.open_workbook(filename)
27
    sheet = workbook.sheet_by_index(0)
28
    num_rows = sheet.nrows
29
    updatedOn = datetime.datetime.now()
1080 chandransh 30
    new_items = []
1264 chandransh 31
    updated_items = []
1356 chandransh 32
 
33
    existing_vendor_item_mappings = VendorItemMapping.query.filter_by(vendor=vendor, vendor_category=category).all()
34
    existing_vendor_item_mappings_set = set([mapping.item_key for mapping in existing_vendor_item_mappings])
35
 
626 chandransh 36
    for rownum in range(1, num_rows):
1833 chandransh 37
        print sheet.row_values(rownum)
1356 chandransh 38
        catalog_item_id, category_id = [None, None]
1264 chandransh 39
 
1833 chandransh 40
        if supplied_product_group != None and supplied_product_group != '':
1810 chandransh 41
            our_brand, our_model_number, our_color,\
42
            brand, model_number, model_name, color,\
43
            dp, mrp, mop, sp,\
44
            comments, hotspot_category, unused_feature, xfer_price, weight, start_date, deal_text, deal_value = sheet.row_values(rownum)[0:19]
45
            product_group = supplied_product_group
46
        else:
47
            our_brand, our_model_number, our_color,\
48
            product_group, brand, model_number, model_name, color,\
49
            dp, mrp, mop, sp,\
50
            comments, hotspot_category, unused_feature, xfer_price, weight, start_date, deal_text, deal_value = sheet.row_values(rownum)[0:20]
51
 
1833 chandransh 52
        print product_group
53
 
626 chandransh 54
        if isinstance(model_number, float):
55
            model_number = str(int(model_number))
1810 chandransh 56
 
57
        if our_brand == '':
58
            our_brand = brand
59
        if our_model_number == '':
60
            our_model_number = model_number
61
        if our_color == '':
62
            our_color = color
63
 
1633 chandransh 64
        if sp == '':
65
            sp = mop 
1356 chandransh 66
        item = None
67
        vendor_item_pricing = None
1080 chandransh 68
 
1356 chandransh 69
        key = product_group.strip().lower() + '|' + brand.strip().lower() + '|' + model_number.strip().lower() + '|' + color.strip().lower()
70
        if key in existing_vendor_item_mappings_set:
71
            existing_vendor_item_mappings_set.remove(key)
72
            item = VendorItemMapping.query.filter_by(vendor=vendor, item_key=key, vendor_category=category).one().item
73
 
626 chandransh 74
        if item is None:
1080 chandransh 75
            #print "[ADDING:]{0} {1} {2} {3} to our catalogue.".format(product_group, brand, model_number, color)
76
            new_items.append(rownum)
626 chandransh 77
            item = Item()
1356 chandransh 78
            item.product_group = product_group
1810 chandransh 79
            item.brand = our_brand
80
            item.model_number = our_model_number
81
            item.color = our_color
626 chandransh 82
            item.status = status.IN_PROCESS
83
            item.addedOn = updatedOn
1089 chandransh 84
            item.hotspotCategory = category
1356 chandransh 85
 
1506 chandransh 86
            if category == 'Handsets':
87
                item.preferredWarehouse = 1
88
            else:
89
                item.preferredWarehouse = 2
90
 
1356 chandransh 91
            vendor_item_mapping = VendorItemMapping(vendor=vendor, item=item, item_key=key, vendor_category=category)
1359 chandransh 92
            vendor_item_pricing = VendorItemPricing(vendor=vendor, item=item)
93
 
626 chandransh 94
            session.add(item)
1356 chandransh 95
            session.add(vendor_item_mapping)
1359 chandransh 96
            session.add(vendor_item_pricing)
1080 chandransh 97
 
98
            if catalog_item_id !=None and catalog_item_id != "":
99
                #Add category and entity id
100
                item.catalog_item_id = int(catalog_item_id)
101
                item.category = int(category_id)
102
                item.status = status.ACTIVE
103
            else:
104
                # Check if a similar item already exists in our database
1810 chandransh 105
                similar_item = Item.query.filter_by(product_group=product_group, brand = our_brand, model_number=our_model_number, hotspotCategory=category).first()
1356 chandransh 106
                print "[SIMILAR ITEM FOUND:] FOR {0} {1} {2} {3}".format(product_group, brand, model_number, color)
107
 
1080 chandransh 108
                if similar_item is None or similar_item.catalog_item_id is None:
109
                    # If there is no similar item in the database from before,
110
                    # use the entity_id_generator
111
                    entity_id = EntityIDGenerator.query.first()
112
                    item.catalog_item_id = entity_id.id + 1
113
                    entity_id.id = entity_id.id  + 1
114
                else:
115
                    #If a similar item already exists for a product group, brand and model_number, set it as same.
116
                    item.catalog_item_id = similar_item.catalog_item_id
117
                    item.category = similar_item.category
1356 chandransh 118
                    item.status = similar_item.status
626 chandransh 119
        else:
1356 chandransh 120
            # If this item already existed and one of its price parameters has changed
1278 chandransh 121
            # in which case we add it to the list of updated items for reporting.
1356 chandransh 122
            vendor_item_pricing = VendorItemPricing.get_by(vendor=vendor, item=item)
123
            if vendor_item_pricing is None:
124
                vendor_item_pricing = VendorItemPricing(vendor=vendor, item=item)
125
                session.add(vendor_item_pricing)
126
 
1633 chandransh 127
            if item.mrp != mrp or vendor_item_pricing.dealerPrice != dp or vendor_item_pricing.transfer_price != xfer_price or item.sellingPrice != sp:
128
                updated_items.append(sheet.row_values(rownum)[0:19] + [item.mrp, item.dealerPrice, item.transfer_price])
1080 chandransh 129
 
130
        if category_id !=None and category_id != "":
131
            item.category = int(category_id)
132
 
133
        if dp != "":
134
            item.dealerPrice = dp
135
            item.sellingPrice = dp
1356 chandransh 136
            vendor_item_pricing.dealerPrice = dp
629 rajveer 137
 
1080 chandransh 138
        if mrp != "" and mop != "" and mrp <  mop:
1271 chandransh 139
            raise Exception("[BAD MRP and MOP:] for {0} {1} {2} {3}. MRP={4}. MOP={5}".format(product_group, brand, model_number, color, mrp, mop))
1080 chandransh 140
 
1633 chandransh 141
        if mrp != "" and sp != "" and mrp < sp:
142
            raise Exception("[BAD MRP and SP:] for {0} {1} {2} {3}. MRP={4}. SP={5}".format(product_group, brand, model_number, color, mrp, sp))
143
 
1080 chandransh 144
        if mop != "" and xfer_price != "" and xfer_price > mop:
1271 chandransh 145
            raise Exception("[BAD MOP and TP:] for {0} {1} {2} {3}. TP={4}. MOP={5}".format(product_group, brand, model_number, color, xfer_price, mop))
1320 chandransh 146
#        if mrp != "":
147
#            if item.mrp == None or item.mrp >= mrp:
148
#                item.mrp = mrp
149
#            else:
150
#                raise Exception("[NEW MRP MORE THAN old MRP:] for {0} {1} {2} {3}. Old mrp={4}. New MRP={5}".format(product_group, brand, model_number, color, item.mrp, mrp))
873 rajveer 151
 
1431 chandransh 152
        if mrp != "":
153
            item.mrp = mrp
154
 
629 rajveer 155
        if mop != "":
156
            item.mop = mop
1356 chandransh 157
            vendor_item_pricing.mop = mop
1080 chandransh 158
 
724 chandransh 159
        if xfer_price !="":
160
            item.transfer_price = xfer_price
1356 chandransh 161
            vendor_item_pricing.transfer_price = xfer_price
1080 chandransh 162
 
1431 chandransh 163
        if item.startDate == None or item.startDate == '':
164
            item.startDate = datetime.datetime.now()
1080 chandransh 165
 
1633 chandransh 166
        item.sellingPrice = sp
1080 chandransh 167
        item.model_name = model_name
168
 
629 rajveer 169
        if weight != "":    
170
            item.weight = weight
1264 chandransh 171
#        if start_date != "":
172
#            item.startDate = datetime.datetime(*xlrd.xldate_as_tuple(start_date, workbook.datemode))
1080 chandransh 173
 
174
#        item.bestDealText = deal_text
175
#        if deal_value != "":
176
#            item.bestDealValue = deal_value
177
#        item.comments = comments
178
 
626 chandransh 179
        item.updatedOn = updatedOn
724 chandransh 180
 
181
        item_change_log = ItemChangeLog()
182
        item_change_log.new_status = item.status
183
        item_change_log.timestamp = updatedOn
184
        item_change_log.item = item
1080 chandransh 185
 
186
        if not dry_run:
187
            session.commit()
188
 
1264 chandransh 189
    write_report("new_items.csv", new_items, sheet, False)
190
    write_report("updated_items.csv", updated_items, sheet, True)
1356 chandransh 191
    phased_out_items = [key.split('|') for key in list(existing_vendor_item_mappings_set)]
1264 chandransh 192
    write_report("phased_out_items.csv", phased_out_items, sheet, True)
1080 chandransh 193
 
194
    if (not dry_run) and full_update:
195
        query_string =  "UPDATE " + str(Item.table) + " SET status=" + str(status.PHASED_OUT) + ", updatedOn='"+ str(updatedOn) +"'"+\
196
                        " WHERE updatedOn <> '" + str(updatedOn) + "' AND hotspotCategory='" + category +"'";
197
        session.execute(query_string, mapper=Item)
626 chandransh 198
        session.commit()
199
 
200
    print "Successfully updated the item list information."
201
 
1264 chandransh 202
def write_report(filename, items, sheet, is_item):
1080 chandransh 203
    items_writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_ALL)
1264 chandransh 204
    items_writer.writerow(sheet.row_values(0) + ['Old MRP', 'Old DP', 'Old TP'])
205
    if is_item:
206
        for item in items:
1833 chandransh 207
            print item
1264 chandransh 208
            items_writer.writerow([str(value) for value in item])
209
    else:
210
        for i in items:
1833 chandransh 211
            print sheet.row_values(i)
1264 chandransh 212
            items_writer.writerow([str(value) for value in sheet.row_values(i)])
1080 chandransh 213
 
626 chandransh 214
def main():
215
    parser = optparse.OptionParser()
216
    parser.add_option("-f", "--file", dest="filename",
217
                   default="ItemList.xls", type="string",
218
                   help="Read the item list from FILE",
219
                   metavar="FILE")
1080 chandransh 220
    parser.add_option("-c", "--category", dest="category",
221
                      type="string",
222
                      help="Update the list only for the products belonging to CATEGORY",
223
                      metavar="CATEGORY")
1356 chandransh 224
    parser.add_option("-v", "--vendor", dest="vendor",
225
                      type="int",
226
                      help="Update the pricing information for VENDOR",
227
                      metavar="VENDOR")
1080 chandransh 228
    parser.add_option("-d", "--dry-run", dest="dry_run",
229
                      action="store_true",
230
                      help="Dry run only reporting on pending changes.Please note that some of the items can be reported twice.")
231
    parser.add_option("-a", "--full", dest="full_update",
232
                      action="store_true",
233
                      help="In a full update, all older items are marked as PHASED_OUT. Also see -pm.")
234
    parser.add_option("-p", "--partial", dest="full_update",
235
                      action="store_false",
236
                      help="In a partial update, older items are left as is. Also see -fm.")
1356 chandransh 237
    parser.add_option("-g", "--product-group", dest="product_group",
238
                      type="string",
239
                      help="Set GROUP as the product group for all items added/updated during this run.",
240
                      metavar="GROUP")
241
    parser.set_defaults(full_update=True, dry_run=False, category="Handsets", vendor=1)
626 chandransh 242
    (options, args) = parser.parse_args()
243
    if len(args) != 0:
244
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
245
    filename = options.filename
1356 chandransh 246
    load_item_data(filename, options.vendor, options.category, options.full_update, options.dry_run, options.product_group)
626 chandransh 247
 
248
if __name__ == '__main__':
249
    main()