Subversion Repositories SmartDukaan

Rev

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

/**
 * 
 */
package in.shop2020.support.controllers;

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.ProductCondition;
import in.shop2020.model.v1.order.TaxType;
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.order.Attribute;
import in.shop2020.logistics.PickUpType;
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.Payment;
import in.shop2020.payments.PaymentException;
import in.shop2020.payments.PaymentStatus;
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 in.shop2020.utils.ModelUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

import com.opensymphony.xwork2.ValidationAwareSupport;

/**
 * @author mandeep
 * 
 */
@SuppressWarnings("serial")
public class BulkOrderController extends ValidationAwareSupport {
    private static final int RTGS_GATEWAY_ID = 6;

    private static Log log = LogFactory.getLog(BulkOrderController.class);
    private SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final String IFSC_CODE   = "ifscCode";
    private static final String RTGS_BRANCH = "rtgsBranch";
    private static final String RTGS_BANK   = "rtgsBank";
    private static final String RTGS_ID     = "rtgsId";
    private static final String PAY_METHOD  = "payMethod";

    private String id;
    private String transactionId;
    private String customerEmailId;
    private String rtgsId;
    private String rtgsBank;
    private String rtgsBranch;
    private String ifscCode;
    private String amount;
    private String itemId;
    private String output;
    private String pickUp;
    private String orderType;
    private String tinNumber;
    private String poRefNumber;
    private int productCondition;
    private int taxType;
    private Transaction transaction;
    private Payment payment;

    private Map<Transaction, Double> transactions;
    private List<LineItem> lineItems;

    public String index() {
        transactions = new HashMap<Transaction, Double>();

        try {
            Client transactionClient = new TransactionClient().getClient();
            in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
            List<Payment> payments = paymentClient.getPayments(0, new Date().getTime(), PaymentStatus.SUCCESS, RTGS_GATEWAY_ID);

            log.info("Loaded " + payments.size() + " payments");
            for (Payment payment : payments) {
                Transaction txn = transactionClient.getTransaction(payment.getMerchantTxnId());
                log.info("Got " + txn);
                transactions.put(txn, payment.getAmount());
            }
        } catch (TTransportException e) {
            log.error("Could not create transaction client", e);
        } catch (TransactionServiceException e) {
            log.error("Could not lookup transaction", e);
        } catch (TException e) {
            log.error("Could not find payment", e);
        } catch (PaymentException e) {
            log.error("Could not find payment", e);
        }

        return "index";
    }

    public String editNew() {
        return "editNew";
    }

    public String show() {
        try {
            transactionId = id;

            Client transactionClient = new TransactionClient().getClient();
            transaction = transactionClient.getTransaction(Long.valueOf(transactionId));

            in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
            payment = paymentClient.getPaymentForTxnId(Long.valueOf(transactionId)).get(0);

            for (Attribute attribute : payment.getAttributes()) {
                if (RTGS_ID.equals(attribute.getName())) {
                    rtgsId = attribute.getValue();
                }
                else if (RTGS_BANK.equals(attribute.getName())) {
                    rtgsBank = attribute.getValue();
                }
                else if (RTGS_BRANCH.equals(attribute.getName())) {
                    rtgsBranch = attribute.getValue();
                }
                else if (IFSC_CODE.equals(attribute.getName())) {
                    ifscCode = attribute.getValue();
                }
            }
        } catch (NumberFormatException e) {
            log.error("Could not lookup transaction Id: " + transactionId, e);
        } catch (TransactionServiceException e) {
            log.error("Could not lookup transaction Id: " + transactionId, e);
        } catch (TException e) {
            log.error("Could not lookup transaction Id: " + transactionId, e);
        } catch (PaymentException e) {
            log.error("Could not lookup payment for transaction Id: " + transactionId, e);
        }

        return "show";
    }

