Subversion Repositories SmartDukaan

Rev

Rev 7260 | Rev 8901 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.catalog.dashboard.client;

import in.shop2020.catalog.dashboard.shared.Item;
import in.shop2020.catalog.dashboard.shared.Utils;
import in.shop2020.catalog.dashboard.shared.VendorItemMapping;
import in.shop2020.catalog.dashboard.shared.VendorPricings;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;

/**
 * ItemForm is a DialogBox which is created on the click of Add Item button in ItemActions.
 * This contains UI fields to fill up item attributes. It also contains tables for adding
 * vendor prices and vendor mapping keys.
 *
 */
public class ItemForm extends DialogBox implements ComingSoon{

    interface ItemFormUiBinder extends UiBinder<Widget, ItemForm> {}
    private static ItemFormUiBinder uiBinder = GWT.create(ItemFormUiBinder.class);
    
    private final static CatalogServiceAsync catalogService = GWT.create(CatalogService.class);
    private final int TABLE_INDEX_VENDORID = 0,
                      TABLE_INDEX_VENDOR_DESC = 1, 
                      TABLE_INDEX_ITEM_KEY = 2,
                      TABLE_INDEX_MOP = 2,
                      TABLE_INDEX_DP = 3,
                      TABLE_INDEX_TP = 4,
                      TABLE_INDEX_NLC = 5;
    
    private static boolean entityIdMandatory = Utils.isEntityIdMandatory();

    @UiField TextBox productGroup, catalogItemId;
    @UiField TextBox brand, modelNumber, modelName, color, comments,holdInventory,defaultInventory;
    @UiField TextBox mrp, sellingPrice, weight, bestDealText, bestDealValue, bestSellingRank,bestDealsDetailsText,bestDealsDetailsLink, minStockLevel, numOfDaysStock, freebieItemId,asin;
    @UiField DateBox startDate, retireDate, comingSoonStartDate, expectedArrivalDate;
    @UiField Button addButton, cancelButton, comingSoonButton;
    @UiField CheckBox defaultForEntity, risky, itemType, hasItemNo, clearance, showSellingPrice;
    @UiField FlexTable headerVendor, vendorTable;
    @UiField FlexTable headerVendorM, vendorTableM;
    @UiField ListBox preferredVendor,preferredInsurer;
    
    public ItemForm(){
        setText("Add New Item");
        setWidget(uiBinder.createAndBindUi(this));
        initVendorKeysHeader();
        initVendorPricesHeader();
        preferredVendor.addItem("select");
        for(Entry<Long, String> e : Utils.getAllVendors().entrySet()){
                preferredVendor.addItem(e.getValue());
        }
        if(!entityIdMandatory) {
                catalogItemId.setEnabled(false);
        }
        preferredInsurer.addItem("select", "0");
        for(Entry<Long, String> e : Utils.getAllInsurers().entrySet()){
                preferredInsurer.addItem(e.getValue(),e.getKey().toString());
        }
        
    }
    
