Subversion Repositories SmartDukaan

Rev

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