Rev 9142 | Rev 20781 | 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.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.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.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 EbayNormalOrderCreatorController extends ActionSupport implements ServletRequestAware {private static Logger logger = LoggerFactory.getLogger(EbayNormalOrderCreatorController.class);private HttpServletRequest request;private HttpSession session;private static final int EBAY_SOURCE_ID = 6;private static final int SALES_RECORD_NUM_INDEX = 0;private static final int BUYER_NAME_INDEX = 2;private static final int CUST_MOBILE_INDEX = 3;private static final int EMAIL_INDEX = 4;private static final int ADDR1_INDEX = 5;private static final int ADDR2_INDEX = 6;private static final int CITY_INDEX = 7;private static final int STATE_INDEX = 8;private static final int PINCODE_INDEX = 9;private static final int EBAY_LISTINGID_INDEX = 11;private static final int QUANTITY_INDEX = 14;private static final int AMOUNT_INDEX = 15;private static final int TRANSACTION_DATE_INDEX = 21;private static final int PAISAPAY_ID_INDEX = 28;private static final int TRANSACTION_ID_INDEX = 31;private static final int SHIP_DATE_INDEX = 24;private static final int WAREHOUSE_ID_INDEX = 34;private static final int OVERRIDE_BILLING_PRICE_INDEX = 35;private static final int EBAY_GATEWAY_ID = 16;private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");private SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");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_"+EBAY_SOURCE_ID+"_"+(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 Ebay", 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 Ebay ", e);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(EBAY_SOURCE_ID);} catch (Exception e) {logger.error("Unable to establish connection to the transaction service", e);addActionError("Unable to establish connection to the transaction service");}if(checkForErrors())return "authsuccess";in.shop2020.model.v1.user.UserContextService.Client userClient = null;try {userClient = new UserClient().getClient();} catch (Exception e) {logger.error("Unable to establish connection to the User service", e);addActionError("Unable to establish connection to the User service");}if(checkForErrors())return "authsuccess";Sheet sheet = wb.getSheetAt(0);Row firstRow = sheet.getRow(0);logger.info("Last row number is:" + sheet.getLastRowNum());for (Row row : sheet) {rowId++;long orderCountForRow = 0;if(row.equals(firstRow))continue;try {//TODO Get this user from a different methodif (userClient.userExists(row.getCell(EMAIL_INDEX).getStringCellValue())) {user = userClient.getUserByEmail(row.getCell(EMAIL_INDEX).getStringCellValue());} else {user = new User();user.setName(row.getCell(BUYER_NAME_INDEX).getStringCellValue());user.setEmail(row.getCell(EMAIL_INDEX).getStringCellValue());user.setSourceId(EBAY_SOURCE_ID);//TODO set mobileNumber for customer//TODO set password for user;user.setIsAnonymous(false);user = userClient.createUser(user);}} catch(Exception e) {logger.error("Unable to establish connection to the User service for row number " + (rowId + 1), e);addActionError("Unable to establish connection to the User service for row number " + (rowId + 1));return "authsuccess";}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 Ebay ");List<Order> orders = new ArrayList<Order>();double listingPrice = 0;double overriddenPrice = 0;double totalPrice = 0;row.getCell(EBAY_LISTINGID_INDEX).setCellType(Cell.CELL_TYPE_STRING);String ebayListingId = row.getCell(EBAY_LISTINGID_INDEX).getStringCellValue();CatalogService.Client catalogClient = new CatalogClient().getClient();EbayItem ebayItem = catalogClient.getEbayItem(ebayListingId);long quantity = new Double(row.getCell(QUANTITY_INDEX).getNumericCellValue()).longValue();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();}String totalPriceString = row.getCell(AMOUNT_INDEX).getStringCellValue();if(overriddenPrice>=1) {totalPrice = overriddenPrice*quantity;listingPrice = (Double.parseDouble(totalPriceString.substring(3).replace(",","")))/quantity;} else {totalPrice = Double.parseDouble(totalPriceString.substring(3).replace(",",""));listingPrice = totalPrice/quantity;}LineItem lineItem = null;try {lineItem = createLineItem(ebayItem.getItemId(), quantity, totalPrice);Double salesRecordNumber = row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue();row.getCell(PAISAPAY_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);String paisaPayId = row.getCell(PAISAPAY_ID_INDEX).getStringCellValue();lineItem.setExtra_info("PaisaPayId = " + paisaPayId + " SalesRecordNumber = " + salesRecordNumber);} catch (Exception tex) {logger.error("Unable to establish connection to the Catalog service", tex);addActionError("Unable to establish connection to the Catalog service");return "authsuccess";}Order order = new Order();order.setCustomer_id(user.getUserId());order.setCustomer_email(user.getEmail());order.setCustomer_name(user.getName());try {order.setCustomer_mobilenumber(new Double(row.getCell(CUST_MOBILE_INDEX).getNumericCellValue()).toString());} catch (Exception e) {addActionError("Error in reading mobile Number for rowNumber " + row.getRowNum());logger.error("Error in reading mobile Number for rowNumber " + row.getRowNum());}order.setCustomer_address1(row.getCell(ADDR1_INDEX).getStringCellValue());Cell address2Cell = row.getCell(ADDR2_INDEX);if(address2Cell != null && address2Cell.getCellType() != Cell.CELL_TYPE_BLANK) {order.setCustomer_address2(row.getCell(ADDR2_INDEX).getStringCellValue());}// order.setCustomer_address2(row.getCell(ADDR2_INDEX).getStringCellValue());order.setCustomer_city(row.getCell(CITY_INDEX).getStringCellValue());order.setCustomer_state(row.getCell(STATE_INDEX).getStringCellValue());row.getCell(PINCODE_INDEX).setCellType(Cell.CELL_TYPE_STRING);order.setCustomer_pincode(row.getCell(PINCODE_INDEX).getStringCellValue());order.setTotal_amount(totalPrice);order.setTotal_weight(lineItem.getTotal_weight());order.setLineitems(Collections.singletonList(lineItem));order.setStatus(OrderStatus.SUBMITTED_FOR_PROCESSING);order.setStatusDescription("In Process");order.setCreated_timestamp(new Date().getTime());order.setCod(false);try {//Date shippingDate = interchangeDateAndMonth(row.getCell(SHIP_DATE_INDEX).getDateCellValue());Date shippingDate = row.getCell(SHIP_DATE_INDEX).getDateCellValue();order.setPromised_shipping_time(shippingDate.getTime());order.setExpected_shipping_time(shippingDate.getTime());//order.setPromised_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());//order.setExpected_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());Calendar time = Calendar.getInstance();time.setTimeInMillis(order.getExpected_shipping_time());time.add(Calendar.DAY_OF_MONTH, 3);order.setPromised_delivery_time(time.getTimeInMillis());order.setExpected_delivery_time(time.getTimeInMillis());} catch(Exception e) {addActionError("Error in updating Shipping Time for row number " + (rowId + 1));logger.error("Error in updating Shipping Time for row number " + (rowId + 1),e);continue;}//TODO Delivery timeInventoryService.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 if (ebayItem.getDefaultWarehouseId()!=0 ){fulfillmentWarehouse = inventoryClient.getWarehouse(ebayItem.getDefaultWarehouseId());} else {List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(ebayItem.getItemId(), 1);fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));}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();}order.setWarehouse_id(billingWarehouseId);//order.setWarehouse_id(fulfillmentWarehouse.getBillingWarehouseId());VendorItemPricing vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), fulfillmentWarehouse.getVendor().getId());order.getLineitems().get(0).setTransfer_price(vendorItemPricing.getTransferPrice());order.getLineitems().get(0).setNlc(vendorItemPricing.getNlc());} catch (InventoryServiceException e) {addActionError("Error in updating WarehouseId for row number " + rowId + 1);logger.error("Error in updating WarehouseId for row number " + (rowId + 1),e);continue;}order.setTotal_amount(totalPrice);order.setSource(EBAY_SOURCE_ID);orders.add(order);orderCountForRow++;txn.setOrders(orders);Client transaction_client = new TransactionClient().getClient();try {long salesRecNumber = new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue();if(transaction_client.ebayOrderExists(salesRecNumber, ebayItem.getEbayListingId())) {setErrorMsg(getErrorMsg() + "<br>Duplicate order for salesRecNumber " + salesRecNumber + " and listingId " + ebayItem.getEbayListingId() + " for row number " + rowId);logger.error("Duplicate order for salesRecNumber " + salesRecNumber + " and listingId " + ebayItem.getEbayListingId());continue;}try {LogisticsService.Client logisticsClient = new LogisticsClient().getClient();LogisticsInfo logisticsInfo = logisticsClient.getLogisticsInfo(order.getCustomer_pincode(),new Double(order.getLineitems().get(0).getItem_id()).longValue(), DeliveryType.PREPAID, PickUpType.COURIER);if(logisticsInfo.getProviderId()<7) {String airwaybillNo= logisticsClient.getEmptyAWB(logisticsInfo.getProviderId(), DeliveryType.PREPAID);order.setAirwaybill_no(airwaybillNo);order.setTracking_id(airwaybillNo);}order.setLogistics_provider_id(logisticsInfo.getProviderId());} catch (Exception e) {logger.error("Error while setting logistics provider for order for rowId " + rowId, e);addActionError("Error while setting logistics provider for order for rowId " + rowId);setErrorMsg(getErrorMsg() + "<br>Error while setting logistics provider for order for rowId " + rowId);continue;}transactionId = String.valueOf(transaction_client.createTransaction(txn));row.getCell(PAISAPAY_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);String paisaPayId = row.getCell(PAISAPAY_ID_INDEX).getStringCellValue();long paymentId = createPayment(user, paisaPayId, totalPrice);//TODO/*in.shop2020.model.v1.order.Attribute orderAttribute = new in.shop2020.model.v1.order.Attribute();orderAttribute.setName("tinNumber");orderAttribute.setValue(sourceDetail.getTinNumber());if(!sourceDetail.getTinNumber().equals("") && !(sourceDetail.getTinNumber() == null)) {transaction_client.setOrderAttributeForTransaction(Long.parseLong(transactionId), orderAttribute);}*///source//transaction_client.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.AUTHORIZED, "Ebay Order", 0L, OrderType.B2C, OrderSource.EBAY);//transaction_client.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS, "Ebay Order", 0L, OrderType.B2C, OrderSource.EBAY);logger.info("Successfully created transaction: " + transactionId + " for amount: " + totalPrice);Transaction transaction = transaction_client.getTransaction(Long.parseLong(transactionId));order = transaction.getOrders().get(0);inventoryClient.reserveItemInWarehouse(ebayItem.getItemId(), fulfillmentWarehouse.getId(), 1,order.getId(), order.getCreated_timestamp(), order.getPromised_shipping_time(), order.getLineitems().get(0).getQuantity());transaction_client.updateOrderForEbay(order);EbayOrder ebayOrder = new EbayOrder();ebayOrder.setEbayListingId(ebayItem.getEbayListingId());ebayOrder.setSalesRecordNumber(new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue());row.getCell(TRANSACTION_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);ebayOrder.setTransactionId(row.getCell(TRANSACTION_ID_INDEX).getStringCellValue());try {//Date ebayTransactionDate = interchangeDateAndMonth(row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue());Date ebayTransactionDate = row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue();ebayOrder.setEbayTxnDate(ebayTransactionDate.getTime());//ebayOrder.setEbayTxnDate(sdf2.parse(row.getCell(TRANSACTION_DATE_INDEX).getStringCellValue()).getTime());//ebayOrder.setEbayTxnDate(sdf.parse(row.getCell(TRANSACTION_DATE_INDEX).getStringCellValue()).getTime());} catch (Exception e) {logger.error("Error in setting transaction date for Ebay Order with OrderId : " + order.getId());}ebayOrder.setOrderId(transaction.getOrders().get(0).getId());ebayOrder.setPaisaPayId(paisaPayId);ebayOrder.setSubsidyAmount(ebayItem.getSubsidy()*quantity);ebayOrder.setListingName(ebayItem.getListingName());ebayOrder.setListingPrice(listingPrice);transaction_client.createEbayOrder(ebayOrder);in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();client.updatePaymentDetails(paymentId, null, null, null, null, null, null, paisaPayId, 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;}}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, long quantity, 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(quantity);lineItem.setItem_id(item.getId());lineItem.setUnit_weight(item.getWeight());lineItem.setTotal_weight(item.getWeight()*quantity);lineItem.setUnit_price(amount/quantity);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 paisaPayId, double amount) throws NumberFormatException, PaymentException, TException {in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();return client.createPayment(user.getUserId(), amount, EBAY_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;}}