Subversion Repositories SmartDukaan

Rev

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