Subversion Repositories SmartDukaan

Rev

Rev 9813 | Rev 9817 | 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();
9800 vikram.rag 72
		//sendTo = new String[]{"vikram.raghav@shop2020.in"};
73
		sendTo = new String[]{ "sandeep.sachdeva@shop2020.in", "vikram.raghav@shop2020.in", "rajneesh.arora@shop2020.in",
9776 vikram.rag 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
		CatalogClient catalogServiceClient = null;
77
		try {
78
			catalogServiceClient = new CatalogClient();
79
		} catch (TTransportException e1) {
80
			e1.printStackTrace();
81
		}
82
		in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
83
		List<SnapdealItemDetails> allSnapdealItems = null;
84
		try {
85
			allSnapdealItems = catalogClient.getAllSnapdealItems();
86
			time = System.currentTimeMillis();
87
			SNAPDEAL_PRICING_SHEET = "/home/snapdeal/snapdeal-pricing-"+time+".xls";
88
			marketPlaceItemsPrices = catalogClient.getMarketPlaceItemsForPriceUpdate(7);
89
			if(marketPlaceItemsPrices.size()==0){
90
				System.out.println("No Change in Price to update");
91
				try {
92
					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>());
93
				} catch (MessagingException e) {
94
					e.printStackTrace();
95
				}
96
				System.exit(0);
97
			}
98
		} catch (TException e) {
99
			e.printStackTrace();
100
		}
101
		for(SnapdealItemDetails snapdealItem:allSnapdealItems){
102
			snapdealItemMap.put(snapdealItem.getSkuAtSnapdeal(),snapdealItem);
103
			itemSnapdealMap.put(snapdealItem.getItem_id(), snapdealItem);
104
		}
105
 
106
	}
107
 
108
 
109
	public static void main(String... args) throws IOException, InterruptedException{
110
		HttpPost post = new HttpPost("http://seller.snapdeal.com/login_security_check?spring-security-redirect=http://seller.snapdeal.com/inventory&");
111
		HttpGet get; 
112
		BufferedReader rd= null;
113
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
114
		nameValuePairs.add(new BasicNameValuePair("j_username",
115
		"khushal.bhatia@saholic.com"));
116
		nameValuePairs.add(new BasicNameValuePair("j_password",
117
		"sonline"));
118
		post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
119
		HttpResponse response = null;
120
		try {
121
			response = client.execute(post);
122
		} catch (ClientProtocolException e) {
123
			// TODO Auto-generated catch block
124
			e.printStackTrace();
125
		} catch (IOException e) {
126
			// TODO Auto-generated catch block
127
			e.printStackTrace();
128
		}
129
		try {
130
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
131
		} catch (IllegalStateException e1) {
132
			// TODO Auto-generated catch block
133
			e1.printStackTrace();
134
		} catch (IOException e1) {
135
			// TODO Auto-generated catch block
136
			e1.printStackTrace();
137
		}
138
		String line = "";
139
		try {
140
			while ((line = rd.readLine()) != null) {
141
				//System.out.println(line);
142
			}
143
		} catch (IOException e) {
144
			// TODO Auto-generated catch block
145
			e.printStackTrace();
146
		}
147
		Gson gson = new Gson();
148
		int i = 1;
149
		boolean exitfetchingcurrent = true;
150
		System.out.println("Fetching current prices");
151
		while(exitfetchingcurrent){
152
			get = new HttpGet("http://seller.snapdeal.com/pricing/search?gridType=normal&_search=false&nd="+time+"&rows=30&page="+i+"&sidx=&sord=asc");
153
			response = client.execute(get);
154
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
155
			currentPricingItems = (CurrentPricingItems) gson.fromJson(rd, CurrentPricingItems.class);
156
			if(currentPricingItems.getRows().size()!=0){
157
				for(CurrentPricing currentPricing:currentPricingItems.getRows()){
158
					currentPricesMap.put(currentPricing.getSellerSku(),currentPricing);
159
					//System.out.println(currentPricing.getSellerSku()+" "+currentPricing.getSellingPrice());
160
				}
161
			}
162
			else{
163
				exitfetchingcurrent = false;
164
			}
165
			i++;
166
		}
167
 
168
		FileInputStream fis = new FileInputStream("/root/code/trunk/SnapDealFeeds/SellerPricing.xls");
169
		Workbook hwb = new HSSFWorkbook(fis);
170
		Sheet sheet = hwb.getSheetAt(0);
171
		Row row;
172
		int iterator = 1;
173
		List<String> toUpdateSkuList = new ArrayList<String>();
174
		for(MarketPlaceItemPrice marketPlaceItemPrice:marketPlaceItemsPrices){
175
			System.out.println(marketPlaceItemPrice.getItem_id() + " " + marketPlaceItemPrice.getSellingPrice());
176
			if(itemSnapdealMap.containsKey(marketPlaceItemPrice.getItem_id()) && marketPlaceItemPrice.getLastUpdatedOn() > marketPlaceItemPrice.getLastUpdatedOnMarketplace() && !marketPlaceItemPrice.isIsPriceOverride() && marketPlaceItemPrice.isIsListedOnSource()){
177
				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 178
					row =   sheet.getRow((short) iterator);
9776 vikram.rag 179
					row.getCell((short) 0).setCellValue(currentPricesMap.get(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()).getSupc());
180
					row.getCell((short) 1).setCellValue(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal());
181
					row.getCell((short) 2).setCellValue(currentPricesMap.get(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()).getProductName());
182
					row.getCell((short) 3).setCellValue(marketPlaceItemPrice.getSellingPrice());
183
					row.getCell((short) 4).setCellValue(currentPricesMap.get(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal()).getLive());
184
					toUpdateSkuList.add(itemSnapdealMap.get(marketPlaceItemPrice.getItem_id()).getSkuAtSnapdeal());
185
					iterator++;
186
				}
187
			}
188
		}
