Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.serving.services;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import in.shop2020.model.v1.order.FlipkartOrder;
import in.shop2020.model.v1.order.TransactionServiceException;

import in.shop2020.serving.model.Order;
import in.shop2020.serving.model.OrderItems;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.utils.GmailUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;

public class FlipkartHoldOrdersReconciliation{
        private static String sendTo[] = new String[]{ "sandeep.sachdeva@shop2020.in", "eng@shop2020.in" ,
                        "khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
                        "yukti.jain@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in"};
        //private static String sendTo1[]  = new String[]{"manish.sharma@shop2020.in"};
        private static java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        private static Calendar cal=GregorianCalendar.getInstance();
        private static String emailFromAddress = "build-staging@shop2020.in";
        private static String password = "shop2020";
        private static GmailUtils mailer = new GmailUtils();
        private static String cookies;
        
        public static void main(String[] args) throws IOException{
                File file = new File("/home/manish/alerts/fkhold.txt");
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
                
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost("https://seller.flipkart.com/login");
                BufferedReader rd= null;
                try {
                        HttpGet get_new;
                        get_new = new HttpGet("https://seller.flipkart.com/");
                        get_new.addHeader("Host","seller.flipkart.com");
            get_new.addHeader("User-agent", "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31");
            get_new.addHeader("Connection","keep-alive");
            
            HttpResponse response = client.execute(get_new);
            rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }
            cookies = response.getFirstHeader("Set-Cookie") == null ? "" : 
                response.getFirstHeader("Set-Cookie").getValue();
            
            System.out.println("Cookies Before Login "+ cookies);
            
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("authName",
                        "flipkart"));
                        nameValuePairs.add(new BasicNameValuePair("username",
                        "flipkart-support@saholic.com"));
                        nameValuePairs.add(new BasicNameValuePair("password",
                        "bestmobiledeals2010"));
                        post.addHeader("Cookie",cookies);
                        post.addHeader("User-agent", "Mozilla/4.0");
                        post.addHeader("Referer", "seller.flipkart.com");
                        post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
                        response = client.execute(post);
                        cookies = response.getFirstHeader("Set-Cookie") == null ? "" : 
                response.getFirstHeader("Set-Cookie").getValue();
                        System.out.println("Cookies After Login "+cookies);
                        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                        line = "";
                        
                        List<FlipkartOrder> pendingOrderList = new ArrayList<FlipkartOrder>();
                        List<FlipkartOrder> acceptedOrderList = new ArrayList<FlipkartOrder>();
                        List<FlipkartOrder> cancelledOrderList = new ArrayList<FlipkartOrder>();
                        List<FlipkartOrder> errorOrderList = new ArrayList<FlipkartOrder>();
                        
                        while ((line = rd.readLine()) != null) {
                                System.out.println(line);
                        }
                        
