Subversion Repositories SmartDukaan

Rev

Rev 19443 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.serving.controllers;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

import in.shop2020.logistics.DeliveryType;
import in.shop2020.logistics.LogisticsInfo;
import in.shop2020.logistics.PickUpType;
import in.shop2020.logistics.LogisticsService.Client;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.catalog.ItemShippingInfo;
import in.shop2020.model.v1.catalog.StorePricing;
import in.shop2020.model.v1.order.HotspotStore;
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.StoreOrderDetail;
import in.shop2020.model.v1.order.StorePaymentStatus;
import in.shop2020.model.v1.order.Transaction;
import in.shop2020.model.v1.order.TransactionStatus;
import in.shop2020.model.v1.user.User;
import in.shop2020.model.v1.user.UserContextException;
import in.shop2020.payments.PaymentStatus;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.HelperClient;
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.utils.Mail;

import in.shop2020.serving.controllers.BaseController;
import in.shop2020.serving.utils.FormattingUtils;

@Results({
    @Result(name="order-success-redirect", type="redirectAction", params = {"actionName", "order-success", "paymentId", "${paymentId}", "userId", "${userId}"})
})

public class PaymentDetailsController  extends BaseController {
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String name;
    private String phone;
    private String line1;
    private String line2;
    private String city;
    private String state;
    private String pincode;
    private Long product_id;
    private String email;
    private static int LENGTH = 10;
    private static final String chars = "abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final Random random = new Random();
    private String errorMsg = "";
    private double price;
    private List<Order> orders = new ArrayList<Order>();
    private Double advanceAmount;
    private String deliveryDate = "";
    private String productName = "";
    private String bestDealText = "";
    private String CatalogItemId = "";
    private String cardType = "";
    private long paymentId;
    private long userId;
    
    
    private StorePricing sp;
    private double cardAmount;
    private double cashAmount;
    private String edc;
    private String approvalCode;
    
