Subversion Repositories SmartDukaan

Rev

Rev 9797 | Rev 9800 | 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;
22
 
23
import javax.mail.MessagingException;
24
 
25
import org.apache.http.HttpResponse;
26
import org.apache.http.NameValuePair;
27
import org.apache.http.client.ClientProtocolException;
28
import org.apache.http.client.entity.UrlEncodedFormEntity;
29
import org.apache.http.client.methods.HttpGet;
30
import org.apache.http.client.methods.HttpPost;
31
import org.apache.http.entity.mime.MultipartEntity;
32
import org.apache.http.entity.mime.content.ContentBody;
33
import org.apache.http.entity.mime.content.FileBody;
34
import org.apache.http.impl.client.DefaultHttpClient;
35
import org.apache.http.message.BasicNameValuePair;
36
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
37
import org.apache.poi.ss.usermodel.Row;
38
import org.apache.poi.ss.usermodel.Sheet;
39
import org.apache.poi.ss.usermodel.Workbook;
40
import org.apache.thrift.TException;
41
import org.apache.thrift.transport.TTransportException;
42
 
43
import pricing.CurrentPricing;
44
import pricing.CurrentPricingItems;
45
import pricing.PricingHistory;
46
import pricing.PricingHistoryItems;
47
 
48
import com.google.gson.Gson;
49
 
50
public class CreateSnapdealPricingFeed {
51
 
52
	private static DefaultHttpClient client = new DefaultHttpClient();
53
	private static long time = System.currentTimeMillis();
54
	private static String SNAPDEAL_PRICING_SHEET;
55
	static Map<String,SnapdealItemDetails> snapdealItemMap = new HashMap<String,SnapdealItemDetails>();
56
	static Map<Long,SnapdealItemDetails> itemSnapdealMap = new HashMap<Long,SnapdealItemDetails>();
57
	static List<MarketPlaceItemPrice> marketPlaceItemsPrices;
58
	static Map<String,CurrentPricing> currentPricesMap = new HashMap<String,CurrentPricing>();
59
	static PricingHistoryItems pricingHistoryItems;
60
	static CurrentPricingItems currentPricingItems;
61
	private static SimpleDateFormat sdf;
62
	private static String emailFromAddress;
63
	private static String password;
64
	private static GmailUtils mailer;
65
	private static String[] sendTo;
66
 
67
	static {
68
		sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
69
		emailFromAddress = "build@shop2020.in";
70
		password = "cafe@nes";
71
		mailer = new GmailUtils();
72
		sendTo = new String[]{"vikram.raghav@shop2020.in"};
73
		/*		sendTo = new String[]{ "sandeep.sachdeva@shop2020.in", "vikram.raghav@shop2020.in", "rajneesh.arora@shop2020.in",
74
				"khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
75
				"yukti.jain@shop2020.in","manisha.sharma@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in","amar.kumar@shop2020.in"};
76
		 */
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;
174
		List<String> toUpdateSkuList = new ArrayList<String>();
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());
185
					toUpdateSkuList.add(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal());
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;
233
			List<String> updatedSkuList = new ArrayList<String>();
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++;
262
								updatedSkuList.add(pricingHistory.getSellerSku());
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>();
286
			if(toUpdateSkuList.size() != updatedSkuList.size()){
287
				toUpdateSkuList.removeAll(updatedSkuList);
288
				System.out.println("SKUs not updated");
289
				try {
9778 vikram.rag 290
					mailer.sendSSLMessage(sendTo,"Snapdeal Item Prices were not updated "+ sdf.format(System.currentTimeMillis()),"Following Snapdeal Item Prices were not updated \n"+toUpdateSkuList.toString(), emailFromAddress, password, new ArrayList<File>());
9776 vikram.rag 291
				} catch (MessagingException e) {
292
					// TODO Auto-generated catch block
293
					e.printStackTrace();
294
				}
295
 
296
			}
297
			if(updatedSkuList.size()>0){
298
				for(String updatedSku:updatedSkuList){
299
					if(snapdealItemMap.containsKey(updatedSku)){
300
						updatedItems.add(snapdealItemMap.get(updatedSku).getItem_id());
301
					}
302
				}
303
				try {
304
					catalogClient.updateMarketPlacePriceUpdateStatus(updatedItems,time);
305
				} catch (TException e) {
306
					try {
307
						new CatalogClient().getClient().updateMarketPlacePriceUpdateStatus(updatedItems, time);
308
					} catch (TTransportException e1) {
309
						e1.printStackTrace();
310
					} catch (TException e1) {
311
						e1.printStackTrace();
312
					}
313
					e.printStackTrace();
314
				}
315
				try {
9778 vikram.rag 316
					System.out.println("Snapdeal Item Prices updated Successfully");
9797 vikram.rag 317
					if(updatedSkuList.size()==1){
318
						mailer.sendSSLMessage(sendTo,updatedSkuList.size()+" Snapdeal Item Price updated Successfully "+ sdf.format(System.currentTimeMillis()),"Snapdeal Item Price updated Successfully ", emailFromAddress, password, new ArrayList<File>());
319
					}
320
					else{
321
						mailer.sendSSLMessage(sendTo,updatedSkuList.size()+" Snapdeal Items Price updated Successfully "+ sdf.format(System.currentTimeMillis()),"All Snapdeal Item Prices updated Successfully ", emailFromAddress, password, new ArrayList<File>());						
322
					}
9776 vikram.rag 323
				} catch (MessagingException e) {
324
					e.printStackTrace();
325
				}
326
			}
327
		}
328
		else{
329
			try {
330
				System.out.println("Prices are same as the snapdeal prices");
331
				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>());
332
			} catch (MessagingException e) {
333
				e.printStackTrace();
334
			}
335
 
336
		}
337
 
338
	}
339
 
340
 
341
}