189
		if(iterator!=1){
190
			FileOutputStream fileOut = null;
191
			fis.close();
192
			try {
193
				System.out.println("Before writing file ");
194
				fileOut = new FileOutputStream(SNAPDEAL_PRICING_SHEET);
195
			} catch (FileNotFoundException e) {
196
				e.printStackTrace();
197
			}
198
			try {
199
 
200
				hwb.write(fileOut);
201
			} catch (IOException e) {
202
				// TODO Auto-generated catch block
203
				e.printStackTrace();
204
			}
205
			post = new HttpPost("http://seller.snapdeal.com/pricing/upload");
206
			File file = new File(SNAPDEAL_PRICING_SHEET);
207
			MultipartEntity mpEntity = new MultipartEntity();
208
			ContentBody cbFile = new FileBody(file,"application/vnd.ms-excel");
209
			mpEntity.addPart("file", cbFile);
210
			post.setEntity(mpEntity);
211
			response = client.execute(post);
212
			try {
213
				rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
214
			} catch (IllegalStateException e1) {
215
				e1.printStackTrace();
216
			} catch (IOException e1) {
217
				e1.printStackTrace();
218
			}
219
			line = "";
220
			String feedresponse = null;
221
			try {
222
				while ((line = rd.readLine()) != null) {
223
					feedresponse = line;
224
				}
225
			} catch (IOException e) {
226
				// TODO Auto-generated catch block
227
				e.printStackTrace();
228
			}
229
			int retry = 5;
230
			boolean exitfetchinghistory;
231
			int successfullyUpdated;
232
			List<String> updatedSkuList = new ArrayList<String>();
233
			System.out.println("Feed response " + feedresponse);
234
			if(feedresponse.contains("Error")){
235
				System.out.println("Error while uploading sheet");
236
				try {
237
					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>());
238
				} catch (MessagingException e) {
239
					e.printStackTrace();
240
				}
241
				System.exit(0);
242
			}
243
			String uploadId = "UID"+feedresponse.split("UID")[1];
244
			System.out.println("Feed Upload Id is " + uploadId);
245
			int j = 1;
246
			i=1;
