Rev 7410 | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.support.controllers;import in.shop2020.model.v1.catalog.CatalogService;import in.shop2020.model.v1.catalog.CatalogServiceException;import in.shop2020.model.v1.catalog.Item;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.TransactionService.Client;import in.shop2020.model.v1.order.TransactionServiceException;import in.shop2020.model.v1.order.TransactionStatus;import in.shop2020.model.v1.user.Address;import in.shop2020.model.v1.user.User;import in.shop2020.model.v1.user.UserContextException;import in.shop2020.payments.Attribute;import in.shop2020.payments.PaymentException;import in.shop2020.payments.PaymentStatus;import in.shop2020.support.utils.ReportsUtils;import in.shop2020.thrift.clients.CatalogClient;import in.shop2020.thrift.clients.PaymentClient;import in.shop2020.thrift.clients.TransactionClient;import in.shop2020.thrift.clients.UserClient;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.Date;import java.util.List;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.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.apache.thrift.transport.TTransportException;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 SourceOrderCreationController extends ActionSupport implements ServletRequestAware {private static Logger logger = LoggerFactory.getLogger(SourceOrderCreationController.class);private static final int AMAZON_SOURCE_ID = 3;private static final int ITEM_ID_INDEX = 0;private static final int QUANTITY_INDEX = 1;private static final int BILLING_NAME_INDEX = 2;private static final int AMOUNT_PER_ORDER_INDEX = 3;private static final int CUST_EMAIL_INDEX = 4;private static final int CUST_MOBILE_INDEX = 5;private static final int CUST_ADDR1_INDEX = 6;private static final int CUST_ADDR2_INDEX = 7;private static final int CUST_CITY_INDEX = 8;private static final int CUST_STATE_INDEX = 9;private static final int CUST_PIN_INDEX = 10;private static final int AMAZON_ORDER_ID = 11;private static final String PAY_METHOD = "payMethod";private static final int RTGS_GATEWAY_ID = 6;private HttpServletRequest request;private HttpSession session;private File orderDataFile;private Long sourceId;private String orderDataFileName;private Long orderType;private Long pickUpType;private String transactionId;private Long amount;private String errorMsg = "";private Long rowId = 0L;public String index() {if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getServletPath()))return "authfail";checkForErrors();return "authsuccess";}public String create() throws TException {File fileToCreate = null;orderDataFileName = "OrderSheet_"+sourceId+"_"+(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", 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 SourceId " + sourceId, 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(sourceId);} 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";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);addActionError("Unable to establish connection to the User service");}if (user == null) {addActionError("Could not find default user for SourceId: " + sourceId);}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) {long orderCountForRow = 0;if(row.equals(firstRow))continue;rowId++;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 SourceId : " + sourceId);List<Order> orders = new ArrayList<Order>();// Extracting default addressAddress defaultAddress = null;for (Address address : user.getAddresses()) {if (address.getId() == user.getDefaultAddressId()) {defaultAddress = address;break;}}while(orderCountForRow <row.getCell(QUANTITY_INDEX).getNumericCellValue()) {LineItem lineItem = null;try {lineItem = createLineItem(row.getCell(ITEM_ID_INDEX).getNumericCellValue());lineItem.setTotal_price(row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue());lineItem.setUnit_price(row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue());} 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 t_order = new Order();t_order.setCustomer_id(user.getUserId());t_order.setCustomer_email(sourceDetail.getEmail());if(row.getCell(BILLING_NAME_INDEX)!=null && row.getCell(BILLING_NAME_INDEX).getStringCellValue()!=null &&!row.getCell(BILLING_NAME_INDEX).getStringCellValue().isEmpty()) {t_order.setCustomer_name(row.getCell(BILLING_NAME_INDEX).getStringCellValue());} else {t_order.setCustomer_name(sourceDetail.getName());}if(row.getCell(CUST_ADDR1_INDEX)!=null && row.getCell(CUST_CITY_INDEX)!=null && row.getCell(CUST_STATE_INDEX)!=null &&row.getCell(CUST_PIN_INDEX)!=null) {t_order.setCustomer_pincode(new Long(new Double(row.getCell(CUST_PIN_INDEX).getNumericCellValue()).longValue()).toString());t_order.setCustomer_address1(row.getCell(CUST_ADDR1_INDEX).getStringCellValue());if(row.getCell(CUST_ADDR2_INDEX)!=null) {t_order.setCustomer_address2(row.getCell(CUST_ADDR2_INDEX).getStringCellValue());}t_order.setCustomer_city(row.getCell(CUST_CITY_INDEX).getStringCellValue());t_order.setCustomer_state(row.getCell(CUST_STATE_INDEX).getStringCellValue());} else {if(pickUpType !=2 ) {addActionError("Customer address is mandatory if pickupType is not selected as Self-Pickup");return "authsuccess";}t_order.setCustomer_pincode(defaultAddress.getPin());t_order.setCustomer_address1(defaultAddress.getLine1());t_order.setCustomer_address2(defaultAddress.getLine2());t_order.setCustomer_city(defaultAddress.getCity());t_order.setCustomer_state(defaultAddress.getState());}try {t_order.setCustomer_mobilenumber(new Double(row.getCell(CUST_MOBILE_INDEX).getNumericCellValue()).toString());} catch (Exception e) {logger.error("Error in reading mobile Number for SourceId " + sourceId + " and 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.setTotal_amount(row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue());t_order.setSource(sourceId);orders.add(t_order);orderCountForRow++;}amount = new Double (row.getCell(1).getNumericCellValue() * row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue()).longValue();txn.setOrders(orders);Client transaction_client = new TransactionClient().getClient();try {transactionId = String.valueOf(transaction_client.createTransaction(txn));if(sourceDetail.getId()!= AMAZON_SOURCE_ID) {createPayment(user);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);}} else {}transaction_client.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.AUTHORIZED, "Dummy Payment received for the order of Source " + sourceId, pickUpType, OrderType.findByValue(orderType.intValue()), OrderSource.findByValue(sourceId.intValue()));transaction_client.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS, "Dummy RTGS Payment accepted for order of Source " + sourceId, pickUpType, OrderType.findByValue(orderType.intValue()), OrderSource.findByValue(sourceId.intValue()));logger.info("Successfully created transaction: " + transactionId + " for amount: " + amount);} catch (Exception e) {logger.error("Unable to establish connection to the transaction service", e);addActionError("Unable to establish connection to the transaction service");return "authsuccess";}}checkForErrors();return "authsuccess";}private LineItem createLineItem(Double itemId) throws CatalogServiceException, TException {LineItem lineItem = new LineItem();CatalogService.Client catalogClient = new CatalogClient().getClient();Item item = catalogClient.getItem(itemId.longValue());lineItem.setProductGroup(item.getProductGroup());lineItem.setBrand(item.getBrand());lineItem.setModel_number(item.getModelNumber());lineItem.setModel_name(item.getModelName());lineItem.setExtra_info(item.getFeatureDescription());lineItem.setItem_id(item.getId());lineItem.setUnit_weight(item.getWeight());lineItem.setTotal_weight(item.getWeight());//lineItem.setDealText(item.getBestDealText());//lineItem.setTotal_price(lineItem.getUnit_price());if (item.getColor() == null || "NA".equals(item.getColor())) {lineItem.setColor("");} else {lineItem.setColor(item.getColor());}return lineItem;}private void createPayment(User user) throws NumberFormatException, PaymentException, TException {List<Attribute> paymentAttributes = new ArrayList<Attribute>();paymentAttributes.add(new Attribute(PAY_METHOD, "4000"));paymentAttributes.add(new Attribute("sourceId", sourceId.toString()));in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();long paymentId = client.createPayment(user.getUserId(), Double.valueOf(amount), RTGS_GATEWAY_ID, Long.valueOf(transactionId), false);client.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null, PaymentStatus.SUCCESS, null, paymentAttributes);}@Overridepublic void setServletRequest(HttpServletRequest request) {this.request = request;this.session = request.getSession();}public String getErrorMsg(){return this.errorMsg;}private boolean checkForErrors(){Collection<String> actionErrors = getActionErrors();if(actionErrors != null && !actionErrors.isEmpty()){for (String str : actionErrors) {errorMsg += "<BR/>" + str;}if(rowId>1) {errorMsg += "<BR/>" + "Error while processing rowNumber : " + rowId;}return true;}return false;}public File getOrderDataFile() {return orderDataFile;}public void setOrderDataFile(File orderDataFile) {this.orderDataFile = orderDataFile;}public String getOrderDataFileName() {return orderDataFileName;}public void setOrderDataFileName(String orderDataFileName) {this.orderDataFileName = orderDataFileName;}public Long getSourceId() {return sourceId;}public void setSourceId(Long sourceId) {this.sourceId = sourceId;}public Long getOrderType() {return orderType;}public void setOrderType(Long orderType) {this.orderType = orderType;}public Long getPickUpType() {return pickUpType;}public void setPickUpType(Long pickUpType) {this.pickUpType = pickUpType;}}