Subversion Repositories SmartDukaan

Rev

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