    /**
     * initialises vendor item key table header. Creates an Add button and
     * adds click event listener to it to create and pop up a dialog for adding 
     * a new vendor item key. 
     */
    private void initVendorKeysHeader(){
        headerVendorM.getColumnFormatter().setWidth(TABLE_INDEX_VENDORID, "128px");
        headerVendorM.getColumnFormatter().setWidth(TABLE_INDEX_VENDOR_DESC, "128px");
        headerVendorM.getColumnFormatter().setWidth(TABLE_INDEX_ITEM_KEY, "400px");
        headerVendorM.getColumnFormatter().setWidth(TABLE_INDEX_ITEM_KEY + 1, "50px");

        headerVendorM.setText(0, TABLE_INDEX_VENDORID, "Vendor Id");
        headerVendorM.setText(0, TABLE_INDEX_VENDOR_DESC, "Vendor");
        headerVendorM.setText(0, TABLE_INDEX_ITEM_KEY, "Item Key");
        
        headerVendorM.getCellFormatter().setVisible(0, TABLE_INDEX_VENDORID, false);
        
        Button addButton = new Button("Add");
        headerVendorM.setWidget(0, TABLE_INDEX_ITEM_KEY + 1, addButton);
        addButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                VendorMappingDialog vendorMappingDialog = new VendorMappingDialog(productGroup.getText().trim(), brand.getText().trim(), 
                        modelNumber.getText().trim(), color.getText().trim());
                vendorMappingDialog.updateButton.setText("Add");
                vendorMappingDialog.setVendorMappingUpdateListener(new VendorMappingDialog.VendorMappingUpdateListener() {
                    @Override
                    public boolean onUpdate(String key, long vendorId) {
                        final int row = vendorTableM.getRowCount();
                        vendorTableM.getColumnFormatter().setWidth(TABLE_INDEX_VENDORID, "128px");
                        vendorTableM.getColumnFormatter().setWidth(TABLE_INDEX_VENDOR_DESC, "128px");
                        vendorTableM.getColumnFormatter().setWidth(TABLE_INDEX_ITEM_KEY, "400px");
                        vendorTableM.getColumnFormatter().setWidth(TABLE_INDEX_ITEM_KEY + 1, "50px");
                        
                        vendorTableM.setText(row, TABLE_INDEX_VENDORID, vendorId + "");
                        vendorTableM.setText(row, TABLE_INDEX_VENDOR_DESC, Utils.getVendorDesc(vendorId));
                        vendorTableM.setText(row, TABLE_INDEX_ITEM_KEY, key);
                        Button removeButton = new Button("X");
                        vendorTableM.setWidget(row, TABLE_INDEX_ITEM_KEY + 1, removeButton);
                        
                        vendorTableM.getCellFormatter().setVisible(row, TABLE_INDEX_VENDORID, false);
                        removeButton.addClickHandler(new ClickHandler() {
                            @Override
                            public void onClick(ClickEvent event) {
                                vendorTableM.removeRow(row);
                            }
                        });
                        return true;
                    }
                });
                vendorMappingDialog.show();
            }
        });
    }
    
    /**
     * initialises vendor prices table header. Creates an Add button and
     * adds click event listener to it to create and pop up a dialog for adding 
     * a prices for a new vendor 
     */
    private void initVendorPricesHeader(){
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_VENDORID, "128px");
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_VENDOR_DESC, "128px");
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_MOP, "128px");
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_DP, "128px");
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_TP, "128px");
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_NLC, "128px");
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_NLC + 1, "50px");

        headerVendor.setText(0, TABLE_INDEX_VENDORID, "Vendor Id");
        headerVendor.setText(0, TABLE_INDEX_VENDOR_DESC, "Vendor");
        headerVendor.setText(0, TABLE_INDEX_MOP, "MOP");
        headerVendor.setText(0, TABLE_INDEX_DP, "Dealer Price");
        headerVendor.setText(0, TABLE_INDEX_TP, "Transfer Price");
        headerVendor.setText(0, TABLE_INDEX_NLC, "NLC");
        
        headerVendor.getCellFormatter().setVisible(0, TABLE_INDEX_VENDORID, false);
        
        Button addButton = new Button("Add");
        headerVendor.setWidget(0, TABLE_INDEX_NLC + 1, addButton);
        addButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                VendorPricesDialog vendorPricesDialog = new VendorPricesDialog();
                vendorPricesDialog.updateButton.setText("Add");
                vendorPricesDialog.setVendorPriceUpdateListener(new VendorPricesDialog.VendorPriceUpdateListener() {
                    @Override
                    public boolean onUpdate(double mop, double dp, double tp, double nlc, long vendorId) {
                        if(!vendorExists(vendorId)) {
                            Window.alert("Vendor already exists");
                            return false;
                        }
                        /*if(!validateVendorPrices(mop, dp, tp)) {
                            return false;
                        }*/
                        final int row = vendorTable.getRowCount();
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_VENDORID, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_VENDOR_DESC, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_MOP, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_DP, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_TP, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_NLC, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_NLC + 1, "50px");
                        
                        vendorTable.setText(row, TABLE_INDEX_VENDORID, vendorId + "");
                        vendorTable.setText(row, TABLE_INDEX_VENDOR_DESC, Utils.getVendorDesc(vendorId));
                        vendorTable.setText(row, TABLE_INDEX_MOP, mop + "");
                        vendorTable.setText(row, TABLE_INDEX_DP, dp + "");
                        vendorTable.setText(row, TABLE_INDEX_TP, tp + "");
                        vendorTable.setText(row, TABLE_INDEX_NLC, nlc + "");
                        
                        vendorTable.getCellFormatter().setVisible(row, TABLE_INDEX_VENDORID, false);
                        
                        Button removeButton = new Button("X");
                        vendorTable.setWidget(row, TABLE_INDEX_NLC + 1, removeButton);
                        removeButton.addClickHandler(new ClickHandler() {
                            @Override
                            public void onClick(ClickEvent event) {
                                vendorTable.removeRow(row);
                            }
                        });
                        return true;
                    }
                });
                vendorPricesDialog.show();
            }
        });
    }

    @UiHandler("addButton")
    /**
     * On add button click a new Item instance is created and all the information from UI fields is dumped in this item instance.
     * This item instance is then passed to the service to be added to the database.
     */
    void addItem(ClickEvent event) {
        if(entityIdMandatory) {
                long entityId = 0;
                try {
                if(!catalogItemId.getText().trim().isEmpty()) {
                    entityId = Long.parseLong(catalogItemId.getText().trim());
                    if(entityId <= 0) {
                        throw new NumberFormatException("Invalid value of Catalog Item Id");
                    }
                }
                else {
                        Window.alert("Catalog Item Id can not be empty");
                        return;
                }
            } catch(NumberFormatException ex) {
                Window.alert("Invalid value of Catalog Item Id");
                return;
            }
                catalogService.checkEntityId(entityId, new AsyncCallback<Boolean>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        GWT.log("Error checking Catalog Item Id");
                        Window.alert("Error checking Catalog Item Id");
                        return;
                    }
                    @Override
                    public void onSuccess(Boolean result) {
                                if(!result) {
                            Window.alert("Invalid value of Catalog Item Id");
                            return;
                        }
                        addNewItem();
                        }
                });
        }
        else {
                catalogService.checkSimilarItem(brand.getText().trim(), modelNumber.getText().trim(),
                                modelName.getText().trim(), color.getText().trim(), new AsyncCallback<Long>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        GWT.log("Error checking similar item");
                        Window.alert("Error checking similar item");
                        return;
                    }
                    @Override
                    public void onSuccess(Long result) {
                        if(result != 0) {
                            Window.alert("Similar product exists with Item Id " + result);
                            return;
                        }
                        addNewItem();
                    }
                });
        }
    }
    
    private void addNewItem() {
        Item item = new Item();
        
        if(!productGroup.getText().trim().isEmpty()) {
                item.setProductGroup(productGroup.getText().trim());
        }
        else {
                Window.alert("Product Group can not be empty.");
            return;
        }
        
        if(entityIdMandatory) {
                try {
                    if(!catalogItemId.getText().trim().isEmpty()) {
                        long entityId = Long.parseLong(catalogItemId.getText().trim());
                        if(entityId <= 0) {
                            throw new NumberFormatException("Invalid value of Catalog Item Id");
                        }
                        item.setCatalogItemId(entityId);
                    }
                    else {
                        Window.alert("Catalog Item Id can not be empty");
                        return;
                    }
                } catch(NumberFormatException ex) {
                    Window.alert("Invalid value of Catalog Item Id");
                    return;
                }
        }
        
        item.setBrand(brand.getText().trim());
        item.setModelNumber(modelNumber.getText().trim());
        item.setModelName(modelName.getText().trim());
        item.setColor(color.getText().trim());
        item.setComments(comments.getText().trim());
        try {
            if(!mrp.getText().trim().isEmpty()) {
                double mrpValue = Double.parseDouble(mrp.getText().trim());
                if(mrpValue <= 0) {
                    throw new NumberFormatException("Negative value of MRP");
                }
                item.setMrp(mrpValue);
            }
        } catch(NumberFormatException ex) {
            Window.alert("Invalid MRP format/value. Value shoule be greater than zero");
            return;
        }
        try {
            if(!sellingPrice.getText().trim().isEmpty()) {
                double spValue = Double.parseDouble(sellingPrice.getText().trim());
                if(spValue <= 0) {
                    throw new NumberFormatException("Negative value of Selling price");
                }
                item.setSellingPrice(spValue);
            }
        } catch(NumberFormatException ex) {
            Window.alert("Invalid Selling Price format/value. Value shoule be greater than zero");
            return;
        }
        try {
            if(!weight.getText().trim().isEmpty()) {
                double wtValue = Double.parseDouble(weight.getText().trim());
                if(wtValue <= 0) {
                    throw new NumberFormatException("Negative value of Weight");
                }
                item.setWeight(wtValue);
            }
        } catch(NumberFormatException ex) {
            Window.alert("Invalid weight format/value. Value shoule be greater than zero");
            return;
        }
        try {
            if(!startDate.getTextBox().getText().trim().equals("")) {
                item.setStartDate(startDate.getValue().getTime());
            }
        } catch(Exception ex) {
            Window.alert("Invalid start date format");
            return;
        }
        if(comingSoonStartDate.getValue()==null){
                item.setComingSoonStartDate(null);
        }else {
                item.setComingSoonStartDate(comingSoonStartDate.getValue().getTime());
        }
        if(expectedArrivalDate.getValue()==null){
                item.setExpectedArrivalDate(null);
        }else {
                item.setExpectedArrivalDate(expectedArrivalDate.getValue().getTime());
        }
        item.setBestDealsText(bestDealText.getText().trim());
        item.setBestDealsDetailsText(bestDealsDetailsText.getText().trim());
        item.setBestDealsDetailsLink(bestDealsDetailsLink.getText().trim());
        try {
            if(!bestDealValue.getText().trim().equals("")) {
                double bdValue = Double.parseDouble(bestDealValue.getText().trim());
                if(bdValue < 0) {
                    throw new NumberFormatException("Negative value of BestDealValue");
                }
                item.setBestDealsValue(bdValue);
            }
        } catch(NumberFormatException ex) {
            Window.alert("Invalid best deal value format");
            return;
        }
        try {
            if(!bestSellingRank.getText().trim().equals("")) {
                long bsrValue = Long.parseLong(bestSellingRank.getText().trim());
                if(bsrValue < 0) {
                    throw new NumberFormatException("Negative value of Best Selling Rank");
                }
                item.setBestSellingRank(bsrValue);
            }
        } catch(NumberFormatException ex) {
            Window.alert("Invalid best selling rank format");
            return;
        }
        
        try {
                if(!minStockLevel.getText().trim().equals("")) {
                    long msl = Long.parseLong(minStockLevel.getText().trim());
                    if(msl < 0) {
                        throw new NumberFormatException("Negative value of Min Stock Value");
                    }
                    item.setMinStockLevel(msl);
                }else {
                        item.setMinStockLevel(0L);
                }
            } catch(NumberFormatException ex) {
                item.setMinStockLevel(0L);
                Window.alert("Invalid min Stock Level. Setting it to zero(0)");
                return;
            }
            
            try {
                if(!numOfDaysStock.getText().trim().equals("")) {
                    Long nds = Long.parseLong(numOfDaysStock.getText().trim());
                    if(nds < 0) {
                        throw new NumberFormatException("Negative value of Num of Days Of Stock");
                    }
                    item.setNumOfDaysStock(nds.intValue());
                } else {
                        item.setNumOfDaysStock(0);
                }
            } catch(NumberFormatException ex) {
                item.setNumOfDaysStock(0);
                Window.alert("Invalid min Stock Level. Setting it to zero(0)");
                return;
            }
            
            try {
            if(!freebieItemId.getText().trim().equals("")) {
                long freeItemId = Long.parseLong(freebieItemId.getText().trim());
                if(freeItemId < 0) {
                    throw new NumberFormatException("Negative value of freebieItemId ");
                }
                item.setFreebieItemId(new Long(freeItemId));
            }
        } catch(NumberFormatException ex) {
            Window.alert("Invalid freebie ItemId");
            return;
        }
            item.setAsin(asin.getText().trim());
                    
        try {
            if(!holdInventory.getText().trim().equals("")) {
                long hold_inventory = Long.parseLong(holdInventory.getText().trim());
                if(hold_inventory < 0) {
                    throw new NumberFormatException("Negative value of Hold Inventory");
                }
                item.setHoldInventory(hold_inventory);
            }
        } catch(NumberFormatException ex) {
            Window.alert("Invalid Hold Inventory Value");
            return;
        }
      
        try {
            if(!defaultInventory.getText().trim().equals("")) {
                long default_inventory = Long.parseLong(defaultInventory.getText().trim());
                if(default_inventory < 0) {
                    throw new NumberFormatException("Negative value of Default Inventory");
                }
                item.setDefaultInventory(default_inventory);
            }
        } catch(NumberFormatException ex) {
            Window.alert("Invalid Default Inventory Value");
            return;
        }
        item.setDefaultForEntity(defaultForEntity.getValue());
        item.setRisky(risky.getValue());
        item.setHasItemNo(hasItemNo.getValue());
        item.setItemType(itemType.getValue());
        if(preferredVendor.getSelectedIndex() == 0) {
                Window.alert("Invalid Vendor Selected");
            return;
        }
        else {
                item.setPreferredVendor(Utils.getVendorId(preferredVendor.getItemText(preferredVendor.getSelectedIndex())));
        }
        
        item.setPreferredInsurer(Long.parseLong(preferredInsurer.getValue(preferredInsurer.getSelectedIndex())));
        
        
        /*Create an instance of VendorPricings for each row in vendor pricing table. Set the vendor prices to the instance.
          Add the instance to map and set the map to the item instance created above.*/
        Map<Long, VendorPricings> vendorPrices = new HashMap<Long, VendorPricings>();
        VendorPricings v;
        for(int row = 0; row < vendorTable.getRowCount(); row++) {
            v = new VendorPricings();
            v.setMop(Double.parseDouble(vendorTable.getText(row, TABLE_INDEX_MOP)));
            v.setDealerPrice(Double.parseDouble(vendorTable.getText(row, TABLE_INDEX_DP)));
            v.setTransferPrice(Double.parseDouble(vendorTable.getText(row, TABLE_INDEX_TP)));
            v.setVendorId(Long.parseLong(vendorTable.getText(row, TABLE_INDEX_VENDORID)));
            v.setNlc(Double.parseDouble(vendorTable.getText(row, TABLE_INDEX_NLC)));
            vendorPrices.put(v.getVendorId(), v);
        }
        item.setVendorPricesMap(vendorPrices);
        
        /*Create an instance of VendorPricings for each row in vendor pricing table. Set the vendor prices to the instance.
        Add the instance to map and set the map to the item instance created above.*/
        Map<String, VendorItemMapping> vendorMappings = new HashMap<String, VendorItemMapping>();
        VendorItemMapping vMapping;
        for(int row = 0; row < vendorTableM.getRowCount(); row++) {
            vMapping = new VendorItemMapping();
            vMapping.setItemKey(vendorTableM.getText(row, TABLE_INDEX_ITEM_KEY));
            vMapping.setVendorId(Long.parseLong(vendorTableM.getText(row, TABLE_INDEX_VENDORID)));
            vendorMappings.put(vMapping.getVendorId() + Item.KEY_SEPARATOR + vMapping.getItemKey(), vMapping);
        }
        item.setVendorKeysMap(vendorMappings);
        
        if(!Utils.validateItem(item)) {
            return;
        }
        
        /*Service method to add item. */
        catalogService.addItem(item, new AsyncCallback<Long>() {
            @Override
            public void onSuccess(Long result) {
                if(result == null || result == 0) {
                    Window.alert("Error while adding item");
                    return;
                }
                Window.alert("Item added successfully. Id = " + result);
                hide();
            }
            @Override
            public void onFailure(Throwable caught) {
                caught.printStackTrace();
                Window.alert("Error while adding item");
            }
        });
    }
    
    @UiHandler("cancelButton")
    void closeForm(ClickEvent event) {
        this.hide();
    }

    /**
     * Checks if vendor details already exists corresponding to the vendor Id parameter. 
     */
    private boolean vendorExists(long vendorId) {
        long id;
        for(int i = 0; i < vendorTable.getRowCount(); i++) {
            id = Long.parseLong(vendorTable.getText(i, TABLE_INDEX_VENDORID));
            if(vendorId == id) {
                return false;
            }
        }
        return true;
    }
    
    /**
     * validate vendor prices (MOP, DealerPrice, TransferPrice)
     */
    @SuppressWarnings("unused")
        private boolean validateVendorPrices(double mop, double dp, double tp) {
        double mrpValue;
        try {
            mrpValue = Double.parseDouble(mrp.getText().trim());
        } catch (NumberFormatException ex) {
            Window.alert("Invalid MRP value.");
            return false;
        }
        if(mrpValue < mop) {
            Window.alert("MOP cannot be more than MRP.");
            return false;
        }
        if(tp > mop) {
            Window.alert("Transfer Price cannot be more than MOP.");
            return false;
        }
        return true;
    }
    
        @UiHandler("comingSoonButton")
        void onComingSoonButtonClick(ClickEvent event) {
                ComingSoonDialog cd = new ComingSoonDialog(this);
                cd.show();
        }
        
        public void setComingSoonStartDate(Date date){
                this.comingSoonStartDate.setValue(date);
        }
        public void setBestDealsText(String bestDealsText){
                this.bestDealText.setText(bestDealsText);
        }

        public void setExpectedArrivalDate(Date date){
                this.expectedArrivalDate.setValue(date);
        }

        public void setShowPrice(boolean b){
                this.showSellingPrice.setValue(b);
        }

        public boolean isShowPrice(){
                return this.showSellingPrice.getValue();
        }

        @Override
        public String getBestDealsText() {
                return this.bestDealText.getValue();
        }

        @Override
        public Date getComingSoonStartDate() {
                return this.comingSoonStartDate.getValue();
        }

        @Override
        public Date getExpectedArrivalDate() {
                return this.expectedArrivalDate.getValue();
        }

        public TextBox getBestDealsDetailsText() {
                return bestDealsDetailsText;
        }

        public void setBestDealsDetailsText(TextBox bestDealsDetailsText) {
                this.bestDealsDetailsText = bestDealsDetailsText;
        }

        public TextBox getBestDealsDetailsLink() {
                return bestDealsDetailsLink;
        }

        public void setBestDealsDetailsLink(TextBox bestDealsDetailsLink) {
                this.bestDealsDetailsLink = bestDealsDetailsLink;
        }
}