Subversion Repositories SmartDukaan

Rev

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