Subversion Repositories SmartDukaan

Rev

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

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

import in.shop2020.logistics.PickUpType;
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.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.ItemPriceQuantity;
import in.shop2020.model.v1.user.User;
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.List;
import java.util.Map;

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

import com.opensymphony.xwork2.ValidationAwareSupport;

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

        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 Transaction transaction;
        private Payment payment;
        private long userWalletAmount;
        private int userId;
        

        private Map<Transaction, Double> transactions;
        private List<LineItem> lineItems;
        
        private Client transactionClient;
        private in.shop2020.model.v1.user.UserContextService.Client userClient;
        private in.shop2020.payments.PaymentService.Client paymentClient;
        private in.shop2020.model.v1.catalog.CatalogService.Client catalogClient;
        
        public BulkOrderController() {
                super();
                try {
                        this.userClient = new UserClient().getClient();
                        this.paymentClient = new PaymentClient().getClient();
                        this.transactionClient = new TransactionClient().getClient();
                        this.catalogClient = new CatalogClient().getClient();
                } catch (Exception e){
                        log.error("Error occured while initialising client");
                        e.printStackTrace();
                }
        }

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

        public String editNew() throws Throwable {
                User user = userClient.getUserByEmail(customerEmailId);
                this.userWalletAmount = this.transactionClient.getUserWallet(user.getUserId()).getAmount();
                return "editNew";
        }

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

                        transaction = this.transactionClient.getTransaction(Long.valueOf(transactionId));
                        payment = this.paymentClient.getPaymentForTxnId(Long.valueOf(transactionId)).get(0);

                } 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 = true;

                try {
                        User user = this.userClient.getUserByEmail(customerEmailId);
                        List<ItemPriceQuantity> ipqList = new ArrayList<ItemPriceQuantity>();
                        double totalAmount = 0;

                        if (user == null) {
                                addActionError("Could not find user by email: " + customerEmailId);
                        } else {
                                double walletAmount = this.transactionClient.getUserWallet(user.getUserId()).getAmount();
                                for (LineItem li : lineItems) {
                                        ItemPriceQuantity ipq = new ItemPriceQuantity();
                                        ipq.setQty((long) li.getQuantity());
                                        ipq.setItemId(li.getItem_id());
                                        log.info("Item ID ----------- " + li.getItem_id());
                                        ipq.setPrice(li.getUnit_price());
                                        ipqList.add(ipq);
                                        totalAmount = li.getUnit_price() * li.getQuantity();
                                }
                                if (totalAmount > walletAmount) {
                                        addActionError("Total Amount not be greater than wallet amount");
                                } else if (!this.userClient.addItemPricingToCart(user.getActiveCartId(), ipqList)) {
                                        addActionError("Total Amount not be greater than wallet amount");
                                } else {
                                        log.info("Setting wallet amount in cart");
                                        this.userClient.setWalletAmountInCart(user.getActiveCartId(), walletAmount);
                                        transactionId = String.valueOf(this.userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, user.getUserId(), 7890,
                                                        OrderSource.WEBSITE.getValue(), true));
                                        log.info("Creating wallet payment for transactionId - " + transactionId);
                                        createPayment(user);

                                        in.shop2020.model.v1.order.Attribute orderAttribute1 = new in.shop2020.model.v1.order.Attribute();
                                        if (poRefNumber != null && !poRefNumber.equals("")) {
                                                orderAttribute1.setName("poRefNumber");
                                                orderAttribute1.setValue(poRefNumber);
                                                this.transactionClient.setOrderAttributeForTransaction(Long.parseLong(transactionId), orderAttribute1);
                                        }
                                        this.transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.AUTHORIZED,
                                                        "Payment received for the order", PickUpType.valueOf(pickUp).getValue(), OrderType.valueOf(orderType),
                                                        OrderSource.WEBSITE);
                                        this.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);
                                        this.transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
                                        hasError = false;
                                }
                        }
                } catch (Exception e) {
                        addActionError("Error occerred - " + e.getMessage());
                        e.printStackTrace();
                }
                if (hasError) {
                        return "error";
                }

                id = transactionId;
                return show();
        }

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

                try {
                        
                        Item item = this.catalogClient.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";
        }
        /**
         As it is always going to be wallet
         **/
        private void createPayment(User user) throws NumberFormatException, PaymentException, TException {
                List<Attribute> paymentAttributes = new ArrayList<Attribute>();
                paymentAttributes.add(new Attribute(PAY_METHOD, "7890"));
                /*
                 * 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));
                 */

                long paymentId = this.paymentClient.createPayment(user.getUserId(), Double.valueOf(amount), WALLET_GATEWAY_ID, Long.valueOf(transactionId),
                                false);
                this.paymentClient.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.setProductCondition(ProductCondition.findByValue(productCondition.intValue()));

                        orders.add(t_order);
                }

                return orders;
        }

        private LineItem enrichLineItem(LineItem lineItem) throws CatalogServiceException, TException {

                Item item = this.catalogClient.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 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(ProductCondition.GOOD.getValue());

                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
        }

        public double getWalletAmount() {
                return this.userWalletAmount;
        }

}