Subversion Repositories SmartDukaan

Rev

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

package in.shop2020;

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.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.LineItem;
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.TransactionServiceException;
import in.shop2020.model.v1.order.TransactionStatus;
import in.shop2020.model.v1.order.TransactionService.Client;
import in.shop2020.model.v1.user.User;
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.PaymentClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.UserClient;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import order.SaholicAPI;
import order.ObjectFactory;
import order.SaholicAPI.Order;

public class ProcessSnapdealOrder {
        private static final int SNAPDEAL_SOURCE_ID = 7;
        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 String transactionId;
        private static final int SNAPDEAL_GATEWAY_ID = 18;
        private static Logger logger;

        public static void processSnapdealOrders(File file) throws JAXBException{
                logger = LoggerFactory.getLogger(ProcessSnapdealOrder.class);
                JAXBContext jc = JAXBContext.newInstance(SaholicAPI.class);
                Unmarshaller unmarshaller = jc.createUnmarshaller();
                SaholicAPI orders = (SaholicAPI) unmarshaller.unmarshal(file);
                Marshaller marshaller = jc.createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                marshaller.marshal(orders, System.out);
                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);
                }
                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);
                }
                for(Order order:orders.getOrder()){
                        long subOrderId = (long) order.getSuborderId();
                        Client transaction_client = null;
                        try {
                                transaction_client = new TransactionClient().getClient();
                                //transaction_client.snapdealOrderExists(subOrderId);
                                System.out.println("Suborder id " + subOrderId);
                                if(transaction_client.snapdealOrderExists(subOrderId)) {
                                        System.out.println("Suborder id exists");
                                        continue;
                                }

                        } catch (TTransportException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                        } catch (TException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        System.out.println("Inside Order Parsing");
                        Transaction txn = new Transaction();
                        System.out.println("User details are " + user.getActiveCartId());
                        txn.setShoppingCartid(user.getActiveCartId());
                        System.out.println("transaction created");
                        txn.setCustomer_id(user.getUserId());
                        System.out.println("User Id is " + user.getUserId());
                        txn.setCreatedOn(new Date().getTime());
                        txn.setTransactionStatus(TransactionStatus.INIT);
                        txn.setStatusDescription("Order for Snapdeal ");
                        List<in.shop2020.model.v1.order.Order> orderlist = new ArrayList<in.shop2020.model.v1.order.Order>();
                        LineItem lineItem = null;
                        try {
                                lineItem = createLineItem(order.getSKUCode(),order.getSellingPricePerItem());
                                System.out.println("Line item created");
                        } catch (CatalogServiceException e) {
                                logger.error("Unable to create order for suborderid  " + order.getSuborderId());
                                e.printStackTrace();
                        } catch (TException e) {
                                logger.error("Unable to create order for suborderid  " + order.getSuborderId());
                                e.printStackTrace();
                        }
                        in.shop2020.model.v1.order.Order t_order = new in.shop2020.model.v1.order.Order();
                        t_order.setCustomer_id(user.getUserId());
                        t_order.setCustomer_email(sourceDetail.getEmail());
                        t_order.setCustomer_name(order.getCustomerName());
                        t_order.setCustomer_address1("");
                        t_order.setCustomer_address2("");
                        t_order.setCustomer_city(order.getCity());
                        t_order.setCustomer_state(order.getState());
                        t_order.setCustomer_pincode(String.valueOf(order.getPINCode()));
                        t_order.setTotal_amount(lineItem.getTotal_price());            
                        t_order.setTotal_weight(lineItem.getTotal_weight());
                        t_order.setLineitems(Collections.singletonList(lineItem));            
                        t_order.setStatus(OrderStatus.SUBMITTED_FOR_PROCESSING);
                        t_order.setStatusDescription("In Process");
                        t_order.setCreated_timestamp(new Date().getTime());
                        t_order.setOrderType(OrderType.B2C);
                        t_order.setCod(false);
                        System.out.println("t order created");
                        try {
                                Calendar time = Calendar.getInstance();
                                time.add(Calendar.DAY_OF_MONTH, 1);
                                t_order.setPromised_shipping_time(order.getShipByDate().getMillisecond());
                                t_order.setExpected_shipping_time(order.getShipByDate().getMillisecond());
                                time.add(Calendar.DAY_OF_MONTH, 3);
                                t_order.setPromised_delivery_time(time.getTimeInMillis());
                                t_order.setExpected_delivery_time(time.getTimeInMillis());
                                System.out.println("Dates set in transaction");
                        } catch(Exception e) {
                                logger.error("Error in updating Shipping or Delivery Time for suborderid  " + order.getSuborderId());
                                continue;
                        }
                        InventoryService.Client inventoryClient = null;
            Warehouse fulfillmentWarehouse= null; 
            try {
                inventoryClient = new InventoryClient().getClient();
                List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(order.getSKUCode(), 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) {
                continue;
                        } catch (TTransportException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (TException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        if(order.getCourier().equalsIgnoreCase(FIRSTFLIGHT)) {
                                t_order.setLogistics_provider_id(12);
                        } else if(order.getCourier().equalsIgnoreCase(DELHIVERY)) {
                                t_order.setLogistics_provider_id(13);
                        } else if(order.getCourier().equalsIgnoreCase(BLUEDART)) {
                                t_order.setLogistics_provider_id(14);
                        }else if(order.getCourier().equalsIgnoreCase(CHHOTU)) {
                                t_order.setLogistics_provider_id(16);
                        } else {
                                logger.error("Error No Courier Match please add courier to our system for suborderid  " + order.getSuborderId() + "Courier Name " + order.getCourier());
                                continue;
                        }

                        t_order.setAirwaybill_no(String.valueOf(order.getAWBNumber()));
                        t_order.setTracking_id(String.valueOf(order.getAWBNumber()));
                        t_order.setTotal_amount(order.getSellingPricePerItem());
                        t_order.setOrderType(OrderType.B2C);
                        t_order.setSource(SNAPDEAL_SOURCE_ID);
                        t_order.setOrderType(OrderType.B2C);
                        orderlist.add(t_order);
                        txn.setOrders(orderlist);
                                String referenceCode = order.getReferenceCode();
                                String productName = order.getProduct();
                                SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                Date snapdealTxnDate = null;
                                try {
                                        snapdealTxnDate = istFormatter.parse(order.getOrderPlacedDate());
                                } catch (ParseException e) {
                                        logger.error("Could not parse order date from file ");
                                        e.printStackTrace();
                                }
                                try {
                                        transactionId =  String.valueOf(transaction_client.createTransaction(txn));
                                } catch (TransactionServiceException e) {
                                        logger.error("Could not create transaction ");
                                        e.printStackTrace();
                                } catch (TException e) {
                                        logger.error("Problem with transaction service while creating transaction");
                                        e.printStackTrace();
                                }
                                createPayment(user, (new Long(subOrderId)).toString(), lineItem.getTotal_price());

                                Transaction transaction = null;
                                try {
                                        transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
                                } catch (NumberFormatException e) {
                                        logger.error("Problem parsing transaction id " + transactionId);
                                        e.printStackTrace();
                                } catch (TransactionServiceException e) {
                                        logger.error("Problem getting transaction from service transaction id " + transactionId);
                                        e.printStackTrace();
                                } catch (TException e) {
                                        logger.error("Problem with transaction service while getting transaction id " + transactionId);
                                        e.printStackTrace();
                                }
                                in.shop2020.model.v1.order.Order snapdealorder = transaction.getOrders().get(0);

                                //inventoryClient.reserveItemInWarehouse(lineItem.getItem_id(), fulfillmentWarehouse.getId(), 1, 
                                //              snapdealorder.getId(), snapdealorder.getCreated_timestamp(), snapdealorder.getPromised_shipping_time(), snapdealorder.getLineitems().get(0).getQuantity());


                                SnapdealOrder snapdealOrder = new SnapdealOrder();
                                snapdealOrder.setOrderId(snapdealorder.getId());
                                snapdealOrder.setSubOrderId(subOrderId);
                                snapdealOrder.setReferenceCode(referenceCode);
                                snapdealOrder.setProductName(productName);
                                snapdealOrder.setSnapdealTxnDate(snapdealTxnDate.getTime());
                                snapdealOrder.setListingPrice(lineItem.getTotal_price());
                                try {
                                        transaction_client.createSnapdealOrder(snapdealOrder);
                                } catch (TException e) {
                                        logger.error("Could not create Snapdeal Order");
                                        e.printStackTrace();
                                }

                        } 

        }

        public static void createPayment(User user, String subOrderId, double amount) {
                in.shop2020.payments.PaymentService.Client client = null;
                try {
                        client = new PaymentClient().getClient();
                } catch (TTransportException e) {
                        logger.error("Could not connect to payment service ");
                        e.printStackTrace();
                }
                long paymentId = 0;
                try {
                        paymentId = client.createPayment(user.getUserId(), amount, SNAPDEAL_GATEWAY_ID, Long.valueOf(transactionId), false);
                } catch (NumberFormatException e) {
                        logger.error("Could not create payment");
                        e.printStackTrace();
                } catch (PaymentException e) {
                        logger.error("Could not create payment payment exception");
                        e.printStackTrace();
                } catch (TException e) {
                        logger.error("Could not create payment thrift exception");
                        e.printStackTrace();
                }
                try {
                        client.updatePaymentDetails(paymentId, null, null, null, null, null, null, subOrderId, null, PaymentStatus.AUTHORIZED, null, null);
                } catch (PaymentException e) {
                        logger.error("Could not update payment to order");
                        e.printStackTrace();
                } catch (TException e) {
                        logger.error("Could not update payment thrift exception");
                        e.printStackTrace();
                }
        }   

        public static 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;
        }

}