Rev 10870 | 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.catalog.SnapdealItem;import in.shop2020.model.v1.inventory.InventoryService;import in.shop2020.model.v1.inventory.InventoryServiceException;import in.shop2020.model.v1.inventory.InventoryType;import in.shop2020.model.v1.inventory.VendorItemPricing;import in.shop2020.model.v1.inventory.Warehouse;import in.shop2020.model.v1.inventory.WarehouseType;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 = 7;private static final int CITY_INDEX = 8;private static final int STATE_INDEX = 9;private static final int PINCODE_INDEX = 10;private static final int AMOUNT_INDEX = 11;private static final int WAREHOUSE_ID_INDEX = 13;private static final int OVERRIDE_BILLING_PRICE_INDEX = 14;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 CHHOTU = "CHHOTU";private static final String LAST_MILE = "LAST_MILE";private static final String ECOM = "Ecom Express";private static final String EWINGS = "EWINGS";private static final String DTDC = "DTDC";private static final String WAREOLOG = "Wareolog";private static final String MIRAKLE = "MIRAKLE";private static final String RAJIV_TRANSPORT = "RAJIV_TRANSPORT";private static final String BLUEDART_HIGH_VALUE = "BLUEDART_HIGH_VALUE";private static final String BLUEDART_SURFACE = "BLUEDART_SURFACE";private static final String BLUEDART_APEX = "BLUEDART APEX";private static final String ARAMEX = "ARAMEX";private static final String GATI = "GATI";private static final String INDIA_POST = "INDIA_POST";private static final String FEDEX = "FEDEX";private static final String IOT = "IOT";private static final String RED_EXP = "Red Express";private static final String GHARPAY = "GHARPAY";private static final String QUANTIUM = "Quantium Solutions";private static final String GATI_AIR = "GATI AIR";private static final String VDELIVER = "VDELIVER";private static final String OVERNITE_EXP = "Overnite Express";private static final String BIBHA_CARGO = "BIBHA CARGO AND COURIER PVT LTD";private File orderDataFile;private String orderDataFileName;private String transactionId;private String errorMsg = "";private Long rowId = 0L;private long paymentId;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 serviceWorkbook 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);SnapdealItem snapdealItem;in.shop2020.model.v1.catalog.CatalogService.Client catalogClient;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);String sku = row.getCell(ITEMID_INDEX).getStringCellValue();Long itemId;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 {catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();snapdealItem = catalogClient.getSnapdealItembySkuAtSnapdeal(sku);itemId = snapdealItem.getItem_id();if(itemId == 0){logger.error("Mapping not present for " + rowId + " "+ sku);logger.error("Unable to create order for RowId " + rowId);continue;}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_mobilenumber("+91-9999999999");t_order.setCustomer_address1("");t_order.setCustomer_address2("");t_order.setCustomer_city(row.getCell(CITY_INDEX).getStringCellValue());row.getCell(STATE_INDEX).setCellType(Cell.CELL_TYPE_STRING);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);if(time.get(Calendar.DAY_OF_WEEK)!=1){t_order.setPromised_shipping_time(time.getTimeInMillis());t_order.setExpected_shipping_time(time.getTimeInMillis());}else{t_order.setPromised_shipping_time(time.getTimeInMillis()+24*60*60*1000);t_order.setExpected_shipping_time(time.getTimeInMillis()+24*60*60*1000);}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());long billingWarehouseId = 0;if(fulfillmentWarehouse.getBillingWarehouseId()== 0) {inventoryClient = new InventoryClient().getClient();List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, fulfillmentWarehouse.getVendor().getId(), 0, 0);for(Warehouse warehouse : warehouses) {if(warehouse.getBillingWarehouseId()!=0) {billingWarehouseId = warehouse.getBillingWarehouseId();break;}}} else {billingWarehouseId = fulfillmentWarehouse.getBillingWarehouseId();}t_order.setWarehouse_id(billingWarehouseId);//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.equalsIgnoreCase(FIRSTFLIGHT)) {t_order.setLogistics_provider_id(12);} else if(provider.equalsIgnoreCase(DELHIVERY)) {t_order.setLogistics_provider_id(13);} else if(provider.equalsIgnoreCase(BLUEDART)) {t_order.setLogistics_provider_id(14);} else if(provider.equalsIgnoreCase(ECOM)) {t_order.setLogistics_provider_id(18);}else if(provider.equalsIgnoreCase(EWINGS)){t_order.setLogistics_provider_id(19);}else if(provider.equalsIgnoreCase(DTDC)){t_order.setLogistics_provider_id(20);}else if(provider.equalsIgnoreCase(WAREOLOG)){t_order.setLogistics_provider_id(21);}else if(provider.equalsIgnoreCase(MIRAKLE)){t_order.setLogistics_provider_id(22);}else if(provider.equalsIgnoreCase(RAJIV_TRANSPORT)){t_order.setLogistics_provider_id(23);}else if(provider.equalsIgnoreCase(BLUEDART_HIGH_VALUE)){t_order.setLogistics_provider_id(24);}else if(provider.equalsIgnoreCase(BLUEDART_SURFACE)){t_order.setLogistics_provider_id(25);}else if(provider.equalsIgnoreCase(BLUEDART_APEX)){t_order.setLogistics_provider_id(26);}else if(provider.equalsIgnoreCase(ARAMEX)){t_order.setLogistics_provider_id(27);}else if(provider.equalsIgnoreCase(GATI)){t_order.setLogistics_provider_id(28);}else if(provider.equalsIgnoreCase(INDIA_POST)){t_order.setLogistics_provider_id(29);}else if(provider.equalsIgnoreCase(FEDEX)){t_order.setLogistics_provider_id(30);}else if(provider.equalsIgnoreCase(IOT)){t_order.setLogistics_provider_id(31);}else if(provider.equalsIgnoreCase(RED_EXP)){t_order.setLogistics_provider_id(32);}else if(provider.equalsIgnoreCase(VDELIVER)){t_order.setLogistics_provider_id(33);}else if(provider.equalsIgnoreCase(GHARPAY)){t_order.setLogistics_provider_id(34);}else if(provider.equalsIgnoreCase(QUANTIUM)){t_order.setLogistics_provider_id(35);}else if(provider.equalsIgnoreCase(GATI_AIR)){t_order.setLogistics_provider_id(36);}else if(provider.equalsIgnoreCase(OVERNITE_EXP)){t_order.setLogistics_provider_id(37);}else if(provider.equalsIgnoreCase(BIBHA_CARGO)){t_order.setLogistics_provider_id(38);}else {t_order.setLogistics_provider_id(44);}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 {row.getCell(SUBORDER_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);long subOrderId = Long.parseLong(row.getCell(SUBORDER_ID_INDEX).getStringCellValue());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(String.valueOf(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));paymentId = 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(String.valueOf(subOrderId));snapdealOrder.setReferenceCode(referenceCode);snapdealOrder.setProductName(productName);snapdealOrder.setSnapdealTxnDate(snapdealTxnDate.getTime());snapdealOrder.setListingPrice(listingPrice);snapdealOrder.setMaxNlc(snapdealItem.getMaxNlc());transaction_client.createSnapdealOrder(snapdealOrder);new PaymentClient().getClient().updatePaymentDetails(paymentId, null, null, null, null, null, null, Long.toString(subOrderId), null, PaymentStatus.SUCCESS, null, null);} 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 long createPayment(User user, String subOrderId, double amount) throws NumberFormatException, PaymentException, TException {in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();return client.createPayment(user.getUserId(), amount, SNAPDEAL_GATEWAY_ID, Long.valueOf(transactionId), false);}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;}@Overridepublic 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;}}