Subversion Repositories SmartDukaan

Rev

Rev 15223 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
9776 vikram.rag 1
package in.shop2020;
2
 
3
import in.shop2020.model.v1.catalog.MarketPlaceItemPrice;
4
import in.shop2020.model.v1.catalog.SnapdealItemDetails;
15593 manish.sha 5
import in.shop2020.serving.services.SnapdealSessionCookie;
9776 vikram.rag 6
import in.shop2020.thrift.clients.CatalogClient;
7
import in.shop2020.utils.GmailUtils;
8
import inventory.Inventory;
9
import inventory.InventoryHistoryItems;
10
 
11
import java.io.BufferedReader;
12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.FileNotFoundException;
15
import java.io.FileOutputStream;
16
import java.io.IOException;
17
import java.io.InputStreamReader;
9858 vikram.rag 18
import java.io.UnsupportedEncodingException;
9776 vikram.rag 19
import java.text.SimpleDateFormat;
20
import java.util.ArrayList;
21
import java.util.HashMap;
22
import java.util.List;
23
import java.util.Map;
9821 vikram.rag 24
import java.util.Map.Entry;
9776 vikram.rag 25
 
26
import javax.mail.MessagingException;
27
 
28
import org.apache.http.HttpResponse;
29
import org.apache.http.NameValuePair;
30
import org.apache.http.client.ClientProtocolException;
31
import org.apache.http.client.entity.UrlEncodedFormEntity;
32
import org.apache.http.client.methods.HttpGet;
33
import org.apache.http.client.methods.HttpPost;
34
import org.apache.http.entity.mime.MultipartEntity;
35
import org.apache.http.entity.mime.content.ContentBody;
36
import org.apache.http.entity.mime.content.FileBody;
37
import org.apache.http.impl.client.DefaultHttpClient;
38
import org.apache.http.message.BasicNameValuePair;
39
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
40
import org.apache.poi.ss.usermodel.Row;
41
import org.apache.poi.ss.usermodel.Sheet;
42
import org.apache.poi.ss.usermodel.Workbook;
43
import org.apache.thrift.TException;
44
import org.apache.thrift.transport.TTransportException;
15593 manish.sha 45
import org.json.JSONObject;
9776 vikram.rag 46
 
47
import pricing.CurrentPricing;
48
import pricing.CurrentPricingItems;
49
import pricing.PricingHistory;
50
import pricing.PricingHistoryItems;
51
 
52
import com.google.gson.Gson;
53
 
