Subversion Repositories SmartDukaan

Rev

Rev 2066 | Rev 2119 | 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.VendorDetails;

import java.util.HashMap;
import java.util.Map;

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.HTMLTable.Cell;
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;

public class ItemForm extends DialogBox {

    interface ItemFormUiBinder extends UiBinder<Widget, ItemForm> {}
    private static ItemFormUiBinder uiBinder = GWT.create(ItemFormUiBinder.class);
    
    private final 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 = 3, TABLE_INDEX_DP = 4, TABLE_INDEX_TP = 5;

    @UiField ListBox vendorCategory;
    @UiField TextBox productGroup;
    @UiField TextBox brand, modelNumber, modelName, color, comments;
    @UiField TextBox mrp, sellingPrice, weight, bestDealText, bestDealValue, bestSellingRank;
    @UiField DateBox startDate, retireDate;
    @UiField Button addButton, cancelButton;
    @UiField CheckBox defaultForEntity;
    @UiField FlexTable headerVendor, vendorTable;
    @UiField Button addVendorPrices;
    
    public ItemForm(){
        setText("Add New Item");
        setWidget(uiBinder.createAndBindUi(this));
        initPricingHeader();
        vendorCategory.addItem("Handsets");
        vendorCategory.addItem("Accessories");
    }
    
    
    private void initPricingHeader(){
        // Initialize the header.
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_VENDORID, "128px");
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_VENDOR_DESC, "128px");
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_ITEM_KEY, "250px");
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_MOP, "128px");
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_DP, "128px");
        headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_TP, "128px");

        headerVendor.setText(0, TABLE_INDEX_VENDORID, "Vendor Id");
        headerVendor.setText(0, TABLE_INDEX_VENDOR_DESC, "Vendor Desc");
        headerVendor.setText(0, TABLE_INDEX_ITEM_KEY, "Item Key");
        headerVendor.setText(0, TABLE_INDEX_MOP, "MOP");
        headerVendor.setText(0, TABLE_INDEX_DP, "Dealer Price");
        headerVendor.setText(0, TABLE_INDEX_TP, "Transfer Price");
    }

    @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 service implementation.
     */
    void addItem(ClickEvent event) {
        //TODO: validate UI fields
        
        Item item = new Item();
        
        item.setProductGroup(productGroup.getText().trim());
        item.setVendorCategory(vendorCategory.getItemText(vendorCategory.getSelectedIndex()));
        
        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 {
            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");
            return;
        }
        try {
            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");
            return;
        }
        try {
            if(!weight.getText().trim().equals("")) {
                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");
            return;
        }
        try {
            if(!startDate.getTextBox().getText().trim().equals("")) {
                item.setStartDate(startDate.getValue().getTime());
            }
        } catch(Exception ex) {
            Window.alert("Invalid start date format");
            return;
        }
        try {
            if(!retireDate.getTextBox().getText().trim().equals("")) {
                item.setRetireDate(retireDate.getValue().getTime());
            }
        } catch(Exception ex) {
            Window.alert("Invalid retire date format");
            return;
        }
        item.setBestDealsText(bestDealText.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;
        }
        item.setDefaultForEntity(defaultForEntity.getValue());
        
        /*Create an instance of VendorDetails for each row in vendor table. Set the vendor details to the instance.
          Add the instance to map and set the map to the item instance created above.*/
        Map<Long, VendorDetails> vendorPrices = new HashMap<Long, VendorDetails>();
        VendorDetails v;
        for(int row = 0; row < vendorTable.getRowCount(); row++) {
            v = new VendorDetails();
            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)));
            vendorPrices.put(v.getVendorId(), v);
            item.setMop(v.getMop());
            item.setDealerPrice(v.getDealerPrice());
            item.setTransferPrice(v.getTransferPrice());
        }
        item.setVendorDetails(vendorPrices);
        
        /*Service method to add item to DB. */
        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) {
                Window.alert("Error while adding item");
            }
        });
        
    }
    
    @UiHandler("cancelButton")
    void closeForm(ClickEvent event) {
        this.hide();
    }
    
    /**
     * This will pop up a dialog box for adding vendor details. 
     * @param event
     */
    @UiHandler("addVendorPrices")
    void addVendorPrices(ClickEvent event) {
        VendorPricesDialog pricesDialog = new VendorPricesDialog();
        pricesDialog.updateButton.setText("Add");
        pricesDialog.setVendorDetailsUpdateListener(new VendorPricesDialog.VendorPriceUpdateListener() {
            @Override
            public boolean onUpdate(String itemKey, double mop, double dp, double tp, long vendorId) {
                if(!vendorExists(vendorId)) {
                    Window.alert("Vendor already exists");
                    return false;
                }   
                if(!validateVendorDetails(itemKey, mop, dp, tp)) {
                    return false;
                }
                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_VENDORID, "128px");
                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_VENDOR_DESC, "128px");
                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_ITEM_KEY, "250px");
                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_MOP, "128px");
                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_DP, "128px");
                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_TP, "128px");
                
                int row = vendorTable.getRowCount();
                vendorTable.setText(row, TABLE_INDEX_VENDORID, vendorId+"");
                vendorTable.setText(row, TABLE_INDEX_VENDOR_DESC, Utils.getVendorDesc(vendorId));
                vendorTable.setText(row, TABLE_INDEX_ITEM_KEY, itemKey);
                vendorTable.setText(row, TABLE_INDEX_MOP, mop + "");
                vendorTable.setText(row, TABLE_INDEX_DP, dp + "");
                vendorTable.setText(row, TABLE_INDEX_TP, tp + "");
                Button removeButton = new Button("Remove");
                vendorTable.setWidget(row, TABLE_INDEX_TP + 1, removeButton);
                removeButton.addClickHandler(new ClickHandler() {
                    @Override
                    public void onClick(ClickEvent event) {
                        Cell cell = vendorTable.getCellForEvent(event);
                        int row = cell.getRowIndex();
                        vendorTable.removeRow(row);
                    }
                });
                return true;
            }
        });
        pricesDialog.center();
        pricesDialog.show();
    }
    
    /**
     * 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 details (Item key, MOP, DealerPrice, TransferPrice)
     */
    private boolean validateVendorDetails(String key, double mop, double dp, double tp) {
        double mrpValue;
        if(key == null || key.isEmpty()) {
            Window.alert("Item key cannot be empty");
            return false;
        }
        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;
    }
}