    public String create() {
        log.info("Creating orders for " + lineItems);

        boolean hasError = false;

        try {
            hasError = validate();

            in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
            User user = userClient.getUserByEmail(customerEmailId);

            if (user == null) {
                addActionError("Could not find user by email: " + customerEmailId);
                hasError = true;
            }
            else {
                /*
                boolean selfPickupFlag = false;
                if(selfPickup.equals("on")){
                        selfPickupFlag = true;
                }
                */
                transactionId = String.valueOf(createTransaction(user));
                createPayment(user);
                
                in.shop2020.model.v1.order.Attribute orderAttribute = new in.shop2020.model.v1.order.Attribute();
                orderAttribute.setName("tinNumber");
                orderAttribute.setValue(tinNumber);
                
                in.shop2020.model.v1.order.Attribute orderAttribute1 = new in.shop2020.model.v1.order.Attribute();
                orderAttribute1.setName("poRefNumber");
                orderAttribute1.setValue(poRefNumber);

                Client transactionClient = new TransactionClient().getClient();
                if(!tinNumber.equals("") && !(tinNumber == null)) {
                    transactionClient.setOrderAttributeForTransaction(Long.parseLong(transactionId), orderAttribute);
                }
                if(!poRefNumber.equals("") && !(poRefNumber == null)) {
                    transactionClient.setOrderAttributeForTransaction(Long.parseLong(transactionId), orderAttribute1);
                }
                transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.AUTHORIZED, "Payment received for the order", PickUpType.valueOf(pickUp).getValue(), OrderType.valueOf(orderType), OrderSource.WEBSITE);
                transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS, "RTGS Payment accepted", PickUpType.valueOf(pickUp).getValue(), OrderType.valueOf(orderType), OrderSource.WEBSITE);
                log.info("Successfully created transaction: " + transactionId + " for amount: " + amount);
            }
        } catch (UserContextException e) {
            addActionError("Error while finding customer: " + customerEmailId);
            log.error("Could not fetch user for email Id: " + customerEmailId, e);
        } catch (TException e) {
            addActionError("Error while finding customer: " + customerEmailId);
            log.error("Could not fetch user for email Id: " + customerEmailId, e);
        } catch (TransactionServiceException e) {
            addActionError("Error creating transaction");
            log.error("Could not create transction Id", e);
        } catch (CatalogServiceException e) {
            addActionError("Error updating inventory");
            log.error("Error in CatalogService", e);
        } catch (NumberFormatException e) {
            addActionError("Error parsing transaction Id: " + transactionId);
            log.error("Error parsing transaction Id: " + transactionId, e);
        } catch (PaymentException e) {
            addActionError("Error creating payment");
            log.error("Could not create payment", e);
        }

        if (hasError) {
            return "error";
        }

        id = transactionId;
        return show();
    }

    public String getModelName() {
        output = "Invalid Item Id: " + itemId;

        try {
            in.shop2020.model.v1.catalog.CatalogService.Client client = new CatalogClient().getClient();
            Item item = client.getItem(Long.parseLong(itemId));
            if (item != null && item.getId() != 0) {
                output = ModelUtils.extractProductNameFromItem(item);
            }
        } catch (NumberFormatException e) {
            log.error("Could not parse itemId: " + itemId, e);
        } catch (CatalogServiceException e) {
            log.error("Could not lookup itemId: " + itemId, e);
        } catch (TException e) {
            log.error("Could not find itemId: " + itemId, e);
        }

        return "output";
    }

    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(RTGS_ID, rtgsId));
        paymentAttributes.add(new Attribute(RTGS_BANK, rtgsBank));
        paymentAttributes.add(new Attribute(RTGS_BRANCH, rtgsBranch));
        paymentAttributes.add(new Attribute(IFSC_CODE, ifscCode));

        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);
    }

    private long createTransaction(User user) throws TransactionServiceException, TException, CatalogServiceException {
        Transaction txn = new Transaction();
        txn.setShoppingCartid(user.getActiveCartId());
        txn.setCustomer_id(user.getUserId());
        txn.setCreatedOn(new Date().getTime());
        txn.setTransactionStatus(TransactionStatus.INIT);
        txn.setStatusDescription("New Order");
        txn.setOrders(createOrders(user));
        Client transaction_client = new TransactionClient().getClient();
        return transaction_client.createTransaction(txn);
    }

    private List<Order> createOrders(User user) throws CatalogServiceException, TException {
        List<Order> orders = new ArrayList<Order>();

        // Extracting default address
        Address defaultAddress = null;
        for (Address address : user.getAddresses()) {
            if (address.getId() == user.getDefaultAddressId()) {
                defaultAddress = address;
                break;
            }
        }

        for (LineItem lineItem : lineItems) {
            enrichLineItem(lineItem);

            Order t_order = new Order();
            t_order.setCustomer_id(user.getUserId());
            t_order.setCustomer_email(user.getEmail());
            t_order.setCustomer_name(defaultAddress.getName());
            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());
            t_order.setCustomer_mobilenumber(defaultAddress.getPhone());
            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.setSource(1);//Source : Website
            t_order.setProductCondition(ProductCondition.findByValue(productCondition));
            t_order.setTaxType(TaxType.findByValue(taxType));
            //t_order.setProductCondition(ProductCondition.findByValue(productCondition.intValue()));

            orders.add(t_order);
        }

        return orders;
    }

    private LineItem enrichLineItem(LineItem lineItem)
            throws CatalogServiceException, TException {
        in.shop2020.model.v1.catalog.CatalogService.Client client = new CatalogClient().getClient();

        Item item = client.getItem(lineItem.getItem_id());

        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.getQuantity());
        lineItem.setDealText(item.getBestDealText());
        lineItem.setTotal_price(lineItem.getUnit_price() * lineItem.getQuantity());

        if (item.getColor() == null || "NA".equals(item.getColor())) {
            lineItem.setColor("");
        } else {
            lineItem.setColor(item.getColor());
        }

        return lineItem;
    }

    private boolean validate() {
        return false;
    }

    public String convertDate(long date) {
        return SDF.format(new Date(date));
    }

    public String extractProductName(LineItem lineItem) {
        if (lineItem == null) {
            return "N/A";
        }

        return ModelUtils.extractProductNameFromLineItem(lineItem);
    }

    // Getters and Setters
    public String getCustomerEmailId() {
        return customerEmailId;
    }

    public void setCustomerEmailId(String customerEmailId) {
        this.customerEmailId = customerEmailId;
    }

    public String getRtgsId() {
        return rtgsId;
    }

    public void setRtgsId(String rtgsId) {
        this.rtgsId = rtgsId;
    }

    public String getRtgsBank() {
        return rtgsBank;
    }

    public void setRtgsBank(String rtgsBank) {
        this.rtgsBank = rtgsBank;
    }

    public String getRtgsBranch() {
        return rtgsBranch;
    }

    public void setRtgsBranch(String rtgsBranch) {
        this.rtgsBranch = rtgsBranch;
    }

    public String getIfscCode() {
        return ifscCode;
    }

    public void setIfscCode(String ifscCode) {
        this.ifscCode = ifscCode;
    }

    public String getAmount() {
        return amount;
    }

    public void setAmount(String amount) {
        this.amount = amount;
    }

    public List<LineItem> getLineItems() {
        return lineItems;
    }

    public void setLineItems(List<LineItem> lineItems) {
        this.lineItems = lineItems;
    }

    public Map<Transaction, Double> getTransactions() {
        return transactions;
    }

    public void setTransactions(Map<Transaction, Double> transactions) {
        this.transactions = transactions;
    }

    public String getTransactionId() {
        return transactionId;
    }

    public void setTransactionId(String transactionId) {
        this.transactionId = transactionId;
    }

    public Transaction getTransaction() {
        return transaction;
    }

    public void setTransaction(Transaction transaction) {
        this.transaction = transaction;
    }

    public Payment getPayment() {
        return payment;
    }

    public void setPayment(Payment payment) {
        this.payment = payment;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getItemId() {
        return itemId;
    }

    public void setItemId(String itemId) {
        this.itemId = itemId;
    }

    public String getOutput() {
        return output;
    }

    public void setOutput(String output) {
        this.output = output;
    }

    public String getPickUp() {
        return pickUp;
    }

    public void setPickUp(String pickUp) {
        this.pickUp = pickUp;
    }

    public String getOrderType() {
        return orderType;
    }

    public void setOrderType(String orderType) {
        this.orderType = orderType;
    }

    public String getTinNumber() {
        return tinNumber;
    }

    public void setTinNumber(String tinNumber) {
        this.tinNumber = tinNumber;
    }

        public int getProductCondition() {
                return productCondition;
        }

        public void setProductCondition(int productCondition) {
                this.productCondition = productCondition;
        }

        public int getTaxType() {
                return taxType;
        }

        public void setTaxType(int taxType) {
                this.taxType = taxType;
        }
        
        public String getPoRefNumber() {
                return poRefNumber;
        }

        public void setPoRefNumber(String poRefNumber) {
                this.poRefNumber = poRefNumber;
        }

        public static void main(String[] args) {
                BulkOrderController blc = new BulkOrderController();
                blc.setCustomerEmailId("neavins@amazon.com");
                blc.setRtgsId("rtgsId");
                blc.setRtgsBank("rtgsBank");
                blc.setRtgsBranch("rtgsBranch");
                blc.setIfscCode("ifscCode");
                blc.setAmount("3400");
                blc.setItemId("10661");
                //blc.setOutput();
                blc.setPickUp("COURIER");
                blc.setOrderType("B2Cbulk");
                //blc.setTinNumber();
                blc.setProductCondition(0);
                blc.setTaxType(0);
                
                
                blc.index();
                /*
                 * = "ifscCode";
    private static final String RTGS_BRANCH = "rtgsBranch";
    private static final String RTGS_BANK   = "rtgsBank";
    private static final String RTGS_ID     = "rtgsId";
                 * private String customerEmailId;
            private String rtgsId;
            private String rtgsBank;
            private String rtgsBranch;
            private String ifscCode;
            private String amount;
            private String itemId;
            private String output;
            private String pickUp;
            private String orderType;
            private String tinNumber;
            private int productCondition;
            private int taxType;*/
                //blc.set
        }
    
}