Subversion Repositories SmartDukaan

Rev

Rev 10253 | Blame | Compare with Previous | Last modification | View Log | RSS feed

#!/usr/bin/python
# coding: ascii
'''
@author: Phani Kumar
'''
import optparse
import csv
import xlrd
import datetime

if __name__ == '__main__' and __package__ is None:
    import sys
    import os
    sys.path.insert(0, os.getcwd())

from shop2020.thriftpy.model.v1.catalog.ttypes import status
from shop2020.model.v1.catalog.impl import DataService
from shop2020.model.v1.catalog.impl.DataService import Item, Vendor, VendorItemPricing, VendorItemMapping
from elixir import *
from shop2020.utils.EmailAttachmentSender import get_attachment_part, mail

from_user = 'cnc.center@shop2020.in'
from_pwd = '5h0p2o2o'
to = ["khushal.bhatia@shop2020.in", "chaitnaya.vats@shop2020.in", "manish.sharma@shop2020.in", "chandan.kumar@shop2020.in","manoj.kumar@shop2020.in"]

def load_item_data(filename, vendorId):
    DataService.initialize('catalog')
    
    vendor = Vendor.get_by(id=vendorId)
    if vendor is None:
        raise Exception("No vendor found for the id: " + str(vendorId))
    
    workbook = xlrd.open_workbook(filename)
    sheet = workbook.sheet_by_index(0)
    num_rows = sheet.nrows
    new_items = []
    phased_out_items = []
    updated_items = []
    unchanged_items = []
    
    for rownum in range(1, num_rows):
        print sheet.row_values(rownum)
        
        product_group, brand, model_number, model_name, color,\
        dp, mrp, mop, xfer_price = sheet.row_values(rownum)[0:9]
        
        if isinstance(model_number, float):
            model_number = str(int(model_number))
        
        item = None
        vendor_item_pricing = None
        keys = []
        if product_group.strip().lower() == 'New Handset'.strip().lower():
            for our_group in ["handsets", "mobile handset", "smart phone"]:
                new_key = our_group.strip().lower() + '|' + brand.strip().lower() + '|' + model_number.strip().lower() + '|' + color.strip().lower()
                keys.append(new_key)
        else:
            new_key = product_group.strip().lower() + '|' + brand.strip().lower() + '|' + model_number.strip().lower() + '|' + color.strip().lower()
            keys.append(new_key)
        
        i = 0
        for key in keys:
            i = i + 1
            vendor_item_mapping = VendorItemMapping.get_by(vendor=vendor, item_key=key)
            if vendor_item_mapping:
                item = vendor_item_mapping.item
                if item is not None and item.status != status.PHASED_OUT:
                    vendor_item_pricing = VendorItemPricing.get_by(vendor=vendor, item=item)
                    if vendor_item_pricing is None:
                        updated_items.append(sheet.row_values(rownum)[0:9] + [None, item.mrp, None, None, item.sellingPrice])
                    elif item.mrp != mrp or vendor_item_pricing.dealerPrice != dp or vendor_item_pricing.transfer_price != xfer_price or vendor_item_pricing.mop != mop:
                        updated_items.append(sheet.row_values(rownum)[0:9] + [vendor_item_pricing.dealerPrice, item.mrp, vendor_item_pricing.mop, vendor_item_pricing.transfer_price, item.sellingPrice])
                    else:
                        unchanged_items.append(rownum)
                else:
                    phased_out_items.append(rownum)
                break
            elif i == len(keys):
                new_items.append(rownum)

    write_report("/tmp/new_items.csv", new_items, sheet, False)
    write_report("/tmp/phased_out_items.csv", phased_out_items, sheet, False)
    write_report("/tmp/updated_items.csv", updated_items, sheet, True)
    write_report("/tmp/unchanged_items.csv", unchanged_items, sheet, False)
    
    attachment_part = [get_attachment_part("/tmp/new_items.csv"), get_attachment_part("/tmp/phased_out_items.csv"), get_attachment_part("/tmp/updated_items.csv"), get_attachment_part("/tmp/unchanged_items.csv")]
    mail(from_user, from_pwd, to, "Comparison report for " + os.path.basename(filename), "This is a system generated email.Please don't reply to it.", attachment_part)

def write_report(filename, items, sheet, is_item):
    '''
    Iterates through the items list and writes all the values to the specified
    filename in the CSV format. 'is_item' indicates whether the list consists
    of row numbers or complete row data.
    '''
    items_writer = csv.writer(open(filename, "wb"), delimiter=',', quoting=csv.QUOTE_ALL)
    items_writer.writerow(sheet.row_values(0)[0:9] + ['Old DP', 'Old MRP', 'Old FBP', 'Old TP', 'SP'])
    if is_item:
        #The list contains the complete rows.
        for item in items:
            print item
            items_writer.writerow([str(value) for value in item])
    else:
        #The list only has row numbers. We've to fetch the data ourselves.
        for i in items:
            print sheet.row_values(i)
            items_writer.writerow([str(value) for value in sheet.row_values(i)[0:9]])

def main():
    parser = optparse.OptionParser()
    parser.add_option("-f", "--file", dest="filename",
                   default="ItemList.xls", type="string",
                   help="Read the item list from FILE",
                   metavar="FILE")
    parser.add_option("-v", "--vendor", dest="vendor",
                      type="int",
                      help="Update the pricing information for VENDOR",
                      metavar="VENDOR")
    parser.set_defaults(vendor=1)
    (options, args) = parser.parse_args()
    if len(args) != 0:
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
    filename = options.filename
    load_item_data(filename, options.vendor)

if __name__ == '__main__':
    main()