247
			while(retry > 0){
248
				Thread.sleep(5*60*1000);
249
				exitfetchinghistory = true;
250
				System.out.println("Fetching history prices " + j);
251
				successfullyUpdated =0;
252
				while(exitfetchinghistory){
253
					get = new HttpGet("http://seller.snapdeal.com/pricing/search?gridType=history&_search=false&nd="+time+"&rows=30&page="+i+"&sidx=&sord=asc");
254
					response = client.execute(get);
255
					rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
256
					pricingHistoryItems = (PricingHistoryItems) gson.fromJson(rd, PricingHistoryItems.class);
9778 vikram.rag 257
					if(pricingHistoryItems.getRows().size()!=0 &&  successfullyUpdated != (iterator - 1)){
9776 vikram.rag 258
						for(PricingHistory pricingHistory:pricingHistoryItems.getRows()){
259
							if(Long.parseLong(pricingHistory.getModifiedOn()) > time && pricingHistory.getApprovalStatus().equals("Done") && pricingHistory.getUploadId().equals(uploadId)){
260
								successfullyUpdated++;
261
								updatedSkuList.add(pricingHistory.getSellerSku());
9778 vikram.rag 262
								System.out.println("SKU Updated " + pricingHistory.getSellerSku() + " " + pricingHistory.getUploadId());
9776 vikram.rag 263
							}
264
						}
265
					}
266
					else{
267
						exitfetchinghistory = false;
9778 vikram.rag 268
						if(successfullyUpdated == (iterator-1)){
9776 vikram.rag 269
							retry = 0;
270
						}
271
					}
272
					i++;
273
				}
274
				retry--;
275
				j++;
276
			}
277
			CatalogClient catalogServiceClient = null;
278
			try {
279
				catalogServiceClient = new CatalogClient();
280
			} catch (TTransportException e1) {
281
				e1.printStackTrace();
282
			}
283
			in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
284
			List<Long> updatedItems = new ArrayList<Long>();
285
			if(toUpdateSkuList.size() != updatedSkuList.size()){
286
				toUpdateSkuList.removeAll(updatedSkuList);
287
				System.out.println("SKUs not updated");
288
				try {
9778 vikram.rag 289
					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 290
				} catch (MessagingException e) {
291
					// TODO Auto-generated catch block
292
					e.printStackTrace();
293
				}
294
 
295
			}
296
			if(updatedSkuList.size()>0){
297
				for(String updatedSku:updatedSkuList){
298
					if(snapdealItemMap.containsKey(updatedSku)){
299
						updatedItems.add(snapdealItemMap.get(updatedSku).getItem_id());
300
					}
301
				}
302
				try {
9814 vikram.rag 303
					catalogClient.updateMarketPlacePriceUpdateStatus(updatedItems,time);
9776 vikram.rag 304
				} catch (TException e) {
305
					try {
9814 vikram.rag 306
						new CatalogClient().getClient().updateMarketPlacePriceUpdateStatus(updatedItems, time);
9776 vikram.rag 307
					} catch (TTransportException e1) {
308
						e1.printStackTrace();
309
					} catch (TException e1) {
310
						e1.printStackTrace();
311
					}
312
					e.printStackTrace();
313
				}
314
				try {
9778 vikram.rag 315
					System.out.println("Snapdeal Item Prices updated Successfully");
9797 vikram.rag 316
					if(updatedSkuList.size()==1){
317
						mailer.sendSSLMessage(sendTo,updatedSkuList.size()+" Snapdeal Item Price updated Successfully "+ sdf.format(System.currentTimeMillis()),"Snapdeal Item Price updated Successfully ", emailFromAddress, password, new ArrayList<File>());
318
					}
319
					else{
320
						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>());						
321
					}
9776 vikram.rag 322
				} catch (MessagingException e) {
323
					e.printStackTrace();
324
				}
325
			}
326
		}
327
		else{
328
			try {
329
				System.out.println("Prices are same as the snapdeal prices");
330
				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>());
331
			} catch (MessagingException e) {
332
				e.printStackTrace();
333
			}
334
 
335
		}
336
 
337
	}
338
 
339
 
340
}