54
public class CreateSnapdealPricingFeed {
55
 
56
	private static DefaultHttpClient client = new DefaultHttpClient();
57
	private static long time = System.currentTimeMillis();
58
	private static String SNAPDEAL_PRICING_SHEET;
59
	static Map<String,SnapdealItemDetails> snapdealItemMap = new HashMap<String,SnapdealItemDetails>();
60
	static Map<Long,SnapdealItemDetails> itemSnapdealMap = new HashMap<Long,SnapdealItemDetails>();
61
	static List<MarketPlaceItemPrice> marketPlaceItemsPrices;
62
	static Map<String,CurrentPricing> currentPricesMap = new HashMap<String,CurrentPricing>();
63
	static PricingHistoryItems pricingHistoryItems;
64
	static CurrentPricingItems currentPricingItems;
65
	private static SimpleDateFormat sdf;
66
	private static String emailFromAddress;
67
	private static String password;
68
	private static GmailUtils mailer;
69
	private static String[] sendTo;
15593 manish.sha 70
	private static Map<String, String> headers = new HashMap<String, String>();
9776 vikram.rag 71
 
72
	static {
73
		sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
74
		emailFromAddress = "build@shop2020.in";
75
		password = "cafe@nes";
76
		mailer = new GmailUtils();
9800 vikram.rag 77
		//sendTo = new String[]{"vikram.raghav@shop2020.in"};
78
		sendTo = new String[]{ "sandeep.sachdeva@shop2020.in", "vikram.raghav@shop2020.in", "rajneesh.arora@shop2020.in",
9776 vikram.rag 79
				"khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
10254 manish.sha 80
				"yukti.jain@shop2020.in","manisha.sharma@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in"};
9776 vikram.rag 81
		CatalogClient catalogServiceClient = null;
82
		try {
83
			catalogServiceClient = new CatalogClient();
84
		} catch (TTransportException e1) {
85
			e1.printStackTrace();
86
		}
87
		in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
88
		List<SnapdealItemDetails> allSnapdealItems = null;
89
		try {
90
			allSnapdealItems = catalogClient.getAllSnapdealItems();
91
			time = System.currentTimeMillis();
92
			SNAPDEAL_PRICING_SHEET = "/home/snapdeal/snapdeal-pricing-"+time+".xls";
93
			marketPlaceItemsPrices = catalogClient.getMarketPlaceItemsForPriceUpdate(7);
94
			if(marketPlaceItemsPrices.size()==0){
95
				System.out.println("No Change in Price to update");
96
				try {
97
					mailer.sendSSLMessage(sendTo,"No changes in Snapdeal Item Prices "+ sdf.format(System.currentTimeMillis()),"No change in Snapdeal Prices to be update ", emailFromAddress, password, new ArrayList<File>());
98
				} catch (MessagingException e) {
99
					e.printStackTrace();
100
				}
101
				System.exit(0);
102
			}
103
		} catch (TException e) {
104
			e.printStackTrace();
105
		}
106
		for(SnapdealItemDetails snapdealItem:allSnapdealItems){
107
			snapdealItemMap.put(snapdealItem.getSkuAtSnapdeal(),snapdealItem);
108
			itemSnapdealMap.put(snapdealItem.getItem_id(), snapdealItem);
109
		}
15593 manish.sha 110
 
111
		headers.put("User-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11");
112
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
113
		headers.put("Accept-Language", "en-US,en;q=0.8");
114
		headers.put("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
9776 vikram.rag 115
 
116
	}
9858 vikram.rag 117
 
15593 manish.sha 118
	public static void main(String... args) throws Exception{
9858 vikram.rag 119
		HttpGet get; 
120
		BufferedReader rd= null;
9776 vikram.rag 121
		Gson gson = new Gson();
122
		int i = 1;
123
		boolean exitfetchingcurrent = true;
124
		System.out.println("Fetching current prices");
9858 vikram.rag 125
		HttpResponse response;
15593 manish.sha 126
		SnapdealSessionCookie sdSessionCookie = new SnapdealSessionCookie();
127
		String cookies = "";
128
		JSONObject cookieObject = null;
9776 vikram.rag 129
		while(exitfetchingcurrent){
130
			get = new HttpGet("http://seller.snapdeal.com/pricing/search?gridType=normal&_search=false&nd="+time+"&rows=30&page="+i+"&sidx=&sord=asc");
15593 manish.sha 131
			cookies = sdSessionCookie.getCookies();
132
			cookieObject = new JSONObject(cookies);
133
			for(String key:headers.keySet())
134
				get.addHeader(key, headers.get(key));
135
			get.addHeader("Cookie","SERVERID="+cookieObject.get("SERVERID")+";sfJSESSIONID="+cookieObject.get("sfJSESSIONID")+";");
9776 vikram.rag 136
			response = client.execute(get);
137
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
138
			currentPricingItems = (CurrentPricingItems) gson.fromJson(rd, CurrentPricingItems.class);
139
			if(currentPricingItems.getRows().size()!=0){
140
				for(CurrentPricing currentPricing:currentPricingItems.getRows()){
141
					currentPricesMap.put(currentPricing.getSellerSku(),currentPricing);
9891 vikram.rag 142
					System.out.println(currentPricing.getSellerSku()+" "+currentPricing.getSellingPrice());
9776 vikram.rag 143
				}
144
			}
145
			else{
146
				exitfetchingcurrent = false;
147
			}
148
			i++;
149
		}
150
		FileInputStream fis = new FileInputStream("/root/code/trunk/SnapDealFeeds/SellerPricing.xls");
151
		Workbook hwb = new HSSFWorkbook(fis);
152
		Sheet sheet = hwb.getSheetAt(0);
153
		Row row;
154
		int iterator = 1;
9821 vikram.rag 155
		Map<String,Double> toUpdateSkuMap = new HashMap<String,Double>();
9776 vikram.rag 156
		for(MarketPlaceItemPrice marketPlaceItemPrice:marketPlaceItemsPrices){
157
			System.out.println(marketPlaceItemPrice.getItem_id() + " " + marketPlaceItemPrice.getSellingPrice());
158
			if(itemSnapdealMap.containsKey(marketPlaceItemPrice.getItem_id()) && marketPlaceItemPrice.getLastUpdatedOn() > marketPlaceItemPrice.getLastUpdatedOnMarketplace() && !marketPlaceItemPrice.isIsPriceOverride() && marketPlaceItemPrice.isIsListedOnSource()){
159
				if(currentPricesMap.containsKey(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()) && Double.parseDouble(currentPricesMap.get(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()).getSellingPrice()) != marketPlaceItemPrice.getSellingPrice() && marketPlaceItemPrice.getSellingPrice()!=0){
9799 vikram.rag 160
					row =   sheet.getRow((short) iterator);
9776 vikram.rag 161
					row.getCell((short) 0).setCellValue(currentPricesMap.get(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()).getSupc());
162
					row.getCell((short) 1).setCellValue(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal());
163
					row.getCell((short) 2).setCellValue(currentPricesMap.get(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()).getProductName());
164
					row.getCell((short) 3).setCellValue(marketPlaceItemPrice.getSellingPrice());
165
					row.getCell((short) 4).setCellValue(currentPricesMap.get(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()).getLive());
9821 vikram.rag 166
					toUpdateSkuMap.put(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal(),marketPlaceItemPrice.getSellingPrice());
9776 vikram.rag 167
					iterator++;
168
				}
169
			}
170
		}
171
		if(iterator!=1){
172
			FileOutputStream fileOut = null;
173
			fis.close();
174
			try {
175
				System.out.println("Before writing file ");
176
				fileOut = new FileOutputStream(SNAPDEAL_PRICING_SHEET);
177
			} catch (FileNotFoundException e) {
178
				e.printStackTrace();
179
			}
180
			try {
181
 
182
				hwb.write(fileOut);
183
			} catch (IOException e) {
184
				e.printStackTrace();
185
			}
11121 vikram.rag 186
			HttpPost post = new HttpPost("http://seller.snapdeal.com/pricing/upload?uploadType=SP");
15593 manish.sha 187
			cookies = sdSessionCookie.getCookies();
188
			cookieObject = new JSONObject(cookies);
189
			for(String key:headers.keySet())
190
				post.addHeader(key, headers.get(key));
191
			post.addHeader("Cookie","SERVERID="+cookieObject.get("SERVERID")+";sfJSESSIONID="+cookieObject.get("sfJSESSIONID")+";");
9776 vikram.rag 192
			File file = new File(SNAPDEAL_PRICING_SHEET);
193
			MultipartEntity mpEntity = new MultipartEntity();
194
			ContentBody cbFile = new FileBody(file,"application/vnd.ms-excel");
195
			mpEntity.addPart("file", cbFile);
196
			post.setEntity(mpEntity);
197
			response = client.execute(post);
198
			try {
199
				rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
200
			} catch (IllegalStateException e1) {
201
				e1.printStackTrace();
202
			} catch (IOException e1) {
203
				e1.printStackTrace();
204
			}
9858 vikram.rag 205
			String line = "";
9776 vikram.rag 206
			String feedresponse = null;
207
			try {
208
				while ((line = rd.readLine()) != null) {
209
					feedresponse = line;
210
				}
211
			} catch (IOException e) {
212
				e.printStackTrace();
213
			}
214
			int retry = 5;
215
			boolean exitfetchinghistory;
216
			int successfullyUpdated;
9821 vikram.rag 217
			Map<String,Double> updatedSkuMap = new HashMap<String,Double>();
9776 vikram.rag 218
			System.out.println("Feed response " + feedresponse);
219
			if(feedresponse.contains("Error")){
220
				System.out.println("Error while uploading sheet");
221
				try {
9891 vikram.rag 222
					mailer.sendSSLMessage(sendTo,"Error at Snapdeal while Uploading Pricing feed "+ sdf.format(System.currentTimeMillis()),"This Error means that there is some problem while uploading pricing feed to snapdeal", emailFromAddress, password, new ArrayList<File>());
9776 vikram.rag 223
				} catch (MessagingException e) {
224
					e.printStackTrace();
225
				}
226
				System.exit(0);
227
			}
228
			String uploadId = "UID"+feedresponse.split("UID")[1];
229
			System.out.println("Feed Upload Id is " + uploadId);
230
			int j = 1;
231
			i=1;
232
			while(retry > 0){
233
				Thread.sleep(5*60*1000);
234
				exitfetchinghistory = true;
235
				System.out.println("Fetching history prices " + j);
236
				successfullyUpdated =0;
237
				while(exitfetchinghistory){
238
					get = new HttpGet("http://seller.snapdeal.com/pricing/search?gridType=history&_search=false&nd="+time+"&rows=30&page="+i+"&sidx=&sord=asc");
15593 manish.sha 239
					cookies = sdSessionCookie.getCookies();
240
					cookieObject = new JSONObject(cookies);
241
					for(String key:headers.keySet())
242
						get.addHeader(key, headers.get(key));
243
					get.addHeader("Cookie","SERVERID="+cookieObject.get("SERVERID")+";sfJSESSIONID="+cookieObject.get("sfJSESSIONID")+";");
9776 vikram.rag 244
					response = client.execute(get);
245
					rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
246
					pricingHistoryItems = (PricingHistoryItems) gson.fromJson(rd, PricingHistoryItems.class);
9778 vikram.rag 247
					if(pricingHistoryItems.getRows().size()!=0 &&  successfullyUpdated != (iterator - 1)){
9776 vikram.rag 248
						for(PricingHistory pricingHistory:pricingHistoryItems.getRows()){
249
							if(Long.parseLong(pricingHistory.getModifiedOn()) > time && pricingHistory.getApprovalStatus().equals("Done") && pricingHistory.getUploadId().equals(uploadId)){
250
								successfullyUpdated++;
9821 vikram.rag 251
								updatedSkuMap.put(pricingHistory.getSellerSku(),Double.parseDouble(pricingHistory.getLineitems().get(0).getNewValue()));
9778 vikram.rag 252
								System.out.println("SKU Updated " + pricingHistory.getSellerSku() + " " + pricingHistory.getUploadId());
9776 vikram.rag 253
							}
254
						}
255
					}
256
					else{
257
						exitfetchinghistory = false;
9778 vikram.rag 258
						if(successfullyUpdated == (iterator-1)){
9776 vikram.rag 259
							retry = 0;
260
						}
261
					}
262
					i++;
263
				}
264
				retry--;
265
				j++;
266
			}
267
			CatalogClient catalogServiceClient = null;
268
			try {
269
				catalogServiceClient = new CatalogClient();
270
			} catch (TTransportException e1) {
271
				e1.printStackTrace();
272
			}
273
			in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
274
			List<Long> updatedItems = new ArrayList<Long>();
9821 vikram.rag 275
			String tableHeader = "<tr>" 
276
				+ "<td>" + "Product Name" +"</td>"
277
				+"<td>" + "Item ID" + "</td>"
278
				+"<td>" + "SKU at Snapdeal" + "</td>"
279
				+"<td>" + "Old Price" + "</td>"
280
				+"<td>" + "New Price" + "</td>"
281
				+"</tr>";
282
			if(toUpdateSkuMap.size() != updatedSkuMap.size()){
283
				StringBuffer notUpdatedMailBody =new StringBuffer();
284
				for(Entry<String, Double> entry:updatedSkuMap.entrySet()){
285
					toUpdateSkuMap.remove(entry.getKey());
286
				}
287
				for(Entry<String, Double> entry:toUpdateSkuMap.entrySet()){
288
					notUpdatedMailBody.append("<tr>" + "<td>" + currentPricesMap.get(entry.getKey()).getProductName() + "</td>"
9824 vikram.rag 289
							+"<td>" + snapdealItemMap.get(entry.getKey()).getItem_id() + "</td>"
290
							+"<td>" + snapdealItemMap.get(entry.getKey()).getSkuAtSnapdeal() + "</td>"
291
							+"<td>" + currentPricesMap.get(entry.getKey()).getSellingPrice() + "</td>" 
292
							+"<td>" + entry.getValue() +"</td>");
293
 
9821 vikram.rag 294
				}
295
				String text = "<html><table border=\"1\" align=\"center\">" 
9824 vikram.rag 296
					+ tableHeader  
297
					+ notUpdatedMailBody.toString() + "</table></html>";
298
 
9776 vikram.rag 299
				System.out.println("SKUs not updated");
300
				try {
9821 vikram.rag 301
					mailer.sendSSLMessage(sendTo,"Snapdeal Item Prices were not updated "+ sdf.format(System.currentTimeMillis()),emailFromAddress, password, text);
9776 vikram.rag 302
				} catch (MessagingException e) {
303
					e.printStackTrace();
304
				}
9824 vikram.rag 305
 
9776 vikram.rag 306
			}
9821 vikram.rag 307
			if(updatedSkuMap.size()>0){
308
				StringBuffer updatedMailBody =new StringBuffer();
309
				for(Entry<String, Double> entry:updatedSkuMap.entrySet()){
310
					updatedMailBody.append("<tr>" + "<td>" + currentPricesMap.get(entry.getKey()).getProductName() + "</td>"
311
							+"<td>" + snapdealItemMap.get(entry.getKey()).getItem_id() + "</td>"
9824 vikram.rag 312
							+"<td>" + snapdealItemMap.get(entry.getKey()).getSkuAtSnapdeal() + "</td>"
9821 vikram.rag 313
							+"<td>" + currentPricesMap.get(entry.getKey()).getSellingPrice() + "</td>" 
314
							+"<td>" + entry.getValue() +"</td>");
9824 vikram.rag 315
					updatedItems.add(snapdealItemMap.get(entry.getKey()).getItem_id());
9776 vikram.rag 316
				}
317
				try {
9817 vikram.rag 318
					catalogClient.updateMarketPlacePriceUpdateStatus(updatedItems,time,7);
9776 vikram.rag 319
				} catch (TException e) {
320
					try {
9817 vikram.rag 321
						new CatalogClient().getClient().updateMarketPlacePriceUpdateStatus(updatedItems, time,7);
9776 vikram.rag 322
					} catch (TTransportException e1) {
323
						e1.printStackTrace();
324
					} catch (TException e1) {
325
						e1.printStackTrace();
326
					}
327
					e.printStackTrace();
328
				}
9821 vikram.rag 329
				String text = "<html><table border=\"1\" align=\"center\">" 
330
					+ tableHeader  
331
					+ updatedMailBody.toString() + "</table></html>";
9824 vikram.rag 332
 
9776 vikram.rag 333
				try {
9778 vikram.rag 334
					System.out.println("Snapdeal Item Prices updated Successfully");
9821 vikram.rag 335
					if(updatedSkuMap.size()==1){
336
						mailer.sendSSLMessage(sendTo,updatedSkuMap.size()+" Snapdeal Item Price updated Successfully "+ sdf.format(System.currentTimeMillis()), emailFromAddress, password,text);
9797 vikram.rag 337
					}
338
					else{
9821 vikram.rag 339
						mailer.sendSSLMessage(sendTo,updatedSkuMap.size()+" Snapdeal Items Price updated Successfully "+ sdf.format(System.currentTimeMillis()), emailFromAddress, password,text);						
9797 vikram.rag 340
					}
9776 vikram.rag 341
				} catch (MessagingException e) {
342
					e.printStackTrace();
343
				}
344
			}
345
		}
346
		else{
347
			try {
348
				System.out.println("Prices are same as the snapdeal prices");
349
				mailer.sendSSLMessage(sendTo,"No changes in Snapdeal Item Prices "+ sdf.format(System.currentTimeMillis()),"No change in Snapdeal Prices to be update ", emailFromAddress, password, new ArrayList<File>());
350
			} catch (MessagingException e) {
351
				e.printStackTrace();
352
			}
9824 vikram.rag 353
 
9776 vikram.rag 354
		}
355
 
356
	}
357
 
358
 
359
}