Subversion Repositories SmartDukaan

Rev

Rev 1264 | Rev 1278 | 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]
1080 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 = sheet.row_values(rownum)[0:15]
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:
1264 chandransh 87
            if item.mrp != mrp or item.dealerPrice != dp or item.transfer_price != xfer_price:
88
                updated_items.append(sheet.row_values(rownum)[0:15] + [item.mrp, item.dealerPrice, item.transfer_price])
1080 chandransh 89
 
90
        if category_id !=None and category_id != "":
91
            item.category = int(category_id)
92
 
93
        if dp != "":
94
            item.dealerPrice = dp
95
            item.sellingPrice = dp
629 rajveer 96
 
1080 chandransh 97
        if mrp != "" and mop != "" and mrp <  mop:
1271 chandransh 98
            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 99
 
100
        if mop != "" and xfer_price != "" and xfer_price > mop:
1271 chandransh 101
            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 102
        if mrp != "":
103
            if item.mrp == None or item.mrp >= mrp:
104
                item.mrp = mrp
105
            else:
1271 chandransh 106
                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 107
 
629 rajveer 108
        if mop != "":
109
            item.mop = mop
1080 chandransh 110
            item.sellingPrice = mop
111
 
724 chandransh 112
        if xfer_price !="":
113
            item.transfer_price = xfer_price
1080 chandransh 114
 
115
        item.startDate = datetime.datetime.now()
116
 
117
        item.model_name = model_name
118
 
629 rajveer 119
        if weight != "":    
120
            item.weight = weight
1264 chandransh 121
#        if start_date != "":
122
#            item.startDate = datetime.datetime(*xlrd.xldate_as_tuple(start_date, workbook.datemode))
1080 chandransh 123
 
124
#        item.bestDealText = deal_text
125
#        if deal_value != "":
126
#            item.bestDealValue = deal_value
127
#        item.comments = comments
128
 
626 chandransh 129
        item.updatedOn = updatedOn
724 chandransh 130
 
131
        item_change_log = ItemChangeLog()
132
        item_change_log.new_status = item.status
133
        item_change_log.timestamp = updatedOn
134
        item_change_log.item = item
1080 chandransh 135
 
136
        if not dry_run:
137
            session.commit()
138
 
1264 chandransh 139
    write_report("new_items.csv", new_items, sheet, False)
140
    write_report("updated_items.csv", updated_items, sheet, True)
141
    phased_out_items = [key.split(';') for key in list(existing_items_set)]
142
    write_report("phased_out_items.csv", phased_out_items, sheet, True)
1080 chandransh 143
 
144
    if (not dry_run) and full_update:
145
        query_string =  "UPDATE " + str(Item.table) + " SET status=" + str(status.PHASED_OUT) + ", updatedOn='"+ str(updatedOn) +"'"+\
146
                        " WHERE updatedOn <> '" + str(updatedOn) + "' AND hotspotCategory='" + category +"'";
147
        session.execute(query_string, mapper=Item)
626 chandransh 148
        session.commit()
149
 
150
    print "Successfully updated the item list information."
151
 
1264 chandransh 152
def write_report(filename, items, sheet, is_item):
1080 chandransh 153
    items_writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_ALL)
1264 chandransh 154
    items_writer.writerow(sheet.row_values(0) + ['Old MRP', 'Old DP', 'Old TP'])
155
    if is_item:
156
        for item in items:
157
            #print item
158
            items_writer.writerow([str(value) for value in item])
159
    else:
160
        for i in items:
161
            #print sheet.row_values(i)
162
            items_writer.writerow([str(value) for value in sheet.row_values(i)])
1080 chandransh 163
 
626 chandransh 164
def main():
165
    parser = optparse.OptionParser()
166
    parser.add_option("-f", "--file", dest="filename",
167
                   default="ItemList.xls", type="string",
168
                   help="Read the item list from FILE",
169
                   metavar="FILE")
1080 chandransh 170
    parser.add_option("-c", "--category", dest="category",
171
                      type="string",
172
                      help="Update the list only for the products belonging to CATEGORY",
173
                      metavar="CATEGORY")
174
    parser.add_option("-d", "--dry-run", dest="dry_run",
175
                      action="store_true",
176
                      help="Dry run only reporting on pending changes.Please note that some of the items can be reported twice.")
177
    parser.add_option("-a", "--full", dest="full_update",
178
                      action="store_true",
179
                      help="In a full update, all older items are marked as PHASED_OUT. Also see -pm.")
180
    parser.add_option("-p", "--partial", dest="full_update",
181
                      action="store_false",
182
                      help="In a partial update, older items are left as is. Also see -fm.")
183
    parser.set_defaults(full_update=True, dry_run=False, category="Handsets")
626 chandransh 184
    (options, args) = parser.parse_args()
185
    if len(args) != 0:
186
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
187
    filename = options.filename
1080 chandransh 188
    load_item_data(filename, options.category, options.full_update, options.dry_run)
626 chandransh 189
 
190
if __name__ == '__main__':
191
    main()