Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.support.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import in.shop2020.logistics.DeliveryType;
import in.shop2020.logistics.LogisticsInfo;
import in.shop2020.logistics.LogisticsService;
import in.shop2020.logistics.PickUpType;
import in.shop2020.model.v1.catalog.CatalogService;
import in.shop2020.model.v1.catalog.CatalogServiceException;
import in.shop2020.model.v1.catalog.EbayItem;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.inventory.InventoryService;
import in.shop2020.model.v1.inventory.InventoryServiceException;
import in.shop2020.model.v1.inventory.VendorItemPricing;
import in.shop2020.model.v1.inventory.Warehouse;
import in.shop2020.model.v1.order.EbayOrder;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.OrderSource;
import in.shop2020.model.v1.order.OrderStatus;
import in.shop2020.model.v1.order.OrderType;
import in.shop2020.model.v1.order.SnapdealOrder;
import in.shop2020.model.v1.order.SourceDetail;
import in.shop2020.model.v1.order.Transaction;
import in.shop2020.model.v1.order.TransactionStatus;
import in.shop2020.model.v1.order.TransactionService.Client;
import in.shop2020.model.v1.user.Address;
import in.shop2020.model.v1.user.User;
import in.shop2020.payments.Attribute;
import in.shop2020.payments.PaymentException;
import in.shop2020.payments.PaymentStatus;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.InventoryClient;
import in.shop2020.thrift.clients.LogisticsClient;
import in.shop2020.thrift.clients.PaymentClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.support.utils.ReportsUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
@InterceptorRefs({
    @InterceptorRef("defaultStack"),
    @InterceptorRef("login")
})
@Results({
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
})
public class SnapdealOrderCreatorController extends ActionSupport implements ServletRequestAware {
        
        private static Logger logger = LoggerFactory.getLogger(SnapdealOrderCreatorController.class);
        
        private HttpServletRequest request;
    private HttpSession session;
    
    private static final int SNAPDEAL_SOURCE_ID = 7;
    
    private static final int COURIER_INDEX = 0;
    private static final int PRODUCT_NAME_INDEX = 1;
    private static final int REFERENCE_CODE_INDEX = 2;
    private static final int SUBORDER_ID_INDEX = 3;
    private static final int ITEMID_INDEX = 4;
    private static final int AWB_INDEX = 5;
    private static final int TRANSACTION_DATE_INDEX = 6;
    private static final int BUYER_NAME_INDEX = 8;
    private static final int CITY_INDEX = 9;
    private static final int STATE_INDEX = 10;
    private static final int PINCODE_INDEX = 11;
    private static final int AMOUNT_INDEX = 12;
    private static final int WAREHOUSE_ID_INDEX = 14;
    private static final int OVERRIDE_BILLING_PRICE_INDEX = 15;
    
    
    private static final int SNAPDEAL_GATEWAY_ID = 18;
    
    private static final String FIRSTFLIGHT = "First Flight";
    private static final String DELHIVERY = "Delhivery";
    private static final String BLUEDART = "Bluedart";
    private static final String ECOM = "Ecom Express";
    
    private File orderDataFile;
    private String orderDataFileName;
    private String transactionId;
    private String errorMsg = "";
    private Long rowId = 0L;
        