                        //https://seller.flipkart.com/order_management/search_order_items?order_id=OD40827062297&sellerId=m2z93iskuj81qiid
                        TransactionClient transactionServiceClient = new TransactionClient();
                        in.shop2020.model.v1.order.TransactionService.Client tClient = transactionServiceClient.getClient();
                        List<FlipkartOrder> pendingFkOrdersList = tClient.getVerificationPendingOrdersFK();
                        StringBuffer sb = new StringBuffer();
                        StringBuffer resB = new StringBuffer();
                        for(FlipkartOrder fkOrder : pendingFkOrdersList){
                                get_new = new HttpGet("https://seller.flipkart.com/order_management/search_order_items?order_id="+fkOrder.getFlipkartOrderId()+"&sellerId=m2z93iskuj81qiid");
                                get_new.addHeader("Cookie",cookies+"; __gads=ID=dfe0374cf04d1576:T=1381304511:S=ALNI_Ma2TpDrlF9_amkoqp3MOYJBaFAOUg; km_lv=x; T=TI138130450866706710769873257251497444628820234222703981199700765991; __CG=u%3A6208250296506778000%2Cs%3A2098853214%2Ct%3A1419058011787%2Cc%3A1%2Ck%3Awww.flipkart.com/24/24/76%2Cf%3A0%2Ci%3A1; S=d1t13CXEVURPbRn%2FTAlMG9iwwwBWoS%2FUUixPxuJkY6W8pdfcWEzMG07x3EBPSRtlGHPdclpSYHdyFGacGJ0K01qpxtQ%3D%3D; __sonar=6631097455123118581; __utma=19769839.1156779613.1390806906.1432813861.1435573112.27; __utmc=19769839; __utmz=19769839.1435573112.27.15.utmcsr=zimbrasmtp.com|utmccn=(referral)|utmcmd=referral|utmcct=/ch300-3.htm; s_ch_list=%5B%5B'Affiliates'%2C'1435573117633'%5D%5D; s_cc=true; s_ppv=0; s_sq=%5B%5BB%5D%5D; SN=2.VIB4C4C187B63B4436AAE42944FD9BE1C9.SI2B008083CC2145FFB103D6E76CDB343C.VS143557310149768094467.1435573140; VID=2.VIB4C4C187B63B4436AAE42944FD9BE1C9.1435573140.VS143557310149768094467; NSID=2.SI2B008083CC2145FFB103D6E76CDB343C.1435573140.VIB4C4C187B63B4436AAE42944FD9BE1C9; sellerId=m2z93iskuj81qiid; _ga=GA1.2.1156779613.1390806906; kvcd=1435740168445; km_vs=1; km_ai=m2z93iskuj81qiid; km_ni=m2z93iskuj81qiid; _gat=1; km_uq=; __utma=143439159.1156779613.1390806906.1435737045.1435740037.94; __utmb=143439159.9.9.1435740156534; __utmc=143439159; __utmz=143439159.1390806906.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _mkto_trk=id:021-QVV-957&token:_mch-flipkart.com-1434970574990-64308");
                                get_new.addHeader("Host","seller.flipkart.com");
                    get_new.addHeader("User-agent", "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31");
                    get_new.addHeader("Connection","keep-alive");
                                response = client.execute(get_new);
                                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                                
                                line = "";
                                line = rd.readLine();
                                System.out.println("Response... "+line);
                                response.getEntity().consumeContent();
                                JSONObject jsonDataObj = null;
                                JSONArray jsonObjArr = null;
                                if(line == null || line.isEmpty()){
                                        sb.append("Flipkart Order Id -"+ fkOrder.getFlipkartOrderId()+" Response - "+line);
                                        sb.append("\n");
                                        continue;
                                } else if (!line.startsWith("{")){
                                        sb.append("Flipkart Order Id -"+ fkOrder.getFlipkartOrderId()+" Response - "+line);
                                        sb.append("\n");
                                        continue;
                                }
                                else{
                                        jsonDataObj = new JSONObject(line);
                                }
                                
                                if(jsonDataObj!=null){
                                        jsonObjArr = new JSONArray(jsonDataObj.get("items").toString());
                                }
                                
                                if(jsonObjArr!=null && jsonObjArr.length()>0){
                                        JSONObject jsonObj = null;
                                        jsonObj = jsonObjArr.getJSONObject(0);
                                        if(jsonObj!=null){
                                                if(jsonObj.get("status")!=null){
                                                        String status = jsonObj.get("status").toString();
                                                        String statusLabel = jsonObj.get("statusLabel").toString();
                                                        if("on_hold".equalsIgnoreCase(status) || "On hold".equalsIgnoreCase(statusLabel)){
                                                                pendingOrderList.add(fkOrder);
                                                        }
                                                        if("approved".equalsIgnoreCase(status) || "Approved".equalsIgnoreCase(statusLabel) || "confirmed".equalsIgnoreCase(statusLabel)){
                                                                if(tClient ==null || !tClient.isAlive()){
                                                                        tClient = transactionServiceClient.getClient();
                                                                }
                                                                tClient.verifyOrder(fkOrder.getOrderId());
                                                                tClient.acceptOrder(fkOrder.getOrderId());
                                                                acceptedOrderList.add(fkOrder);
                                                        }
                                                        if("cancelled".equalsIgnoreCase(status) || "Cancelled".equalsIgnoreCase(statusLabel)){
                                                                if(tClient ==null || !tClient.isAlive()){
                                                                        tClient = transactionServiceClient.getClient();
                                                                }
                                                                tClient.refundOrder(fkOrder.getOrderId(), "flipkart", "As per Buyer's Request");
                                                                cancelledOrderList.add(fkOrder);
                                                        }
                                                }else{
                                                        errorOrderList.add(fkOrder);
                                                }
                                        }
                                }
                                Thread.sleep(3000);
                        }
                        
                        resB.append("Still Pending Orders:-\n");
                        System.out.println("Still Pending Orders:-");
                        for(FlipkartOrder order: pendingOrderList){
                                resB.append(order.getOrderId()+" "+ order.getFlipkartOrderId()+"\n");
                                System.out.println(order.getOrderId()+" "+ order.getFlipkartOrderId());
                        }
                        resB.append("Accepeted Orders:-\n");
                        System.out.println("Accepeted Orders:-");
                        for(FlipkartOrder order: acceptedOrderList){
                                resB.append(order.getOrderId()+" "+ order.getFlipkartOrderId()+"\n");
                                System.out.println(order.getOrderId()+" "+ order.getFlipkartOrderId());
                        }
                        resB.append("Cancelled Orders:-\n");
                        System.out.println("Cancelled Orders:-");
                        for(FlipkartOrder order: cancelledOrderList){
                                resB.append(order.getOrderId()+" "+ order.getFlipkartOrderId()+"\n");
                                System.out.println(order.getOrderId()+" "+ order.getFlipkartOrderId());
                        }
                        resB.append("Response not found Orders:-\n");
                        System.out.println("Response not found Orders:-");
                        for(FlipkartOrder order: errorOrderList){
                                resB.append(order.getOrderId()+" "+ order.getFlipkartOrderId()+"\n");
                                System.out.println(order.getOrderId()+" "+ order.getFlipkartOrderId());
                        }
                        String emailSubjectTxt = " Flipkart Hold Order Reconcilaition Process "+sdf.format(cal.getTime());
                        mailer.sendSSLMessage(sendTo, emailSubjectTxt, resB.toString(), emailFromAddress, password, new ArrayList<File>());
                        System.out.println(sb.toString());
                        
                        bufferedWriter.write(StringUtils.join(new String[] {"FlipkartHoldUpdationDate",sdf.format(new Date())}, '\t'));
                        bufferedWriter.close();
                } catch (Exception e) {
                        e.printStackTrace();
                        try{
                                //mailer.sendSSLMessage(sendTo, "Error in Hold Order Recon Process", "Please inform Engineering Team", emailFromAddress, password, new ArrayList<File>());
                        }catch (Exception e1) {
                                e1.printStackTrace();
                        }
                }
        }
}