Rev 13435 | 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 EbayPsOrderCreatorController extends ActionSupport implements ServletRequestAware {private static Logger logger = LoggerFactory.getLogger(EbayPsOrderCreatorController.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 QUANTITY_INDEX = 2;private static final int AMOUNT_INDEX = 3;private static final int TRANSACTION_DATE_INDEX = 4;private static final int SHIP_DATE_INDEX = 5;private static final int PAISAPAY_ID_INDEX = 7;private static final int COURIER_INDEX = 8;private static final int CUST_MOBILE_INDEX = 13;private static final int EBAY_LISTINGID_INDEX = 14;private static final int AWB_INDEX = 15;private static final int WAREHOUSE_ID_INDEX = 17;private static final int OVERRIDE_BILLING_PRICE_INDEX = 18;private static final int EBAY_GATEWAY_ID = 16;private static final String bluedart = "BLUE DART";private static final String aramex = "ARAMEX";private static final String dtdc = "DTDC";private static final String fedex = "FEDEX";private static final String dotzot = "DOTZOT";private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");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);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(EBAY_SOURCE_ID);} catch (Exception e) {logger.error("Unable to establish connection to the transaction service", e);setErrorMsg(getErrorMsg() + "Error in Order Service while getting Ebay Source Detail");addActionError("Error in 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 Ebay ");addActionError("Unable to get Default Email for Ebay ");}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 Ebay ");List<Order> orders = new ArrayList<Order>();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);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();}long quantity = new Double(row.getCell(QUANTITY_INDEX).getNumericCellValue()).longValue();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 create order for sales Rec Number " + row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue(), tex);setErrorMsg(getErrorMsg() + "<br>Unable to create lineitem using catalog info for RowId " + rowId);addActionError("Unable to create order for sales Rec Number " + row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue());continue;}Order t_order = new Order();t_order.setCustomer_id(user.getUserId());t_order.setCustomer_email(sourceDetail.getEmail());t_order.setCustomer_name("Ebay");try {row.getCell(CUST_MOBILE_INDEX).setCellType(Cell.CELL_TYPE_STRING);t_order.setCustomer_mobilenumber(row.getCell(CUST_MOBILE_INDEX).getStringCellValue());} catch (Exception e) {addActionError("Error in reading mobile Number for rowNumber " + row.getRowNum());setErrorMsg(getErrorMsg() + "<br>Unable to create lineitem using catalog info for RowId " + rowId);logger.error("Error in reading mobile Number for rowNumber " + row.getRowNum());}//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("Payment Pending");t_order.setCreated_timestamp(new Date().getTime());t_order.setCod(false);try {//Date shippingDate = interchangeDateAndMonth(row.getCell(SHIP_DATE_INDEX).getDateCellValue());Date shippingDate = row.getCell(SHIP_DATE_INDEX).getDateCellValue();t_order.setPromised_shipping_time(shippingDate.getTime());t_order.setExpected_shipping_time(shippingDate.getTime());/*t_order.setPromised_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());t_order.setExpected_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());*/Calendar time = Calendar.getInstance();time.setTimeInMillis(t_order.getExpected_shipping_time());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 Time for row number " + rowId);logger.error("Error in updating Shipping Time for row number " + rowId,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, -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.equals(bluedart)) {t_order.setLogistics_provider_id(8);} else if(provider.equals(aramex)) {t_order.setLogistics_provider_id(9);} else if(provider.equals(dtdc)) {t_order.setLogistics_provider_id(10);} else if(provider.equals(fedex)) {t_order.setLogistics_provider_id(11);} else if(provider.equals(dotzot)) {t_order.setLogistics_provider_id(15);} else {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(EBAY_SOURCE_ID);orders.add(t_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;}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);logger.info("Successfully created transaction: " + transactionId + " for amount: " + totalPrice);Transaction transaction = transaction_client.getTransaction(Long.parseLong(transactionId));Order order = transaction.getOrders().get(0);EbayOrder ebayOrder = new EbayOrder();ebayOrder.setEbayListingId(ebayItem.getEbayListingId());ebayOrder.setSalesRecordNumber(new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue());try {//Date ebayTransactionDate = interchangeDateAndMonth(row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue());Date ebayTransactionDate = row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue();ebayOrder.setEbayTxnDate(ebayTransactionDate.getTime());} catch (Exception e) {logger.error("Error in setting transaction date for Ebay Order with OrderId : " + order.getId());}ebayOrder.setOrderId(order.getId());ebayOrder.setPaisaPayId(paisaPayId);ebayOrder.setListingName(ebayItem.getListingName());ebayOrder.setSubsidyAmount(ebayItem.getSubsidy()*quantity);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);inventoryClient.reserveItemInWarehouse(ebayItem.getItemId(), fulfillmentWarehouse.getId(), 1,order.getId(), order.getCreated_timestamp(), order.getPromised_shipping_time(), order.getLineitems().get(0).getQuantity());} 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, 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;}}