Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.serving.controllers;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

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.OrderStatus;
import in.shop2020.model.v1.order.SourceDetail;
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.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.HelperClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.utils.Mail;

import in.shop2020.serving.controllers.BaseController;

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;
    
    public String index() {
        return INDEX;
    }
    
    public String create(){
        return index();
    }
    
    public String persistTransaction() {
        
        /**
         * 0.Create user
         * 1.Make a transaction object comprised of Order which in turn contains lineitem.
         * 2.Call create_transaction
         * 3.retrieve that order
         */
        
        Transaction txnObj = new Transaction();
        
        long tempUserId = -1;

        if(email != null && !email.isEmpty()) {
            tempUserId = createUserAndSendMail(email);
        } else {
            try {
                TransactionClient tcl = new TransactionClient();
                //Source Id for store website is 2 and our normal website is 1
                SourceDetail detail = tcl.getClient().getSourceDetail(2);
                
                tempUserId = createUserAndSendMail(detail.getEmail());
            } catch(Exception e) {
                log.error("Unable to get default source", e);
            }
        }
        
        if(tempUserId == -1) {
            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(tempUserId);
        txnObj.setCreatedOn(Calendar.getInstance().getTimeInMillis());
        txnObj.setTransactionStatus(TransactionStatus.INIT);
        txnObj.setStatusDescription("New Store Order");
        txnObj.setCoupon_code("");
        txnObj.setEmiSchemeId(0);
        
        List<Order> orders = new ArrayList<Order>();
        if(createOrder(tempUserId) ==  null) {
            log.error("Unable to create transaction");
            setErrorMsg("Unable to create order. Please try again.");
            return "error-result";
        }
        
        orders.add(createOrder(tempUserId));
        txnObj.setOrders(orders);
        TransactionClient tcl;
        try {
            tcl = new TransactionClient();
            long txnId = tcl.getClient().createTransaction(txnObj);
        } catch (Exception e) {
            log.error("Unable to create transaction", e);
            setErrorMsg("Unable to create order. Please try again.");
            return "error-result";
        }
        return "create-order";
    }
    
    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.SUBMITTED_FOR_PROCESSING);
        order.setStatusDescription("In process");
        order.setCreated_timestamp(Calendar.getInstance().getTimeInMillis());
        
//        t_order.total_weight = t_line_item.total_weight
//        t_order.lineitems = [t_line_item]
        return order;
    }
        
    public LineItem createLineItem() {
        LineItem lineitem = new LineItem();
        Item item = null;
        try {
            CatalogClient ccl = new CatalogClient();
            item = ccl.getClient().getItem(product_id);
        } 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(item.getBestDealText());
        
        if(item.getWarrantyPeriod() > 0) {
            //Computing Manufacturer Warranty expiry date
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, item.getWarrantyPeriod());
            cal.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, 23, 59, 59);
            lineitem.setWarrantry_expiry_timestamp(cal.getTimeInMillis());
        }
        
        return lineitem;
    }

//        if item.warrantyPeriod:
//            #Computing Manufacturer Warranty expiry date
//            today = datetime.date.today()
//            expiry_year = today.year + int((today.month + item.warrantyPeriod) / 12)
//            expiry_month = (today.month + item.warrantyPeriod) % 12
//            
//            try:
//                expiry_date = datetime.datetime(expiry_year, expiry_month, today.day, 23, 59, 59, 999999)
//            except ValueError:
//                try:
//                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 1), 23, 59, 59, 999999)
//                except ValueError:
//                    try:
//                        expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 2), 23, 59, 59, 999999)
//                    except ValueError:
//                        expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 3), 23, 59, 59, 999999)
//            
//            t_line_item.warrantry_expiry_timestamp = to_java_date(expiry_date)
//    
    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 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 static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 12);
        cal.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, 23, 59, 59);
        System.out.println(cal.getTimeInMillis());
    }

}