Subversion Repositories SmartDukaan

Rev

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