    public String index() {
        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
        if(loginStatus == null || !loginStatus.equals("TRUE")){
            return "authfail";
        }
        storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));
        if(!hotspotStores.containsKey(storeId)){
            try{
                HotspotStore hotSpotStore = (new TransactionClient()).getClient().getHotspotStore(storeId, "");
                hotspotStores.put(storeId, hotSpotStore);
            } catch (Exception e) {
                log.error("Unable to get store", e);
            }
        }
        
        return INDEX;
    }
    
    public String create(){
        return index();
    }
    
    public String persistTransaction() {
        if(advanceAmount > price) {
            setErrorMsg("Advance amount was greater than Total Price.");
            return "error-result";
        }
        
        if(cashAmount + cardAmount != advanceAmount) {
            setErrorMsg("Sum of cash and card amounts was not equal to total Price.");
            return "error-result";
        }
        
        if(cardAmount > 0 && approvalCode.equals("")) {
            setErrorMsg("Approval code cannot be empty.");
            return "error-result";
        }
        
        validateAddress();
        
        Transaction txnObj = new Transaction();
        StoreOrderDetail storeOrderDetail = new StoreOrderDetail();
        
        if(email != null && !email.isEmpty()) {
            userId = createUserAndSendMail(email);
        } else {
            log.error("Email is null, terminating the transaction");
            setErrorMsg("Invalid email Id. Please try again.");
            return "error-result";
        }
        
        if(userId == -1 || userId == 0) {
            log.error("Unable to get a user, terminating the transaction");
            setErrorMsg("Unable to create a user for this order. Please try again.");
            return "error-result";
        }
        
        txnObj.setShoppingCartid(0);
        txnObj.setCustomer_id(userId);
        txnObj.setCreatedOn(Calendar.getInstance().getTimeInMillis());
        txnObj.setTransactionStatus(TransactionStatus.INIT);
        txnObj.setStatusDescription("New Store Order");
        txnObj.setCoupon_code("");
        //txnObj.setPayment_option(payment_option)(0);
        log.info("UserId : " + userId);
        Order order = createOrder(userId);
        
        if(order ==  null) {
            log.error("Unable to create transaction");
            setErrorMsg("Unable to create order. Please try again.");
            return "error-result";
        }
        
        orders.add(order);
        txnObj.setOrders(orders);
        
        TransactionClient tcl;
        long txnId = 0;
        try {
            tcl = new TransactionClient();
            txnId = tcl.getClient().createTransaction(txnObj);
            
            storeOrderDetail.setAdvanceAmount(advanceAmount);
            storeOrderDetail.setCardAmount(cardAmount);
            storeOrderDetail.setCashAmount(cashAmount);
            storeOrderDetail.setOrderId(txnId);
            storeOrderDetail.setStoreId(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")));
            if(advanceAmount == price) {
                storeOrderDetail.setPayStatus(StorePaymentStatus.FULL_PAY_RECEIVED);
            } else {
                storeOrderDetail.setPayStatus(StorePaymentStatus.ADV_RECEIVED);
            }
            if(cardAmount > 0) {
                if(edc == null || edc.equals("")) {
                    setErrorMsg("Unable to create order. Please try again.");
                    log.error("Error : EDC is null");
                    return "error-result";
                }
                
                if(cardType == null || cardType.equals("")) {
                    setErrorMsg("Unable to create order. Please try again.");
                    log.error("Error : CardType is null");
                    return "error-result";
                }
                
                if(cardType == null || cardType.equals("")) {
                    setErrorMsg("Unable to create order. Please try again.");
                    log.error("Error : CardType is null");
                    return "error-result";
                }
                
                storeOrderDetail.setEdcBank(edc);
                storeOrderDetail.setCardType(cardType);
                storeOrderDetail.setApprovalCode(approvalCode);
            }
            storeOrderDetail.setCardRefundAmount(0);
            storeOrderDetail.setCashRefundAmount(0);
            
            boolean saveSuccess = tcl.getClient().saveStoreOrderDetail(storeOrderDetail);
            if(!saveSuccess) {
                setErrorMsg("Unable to create order. Please try again.");
                return "error-result";
            }
            
        } catch (Exception e) {
            log.error("Unable to create transaction", e);
            setErrorMsg("Unable to create order. Please try again.");
            return "error-result";
        }
        
        PaymentClient pcl;
        try {
            pcl = new PaymentClient();
            paymentId = pcl.getClient().createPayment(userId, price, 10, txnId, true);
            //Update payment status as authorized
            pcl.getClient().updatePaymentDetails(paymentId, "", "", "0", "", "", "", "", "", PaymentStatus.SUCCESS, "", null);
            txnId = pcl.getClient().getPayment(paymentId).getMerchantTxnId();
        } catch(Exception e) {
            log.error("Unable to create payment for this order");
            setErrorMsg("Unable to create order. Please try again.");
            return "error-result";
        }
        
        try {
            TransactionStatus txnStatus = TransactionStatus.COD_IN_PROCESS;
            if(advanceAmount >= price) {
                txnStatus = TransactionStatus.AUTHORIZED;
            }
            
            tcl = new TransactionClient();
            boolean status = tcl.getClient().changeTransactionStatus(txnId, txnStatus, "Payment authorized", PickUpType.COURIER.getValue(), OrderType.B2C, OrderSource.STORE);
            if(!status) {
                log.error("Unable to update transaction");
                setErrorMsg("Unable to create order. Please try again.");
                return "error-result";
            }
        } catch (Exception e) {
            log.error("Unable to create transaction", e);
            setErrorMsg("Unable to create order. Please try again.");
            return "error-result";
        }
        
        //No mail is required to sent.
        /*try {
         
            tcl = new TransactionClient();
            tcl.getClient().enqueueTransactionInfoEmail(txnId);
        } catch (Exception e) {
            log.error("Unable to send email", e);
        }*/
        
        return "order-success-redirect";
    }
    
    String validateAddress() {
        if(name.equals("") || line1.equals("") || city.equals("") || state.equals("") || pincode.equals("") || phone.equals("")) {
            setErrorMsg("Address was invalid");
            return "error-result";
        }
        return "";
    }
    
    public Order createOrder(long userId) {
        LineItem lineObj = createLineItem();
        if (lineObj == null) {
            return null;
        }
        Order order = new Order();
        User user = new User();
        try {
            UserClient ucl = new UserClient();
            user = ucl.getClient().getUserById(userId);
        } catch (Exception e) {
            log.error("Unable to get user for id " + userId, e);
            return null;
        }
        order.setCustomer_id(user.getUserId());
        order.setCustomer_email(user.getEmail());
        order.setCustomer_name(name);
        order.setCustomer_address1(line1);
        order.setCustomer_address2(line2);
        order.setCustomer_city(city);
        order.setCustomer_state(state);
        order.setCustomer_pincode(pincode);
        order.setCustomer_mobilenumber(phone);
        
        order.setTotal_amount(price);
        order.setStatus(OrderStatus.PAYMENT_PENDING);
        order.setStatusDescription("Order Incomplete");
        order.setCreated_timestamp(Calendar.getInstance().getTimeInMillis());
        order.setTotal_weight(lineObj.getTotal_weight());
        
        order.setSource(OrderSource.STORE.getValue());
        order.setStoreId(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")));
        
        order.setAdvanceAmount(advanceAmount);
        order.setFreebieItemId(sp.getFreebieItemId());
        
        order.setOrderType(OrderType.B2C);
        
        List<LineItem> lines = new ArrayList<LineItem>();
        lines.add(lineObj);
        order.setLineitems(lines);
        return order;
    }
        
    public LineItem createLineItem() {
        LineItem lineitem = new LineItem();
        Item item = null;
        try {
            CatalogClient ccl = new CatalogClient();
            item = ccl.getClient().getItem(product_id);
            sp = ccl.getClient().getStorePricing(product_id);
            lineitem.setDealText(sp.getBestDealText());
            
            ItemShippingInfo info = ccl.getClient().isActive(product_id);
            boolean isActive = info.isIsActive();
            boolean activeOnStore = ccl.getClient().getItem(product_id).isActiveOnStore();
            
            if(!isActive || !activeOnStore) {
                setErrorMsg("Unable to create order. Please try again.");
                return null;
            }
            
            if(price < sp.getAbsoluteMinPrice()) {
                setErrorMsg("You cannot sell below Rs." + sp.getAbsoluteMinPrice());
                return null;
            }
        } catch (Exception e) {
            log.error("Unable to get the item from catalog service, ItemId : " + product_id, e);
            setErrorMsg("Unable to create order. Please try again.");
            return null;
        }
        lineitem.setProductGroup(item.getProductGroup());
        lineitem.setBrand(item.getBrand());
        lineitem.setModel_number(item.getModelNumber());
        lineitem.setModel_name(item.getModelName());
        if(item.getColor() == null || item.getColor().isEmpty()) {
            lineitem.setColor("");
        } else {
            lineitem.setColor(item.getColor());
        }
        lineitem.setExtra_info(item.getFeatureDescription());
        lineitem.setItem_id(item.getId());
        lineitem.setQuantity(1.0);
        lineitem.setUnit_price(price);
        lineitem.setTotal_price(price);
        lineitem.setUnit_weight(item.getWeight());
        lineitem.setTotal_weight(item.getWeight());
        lineitem.setDealText(bestDealText);
        
        if(item.getWarrantyPeriod() > 0) {
            //Computing Manufacturer Warranty expiry date
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, item.getWarrantyPeriod());
            cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
            lineitem.setWarrantry_expiry_timestamp(cal.getTimeInMillis());
        }
        
        return lineitem;
    }

    private static String generateNewPassword() {
        char[] buf = new char[LENGTH];
        for (int i = 0; i < buf.length; i++) {
            buf[i] = chars.charAt(random.nextInt(chars.length()));
        }
        return new String(buf);
    }
    
    private long createUserAndSendMail(String email) {
        User user = null;
        String password = null;
        try{
        UserClient ucl = new UserClient();
        user = ucl.getClient().getUserByEmail(email);
        if(user.getUserId() == -1) {
            user.setEmail(email);
            password = generateNewPassword();
            String encryptedPassword = password;
            user.setPassword(encryptedPassword);
            user.setCommunicationEmail(email);
            UserClient userContextServiceClient = new UserClient();
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
            user = userClient.createUser(user);
            
            List<String> toList = new ArrayList<String>();
            toList.add(email);
            HelperClient helperServiceClient = null;
            helperServiceClient = new HelperClient();
            in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
            Mail mail = new Mail();
            mail.setSubject("Saholic Registration successful");
            mail.setTo(toList);
            mail.setData("Your have successfully registered with Saholic.com. Your user name is: " + email + " and your password is: " +  password);
            client.sendMail(mail);
            }
        }catch (UserContextException ux){
            return -1;               
        } catch (TTransportException e) {
            return -1;
        } catch (TException e) {
            return -1;
        } catch (Exception e) {
            log.error("Unexpected error while mailing the new password");
            return -1;
        }
        return user.getUserId();
    }
    
    public List<String> getAllEdcBanks() {
        List<String> banks = new ArrayList<String>(); 
        try {
            TransactionClient tcl = new TransactionClient();
            banks = tcl.getClient().getAllEdcBanks();
        } catch (Exception e) {
            log.error("Unable to get banks for EDC", e);
        }
        return banks;
    }

    public String getLine1() {
        return line1;
    }

    public void setLine1(String line1) {
        this.line1 = line1;
    }

    public String getLine2() {
        return line2;
    }

    public void setLine2(String line2) {
        this.line2 = line2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getPincode() {
        return pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public void setProduct_id(Long product_id) {
        this.product_id = product_id;
    }

    public Long getProduct_id() {
        return product_id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public List<Order> getOrders() {
        return orders;
    }

    public void setOrders(List<Order> orders) {
        this.orders = orders;
    }

    public Double getAdvanceAmount() {
        return advanceAmount;
    }

    public void setAdvanceAmount(Double advanceAmount) {
        this.advanceAmount = advanceAmount;
    }

    public void setDeliveryDate(String deliveryDate) {
        this.deliveryDate = deliveryDate;
    }

    public String getDeliveryDate() {
        return deliveryDate;
    }
    
    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getBestDealText() {
        return bestDealText;
    }

    public void setBestDealText(String bestDealText) {
        this.bestDealText = bestDealText;
    }
    
    
    public String getImageSource() {
        return "/storewebsite/images/website/" + getCatalogItemId() + "/default.jpg";
    }

    public String getCatalogItemId() {
        return CatalogItemId;
    }

    public void setCatalogItemId(String catalogItemId) {
        CatalogItemId = catalogItemId;
    }

    public long getPaymentId() {
        return paymentId;
    }

    public void setPaymentId(long paymentId) {
        this.paymentId = paymentId;
    }

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        this.userId = userId;
    }

    public double getCashAmount() {
        return cashAmount;
    }

    public void setCashAmount(double cashAmount) {
        this.cashAmount = cashAmount;
    }

    public double getCardAmount() {
        return cardAmount;
    }

    public void setCardAmount(double cardAmount) {
        this.cardAmount = cardAmount;
    }

    public String getEdc() {
        return edc;
    }

    public void setEdc(String edc) {
        this.edc = edc;
    }

    public String getApprovalCode() {
        return approvalCode;
    }

    public void setApprovalCode(String approvalCode) {
        this.approvalCode = approvalCode;
    }

    public void setCardType(String cardType) {
        this.cardType = cardType;
    }

    public String getCardType() {
        return cardType;
    }
}