    public String create() throws TException {
        File fileToCreate = null;
        orderDataFileName = "OrderSheet_Snapdeal_"+(new Date().toString());
        try {
            fileToCreate = new File("/tmp/", this.orderDataFileName);
            FileUtils.copyFile(this.orderDataFile, fileToCreate);
        } catch (Exception e) {
           logger.error("Error while writing order data file to the local file system for Snapdeal", e);
           addActionError("Error while writing order data file to the local file system");
        }
        
        
        if(checkForErrors())
            return "authsuccess";
        
        //Parse the file and submit the data for update to the transaction service
        Workbook wb = null;
        try {
            wb = new HSSFWorkbook(new FileInputStream(fileToCreate));
        } catch (Exception e) {
            logger.error("Unable to open the File for Order Creation for Snapdeal ", e);
            setErrorMsg(getErrorMsg() + "Error in opening File for Order creation");
            addActionError("Unable to open the File for Order creation");
        }
        if(checkForErrors())
            return "authsuccess";
        
        SourceDetail sourceDetail = null;
        User user = null;
        TransactionClient tsc = null;
        try {
            tsc = new TransactionClient();
                        sourceDetail = tsc.getClient().getSourceDetail(SNAPDEAL_SOURCE_ID);
        } catch (Exception e) {
            logger.error("Unable to establish connection to the transaction service while getting Snapdeal Source Detail", e);
            setErrorMsg(getErrorMsg() + "Error in Order Service while getting Snapdeal Source Detail");
            addActionError("Error in connecting to Order Service");
                }
        
        if(checkForErrors())
            return "authsuccess";
        
            try {   
                in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
                user = userClient.getUserByEmail(sourceDetail.getEmail());
            } catch (Exception e) {
                logger.error("Unable to establish connection to the User service", e);
                setErrorMsg(getErrorMsg() + "Unable to get Default Email for Snapdeal ");
                addActionError("Unable to get Default Email for Snapdeal ");
                }

        if(checkForErrors())
            return "authsuccess";
        
        Sheet sheet = wb.getSheetAt(0);
        Row firstRow = sheet.getRow(0);
        for (Row row : sheet) {
                long orderCountForRow = 0;
                rowId++;
            if(row.equals(firstRow))
                continue;
                try {
                    Transaction txn = new Transaction();
                    txn.setShoppingCartid(user.getActiveCartId());
                    txn.setCustomer_id(user.getUserId());
                    txn.setCreatedOn(new Date().getTime());
                    txn.setTransactionStatus(TransactionStatus.INIT);
                    txn.setStatusDescription("Order for Snapdeal ");
                    
                    List<Order> orders = new ArrayList<Order>();
                    
                    row.getCell(ITEMID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
                    Long itemId = Long.parseLong(row.getCell(ITEMID_INDEX).getStringCellValue());
                        double listingPrice = 0;
                        double overriddenPrice = 0;
                        double totalPrice = 0;
                        Cell overriddenPriceCell = row.getCell(OVERRIDE_BILLING_PRICE_INDEX);
                        if(overriddenPriceCell  != null && overriddenPriceCell .getCellType() != Cell.CELL_TYPE_BLANK) {
                                overriddenPrice = row.getCell(OVERRIDE_BILLING_PRICE_INDEX).getNumericCellValue();
                        }
                        
                        totalPrice = row.getCell(AMOUNT_INDEX).getNumericCellValue();
                        listingPrice = totalPrice;
                        if(overriddenPrice>=1) {
                                totalPrice = overriddenPrice;
                        }
                        LineItem lineItem = null;
                        try {
                                lineItem = createLineItem(itemId, totalPrice);
                                Double subOrderId = row.getCell(SUBORDER_ID_INDEX).getNumericCellValue();
                        String refCode = row.getCell(REFERENCE_CODE_INDEX).getStringCellValue();
                                lineItem.setExtra_info("SubOrderId = " + subOrderId + " ReferenceCode = " + refCode);
                        } catch (Exception tex) {
                                logger.error("Unable to create order for RowId " + rowId, tex);
                                setErrorMsg(getErrorMsg() + "<br>Unable to create lineitem using catalog info for RowId " + rowId);
                        continue;
                        }
                    Order t_order = new Order();
                    t_order.setCustomer_id(user.getUserId());
                    t_order.setCustomer_email(sourceDetail.getEmail());
                    row.getCell(BUYER_NAME_INDEX).setCellType(Cell.CELL_TYPE_STRING);
                        t_order.setCustomer_name(row.getCell(BUYER_NAME_INDEX).getStringCellValue());
                        t_order.setCustomer_address1("");
                        t_order.setCustomer_address2("");
                        t_order.setCustomer_city(row.getCell(CITY_INDEX).getStringCellValue());
                        t_order.setCustomer_state(row.getCell(STATE_INDEX).getStringCellValue());
                        row.getCell(PINCODE_INDEX).setCellType(Cell.CELL_TYPE_STRING);
                        t_order.setCustomer_pincode(row.getCell(PINCODE_INDEX).getStringCellValue());
                    t_order.setTotal_amount(lineItem.getTotal_price());            
                    t_order.setTotal_weight(lineItem.getTotal_weight());
                    t_order.setLineitems(Collections.singletonList(lineItem));            
                    t_order.setStatus(OrderStatus.PAYMENT_PENDING);
                    t_order.setStatusDescription("In Process");
                    t_order.setCreated_timestamp(new Date().getTime());
                    t_order.setOrderType(OrderType.B2C);
                    t_order.setCod(false);
                    try {
                        Calendar time = Calendar.getInstance();
                        time.add(Calendar.DAY_OF_MONTH, 1);
                        t_order.setPromised_shipping_time(time.getTimeInMillis());
                        t_order.setExpected_shipping_time(time.getTimeInMillis());
                        time.add(Calendar.DAY_OF_MONTH, 3);
                        t_order.setPromised_delivery_time(time.getTimeInMillis());
                        t_order.setExpected_delivery_time(time.getTimeInMillis());
                    } catch(Exception e) {
                        addActionError("Error in updating Shipping or Delivery Time for row number " + rowId);
                        logger.error("Error in updating Shipping or Delivery Time for row number " + rowId,e);
                        continue;
                    }
                    
                    InventoryService.Client inventoryClient = null;
                    Warehouse fulfillmentWarehouse= null; 
                    try {
                        inventoryClient = new InventoryClient().getClient();
                        Cell warehouseCell = row.getCell(WAREHOUSE_ID_INDEX);
                        if(warehouseCell != null && warehouseCell.getCellType() != Cell.CELL_TYPE_BLANK) {
                                fulfillmentWarehouse = inventoryClient.getWarehouse(new Double(row.getCell(WAREHOUSE_ID_INDEX).getNumericCellValue()).longValue());
                        } else {
                                List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(itemId, 1);
                                fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
                        }
                        t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
                                t_order.setWarehouse_id(fulfillmentWarehouse.getBillingWarehouseId());
                                
                                VendorItemPricing vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), fulfillmentWarehouse.getVendor().getId());
                                t_order.getLineitems().get(0).setTransfer_price(vendorItemPricing.getTransferPrice());
                                t_order.getLineitems().get(0).setNlc(vendorItemPricing.getNlc());
                                } catch (InventoryServiceException e) {
                                        addActionError("Error in updating WarehouseId for row number " + rowId);
                                        setErrorMsg(getErrorMsg() + "<br>Error in updating WarehouseId for row number  " + rowId);
                        logger.error("Error in updating WarehouseId for row number " + rowId,e);
                        continue;
                                }
                    
                                String provider = row.getCell(COURIER_INDEX).getStringCellValue();
                                if(provider.equals(FIRSTFLIGHT)) {
                                        t_order.setLogistics_provider_id(12);
                                } else if(provider.equals(DELHIVERY)) {
                                        t_order.setLogistics_provider_id(13);
                                } else if(provider.equals(BLUEDART)) {
                                        t_order.setLogistics_provider_id(14);
                                } else if(provider.equals(ECOM)) {
                    t_order.setLogistics_provider_id(18);
                } else {
                                        addActionError("Unknown logistics provider found for row number " + rowId);
                                        setErrorMsg(getErrorMsg() + "<br>Unknown logistics provider found for row number " + rowId);
                        logger.error("Unknown logistics provider found for row number " + rowId);
                        continue;
                                }
                                
                                row.getCell(AWB_INDEX).setCellType(Cell.CELL_TYPE_STRING);
                                t_order.setAirwaybill_no(row.getCell(AWB_INDEX).getStringCellValue());
                                t_order.setTracking_id(row.getCell(AWB_INDEX).getStringCellValue());
                    t_order.setTotal_amount(totalPrice);
                    t_order.setOrderType(OrderType.B2C);
                    t_order.setSource(SNAPDEAL_SOURCE_ID);
                    t_order.setOrderType(OrderType.B2C);
                    orders.add(t_order);
                    orderCountForRow++;
                    
                    txn.setOrders(orders);
                    Client transaction_client = new TransactionClient().getClient();
                    try {
                        long subOrderId = new Double(row.getCell(SUBORDER_ID_INDEX).getNumericCellValue()).longValue();
                        String referenceCode = row.getCell(REFERENCE_CODE_INDEX).getStringCellValue();
                        String productName = row.getCell(PRODUCT_NAME_INDEX).getStringCellValue();
                        Date snapdealTxnDate = row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue();
                        
                        if(transaction_client.snapdealOrderExists(subOrderId, referenceCode)) {
                                setErrorMsg(getErrorMsg() + "<br>Duplicate order for subOrderId " + subOrderId + " for row number  " + rowId);
                                logger.error("Duplicate order for subOrderId " + subOrderId + " for row number  " + rowId);
                                continue;
                        }
                        
                        transactionId =  String.valueOf(transaction_client.createTransaction(txn));
                        createPayment(user, (new Long(subOrderId)).toString(), totalPrice);
                        
                        logger.info("Successfully created transaction: " + transactionId + " for amount: " + totalPrice);
                        
                        Transaction transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
                        Order order = transaction.getOrders().get(0);
                        
                        inventoryClient.reserveItemInWarehouse(itemId, fulfillmentWarehouse.getId(), 1, 
                                        order.getId(), order.getCreated_timestamp(), order.getPromised_shipping_time(), order.getLineitems().get(0).getQuantity());
                        
                        
                        SnapdealOrder snapdealOrder = new SnapdealOrder();
                        snapdealOrder.setOrderId(order.getId());
                        snapdealOrder.setSubOrderId(subOrderId);
                        snapdealOrder.setReferenceCode(referenceCode);
                        snapdealOrder.setProductName(productName);
                        snapdealOrder.setSnapdealTxnDate(snapdealTxnDate.getTime());
                        snapdealOrder.setListingPrice(listingPrice);
                        transaction_client.createSnapdealOrder(snapdealOrder);
                        
                        
                    } catch (Exception e) {
                        logger.error("Error while creating order for rowId " + rowId, e);
                        addActionError("Error while creating order for rowId " + rowId);
                        setErrorMsg(getErrorMsg() + "<br>Error while creating order for row number " + rowId);
                        continue;
                        }
                } catch (Exception e) {
                        logger.error("Error while creating order for row number " + rowId, e);
                        setErrorMsg(getErrorMsg() + "<br>Error while creating order for row number " + rowId);
                        continue;
                }
        }
        
        checkForErrors();
        return "authsuccess";
    }
    
    private Date interchangeDateAndMonth(Date date) {
                Date updatedDate = new Date(date.getTime());
                updatedDate.setDate(date.getMonth() + 1);
                updatedDate.setMonth(date.getDate() - 1);
                return updatedDate;
        }

        private LineItem createLineItem(long itemId, double amount) throws CatalogServiceException, TException {
        LineItem lineItem = new LineItem();
        CatalogService.Client catalogClient = new CatalogClient().getClient();
        Item item = catalogClient.getItem(itemId);
        
        lineItem.setProductGroup(item.getProductGroup());
        lineItem.setBrand(item.getBrand());
        lineItem.setModel_number(item.getModelNumber());
        lineItem.setModel_name(item.getModelName());
        lineItem.setExtra_info(item.getFeatureDescription());
        lineItem.setQuantity(1);
        lineItem.setItem_id(item.getId());
        lineItem.setUnit_weight(item.getWeight());
        lineItem.setTotal_weight(item.getWeight());
        lineItem.setUnit_price(amount);
        lineItem.setTotal_price(amount);

        if (item.getColor() == null || "NA".equals(item.getColor())) {
            lineItem.setColor("");
        } else {
            lineItem.setColor(item.getColor());
        }
        return lineItem;
        }
    
    private void createPayment(User user, String subOrderId, double amount) throws NumberFormatException, PaymentException, TException {
        in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
        long paymentId = client.createPayment(user.getUserId(), amount, SNAPDEAL_GATEWAY_ID, Long.valueOf(transactionId), false);
        client.updatePaymentDetails(paymentId, null, null, null, null, null, null, subOrderId, null, PaymentStatus.AUTHORIZED, null, null);
    }   
    
        public String index() {
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), "/ebay-dashboard"))
            return "authfail";
        checkForErrors();
        return "authsuccess";
    }
        
        private boolean checkForErrors(){
        Collection<String> actionErrors = getActionErrors();
        if(actionErrors != null && !actionErrors.isEmpty()){
            for (String str : actionErrors) {
                errorMsg += "<BR/>" + str;
            }
            return true;
        }
        return false;
    }
        
        @Override
        public void setServletRequest(HttpServletRequest request) {
                this.request = request;
        this.session = request.getSession();
        }

        public String getErrorMsg() {
                return errorMsg;
        }

        public void setErrorMsg(String errorMsg) {
                this.errorMsg = errorMsg;
        }

        public Long getRowId() {
                return rowId;
        }

        public void setRowId(Long rowId) {
                this.rowId = rowId;
        }

        public File getOrderDataFile() {
                return orderDataFile;
        }

        public void setOrderDataFile(File orderDataFile) {
                this.orderDataFile = orderDataFile;
        }

}