Subversion Repositories SmartDukaan

Rev

Rev 15223 | Rev 15598 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
14630 manish.sha 1
package in.shop2020;
2
 
3
import in.shop2020.model.v1.catalog.CatalogService;
4
import in.shop2020.model.v1.catalog.CatalogServiceException;
5
import in.shop2020.model.v1.catalog.Item;
6
import in.shop2020.model.v1.catalog.SnapdealItem;
7
import in.shop2020.model.v1.inventory.InventoryService;
8
import in.shop2020.model.v1.inventory.InventoryServiceException;
9
import in.shop2020.model.v1.inventory.InventoryType;
10
import in.shop2020.model.v1.inventory.VendorItemPricing;
11
import in.shop2020.model.v1.inventory.Warehouse;
12
import in.shop2020.model.v1.inventory.WarehouseType;
13
import in.shop2020.model.v1.order.LineItem;
14
import in.shop2020.model.v1.order.OrderStatus;
15
import in.shop2020.model.v1.order.OrderType;
16
import in.shop2020.model.v1.order.SnapdealOrder;
17
import in.shop2020.model.v1.order.SourceDetail;
18
import in.shop2020.model.v1.order.Transaction;
19
import in.shop2020.model.v1.order.TransactionServiceException;
20
import in.shop2020.model.v1.order.TransactionStatus;
21
import in.shop2020.model.v1.order.TransactionService.Client;
22
import in.shop2020.model.v1.user.User;
23
import in.shop2020.payments.PaymentException;
24
import in.shop2020.payments.PaymentStatus;
25
import in.shop2020.serving.model.OrderItems;
26
import in.shop2020.thrift.clients.CatalogClient;
27
import in.shop2020.thrift.clients.InventoryClient;
28
import in.shop2020.thrift.clients.PaymentClient;
29
import in.shop2020.thrift.clients.TransactionClient;
30
import in.shop2020.thrift.clients.UserClient;
15587 manish.sha 31
import in.shop2020.utils.FlipkartConsumer;
14630 manish.sha 32
import in.shop2020.utils.GmailUtils;
33
 
34
import java.io.BufferedReader;
35
import java.io.File;
36
import java.io.FileWriter;
37
import java.io.IOException;
38
import java.io.InputStreamReader;
39
import java.net.URLEncoder;
40
import java.text.ParseException;
41
import java.text.SimpleDateFormat;
42
import java.util.ArrayList;
43
import java.util.Calendar;
44
import java.util.Collections;
45
import java.util.Date;
46
import java.util.GregorianCalendar;
47
import java.util.HashMap;
48
import java.util.List;
49
import java.util.Map;
50
 
51
import org.apache.http.HttpResponse;
52
import org.apache.http.NameValuePair;
53
import org.apache.http.client.ClientProtocolException;
54
import org.apache.http.client.HttpClient;
55
import org.apache.http.client.entity.UrlEncodedFormEntity;
56
import org.apache.http.client.methods.HttpGet;
57
import org.apache.http.client.methods.HttpPost;
15587 manish.sha 58
import org.apache.http.entity.mime.Header;
14630 manish.sha 59
import org.apache.http.impl.client.DefaultHttpClient;
60
import org.apache.http.message.BasicNameValuePair;
61
import org.apache.thrift.TException;
62
import org.apache.thrift.transport.TTransportException;
63
import org.json.JSONArray;
64
import org.json.JSONException;
65
import org.json.JSONObject;
66
import org.slf4j.Logger;
67
import org.slf4j.LoggerFactory;
68
 
69
import au.com.bytecode.opencsv.CSVReader;
70
import au.com.bytecode.opencsv.CSVWriter;
71
 
72
import com.google.gson.Gson;
73
 
74
import utilities.SnapdealOrderUnit;
75
import utilities.VendorPendingOrderSkuDetail;
76
import utilities.VendorPendingProductOfferDisplayDTO;
77
 
78
public class SnapdealOrderCreator{
79
	private static DefaultHttpClient client = new DefaultHttpClient();
80
	private static Logger logger = LoggerFactory.getLogger(SnapdealOrderCreator.class);
81
	private static List<VendorPendingProductOfferDisplayDTO> pendingOrdersSkuList = new ArrayList<VendorPendingProductOfferDisplayDTO> ();
82
	private static final int SNAPDEAL_SOURCE_ID = 7;
83
	private static String transactionId;
84
	private static long paymentId;
85
	private static final int SNAPDEAL_GATEWAY_ID = 18;
86
 
15587 manish.sha 87
	private static Map<String, String> headers = new HashMap<String, String>();
88
 
89
	static{
90
		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");
91
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
92
		headers.put("Accept-Language", "en-US,en;q=0.8");
93
		headers.put("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
94
	}
95
 
96
	/*
14630 manish.sha 97
	public static void handleLogin() throws ClientProtocolException, IOException{
98
		HttpGet get = new HttpGet("http://selleraccounts.snapdeal.com/keymaker/login");
99
		HttpResponse response = null;
100
		try {
101
			response = client.execute(get);
102
		} catch (Exception e) {
103
			e.printStackTrace();
104
		} 
105
 
106
		BufferedReader rd = null;
107
		try {
108
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
109
		} catch (Exception e1) {
110
			e1.printStackTrace();
111
		} 
112
		String line = "";
113
		StringBuffer sb = new StringBuffer();
114
		try {
115
			while ((line = rd.readLine()) != null) {
116
				sb.append(line);
117
				//System.out.println(line);
118
			}
119
		} catch (IOException e) {
120
			e.printStackTrace();
121
		}
122
		int i= sb.toString().indexOf("name=\"lt\" value=");
123
		char[] charArray = sb.toString().toCharArray();
124
		String lt = "";
125
		int j=0;
126
		for(j=i+16;j<=charArray.length;j++){
127
 
128
			if(charArray[j]==' '){
129
				break;
130
			}
131
		}
132
		lt = sb.substring(i+17,j-1);
133
		System.out.println("LT VALUE " + lt);
134
		i= sb.toString().indexOf("name=\"execution\" value=");
135
		charArray = sb.toString().toCharArray();
136
 
137
		String ex = "";
138
		j=0;
139
		for(j=i+24;j<=charArray.length;j++){
140
			if(charArray[j]==' '){
141
				break;
142
			}
143
		}
144
		ex = sb.substring(i+24,j-1);
145
		System.out.println("EXECUTION VALUE " + ex);	
146
 
147
 
148
		HttpPost post = new HttpPost("http://selleraccounts.snapdeal.com/login?service=http%3A%2F%2Fshipping.snapdeal.com%2Fj_spring_cas_security_check");
149
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
150
		//nameValuePairs.add(new BasicNameValuePair("username",
151
		//"khushal.bhatia@saholic.com"));
152
		nameValuePairs.add(new BasicNameValuePair("username",
153
		"saholic-snapdeal@saholic.com"));
154
		//nameValuePairs.add(new BasicNameValuePair("password",
155
		//"sonline"));
156
		nameValuePairs.add(new BasicNameValuePair("password",
15223 manish.sha 157
		"saholic15"));
14630 manish.sha 158
		nameValuePairs.add(new BasicNameValuePair("_eventId","submit"));
159
		nameValuePairs.add(new BasicNameValuePair("execution",ex));
160
		nameValuePairs.add(new BasicNameValuePair("lt",lt));
161
		nameValuePairs.add(new BasicNameValuePair("submit","LOGIN"));
162
		post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
163
		//response = null;
164
		try {
165
			response = client.execute(post);
166
		} catch (Exception e) {
167
			logger.error("Unable to get Http Response for snapdeal seller portal login", e);
168
		}
169
 
170
		try {
171
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
172
		} catch (Exception e1) {
173
			logger.error("Unable to read Http Response for snapdeal seller portal login", e1);
174
		} 
175
 
176
		try {
177
			while ((line = rd.readLine()) != null) {
178
				System.out.println(line);
179
			}
180
		} catch (Exception e) {
181
			logger.error("Unable to extract Http Response for snapdeal seller portal login", e);
182
		}
15587 manish.sha 183
	}*/
14630 manish.sha 184
 
185
	@SuppressWarnings("unchecked")
186
	public static void fetchOrders() throws IllegalStateException, IOException, JSONException{
187
		List<SnapdealOrderUnit> snapdealOrderUnitsList = new ArrayList<SnapdealOrderUnit>();
188
		Map<String, SnapdealOrderUnit> snapdealOrderUnitListMap = new HashMap<String, SnapdealOrderUnit>();
189
		Map<String, Long> pendingSkuMap = new HashMap<String, Long>();
190
		String pendingOrderSummaryUrl = "http://shipping.snapdeal.com/vendor/ONESHIP/product-shipment/pendingOrders/40?fulfillmentModelCode=ONESHIP";
15587 manish.sha 191
		String cookie = "";
14630 manish.sha 192
		HttpGet get = new HttpGet(pendingOrderSummaryUrl);
15587 manish.sha 193
		for(String key:headers.keySet())
194
			get.addHeader(key, headers.get(key));
195
		get.addHeader("Cookie","SERVERID=s1;sfJSESSIONID=2A00C6B6C929B16511E35202A4DC10EB;");
14630 manish.sha 196
		HttpResponse response = null;
197
		Gson gson = new Gson();
198
		BufferedReader rd= null;
199
		String line = "";
200
		try {
201
			response = client.execute(get);
202
		} catch (ClientProtocolException e) {
203
			e.printStackTrace();
204
		} catch (IOException e) {
205
			e.printStackTrace();
206
		}
207
 
208
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
209
 
210
		while((line=rd.readLine())!=null){
211
 
212
		}
213
 
214
		get = new HttpGet("http://shipping.snapdeal.com/json/vendor/ONESHIP/product-shipment/pendingOrders/PFF/ALL/pending");
15587 manish.sha 215
		for(String key:headers.keySet())
216
			get.addHeader(key, headers.get(key));
217
		get.addHeader("Cookie","SERVERID=s1;sfJSESSIONID=2A00C6B6C929B16511E35202A4DC10EB;");
14630 manish.sha 218
 
219
		response = null;
220
 
221
		try {
222
			response = client.execute(get);
223
		} catch (ClientProtocolException e) {
224
			e.printStackTrace();
225
		} catch (IOException e) {
226
			e.printStackTrace();
227
		}
228
 
229
 
230
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
231
 
232
		line = rd.readLine();
233
 
234
 
235
		JSONArray jsonArray = new JSONArray(line);
236
		for(int i=0; i<jsonArray.length(); i++){
237
			VendorPendingOrderSkuDetail vendorPendingSku = (VendorPendingOrderSkuDetail)gson.fromJson(jsonArray.get(i).toString(),VendorPendingOrderSkuDetail.class);
238
			pendingOrdersSkuList.add(vendorPendingSku.getVendorPendingProductOfferDisplayDTO());
239
		}
240
 
241
		for(VendorPendingProductOfferDisplayDTO vendorPendingSku : pendingOrdersSkuList){
242
			pendingSkuMap.put(vendorPendingSku.getProductCode(), (long)vendorPendingSku.getPendingQuantity());
243
		}
244
 
245
		String productCodeToParse = "";
246
		String pendingQuantityToParse = "";
247
 
248
		for(String productCode : pendingSkuMap.keySet()){
249
			productCodeToParse = productCodeToParse + productCode +",";
250
			pendingQuantityToParse = pendingQuantityToParse + pendingSkuMap.get(productCode) + ",";
251
		}
252
		productCodeToParse = productCodeToParse.substring(0,productCodeToParse.length()-1);
253
		pendingQuantityToParse = pendingQuantityToParse.substring(0,pendingQuantityToParse.length()-1);
254
 
255
		productCodeToParse= URLEncoder.encode(productCodeToParse.toString(),"UTF-8"); 
256
		pendingQuantityToParse = URLEncoder.encode(pendingQuantityToParse.toString(),"UTF-8"); 
257
 
258
		get = new HttpGet("http://shipping.snapdeal.com/vendor/ONESHIP/product-shipment/pendingOrders/PFF/fetch?statusCode=PFF&packCategory=ALL&productCode="+productCodeToParse+"&maxPackagesToFetch="+pendingQuantityToParse+"&oneshipCenter=");
15587 manish.sha 259
		for(String key:headers.keySet())
260
			get.addHeader(key, headers.get(key));
261
		get.addHeader("Cookie","SERVERID=s1;sfJSESSIONID=2A00C6B6C929B16511E35202A4DC10EB;");
14630 manish.sha 262
 
263
		response = null;
264
 
265
		try {
266
			response = client.execute(get);
267
		} catch (ClientProtocolException e) {
268
			e.printStackTrace();
269
		} catch (IOException e) {
270
			e.printStackTrace();
271
		}
272
 
273
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
274
 
275
		line = rd.readLine();
276
		String shipmentIdsToParse = "";
277
		JSONArray jsonArr = new JSONArray(line);
278
		for(int i=0; i<jsonArr.length(); i++){
279
			JSONArray jsonSubArr = jsonArr.getJSONArray(i);
280
			SnapdealOrderUnit snapdealOrderUnit = (SnapdealOrderUnit)gson.fromJson(jsonSubArr.get(0).toString(),SnapdealOrderUnit.class);
281
			snapdealOrderUnitsList.add(snapdealOrderUnit);
282
		}
283
 
284
		for(SnapdealOrderUnit orderUnit : snapdealOrderUnitsList){
285
			shipmentIdsToParse = shipmentIdsToParse + orderUnit.getSiId() + ",";
286
			snapdealOrderUnitListMap.put(orderUnit.getSlpCode()+orderUnit.getSuborderCode(), orderUnit);
287
		}
288
 
289
		get = new HttpGet("http://shipping.snapdeal.com/vendor/ONESHIP/product-shipment/invoicedetails/VENDOR_READY?selectedShipments="+shipmentIdsToParse);
15587 manish.sha 290
		for(String key:headers.keySet())
291
			get.addHeader(key, headers.get(key));
292
		get.addHeader("Cookie","SERVERID=s1;sfJSESSIONID=2A00C6B6C929B16511E35202A4DC10EB;");
14630 manish.sha 293
 
294
		response = null;
295
 
296
		try {
297
			response = client.execute(get);
298
		} catch (ClientProtocolException e) {
299
			e.printStackTrace();
300
		} catch (IOException e) {
301
			e.printStackTrace();
302
		}
303
 
304
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
305
 
306
		CSVReader csvOrdersReader = new CSVReader(rd);
307
		String[] values;
308
 
309
		int i=1;
310
 
311
		CSVWriter writer = new CSVWriter(new FileWriter("/tmp/SnapdealOrders-"+System.currentTimeMillis()+".csv", true));
312
		while ((values = csvOrdersReader.readNext()) != null) {
313
			writer.writeNext(values);
314
			if(i==1){
315
				if(values[3].equalsIgnoreCase("Reference Code") && values[4].equalsIgnoreCase("Suborder Id") 
316
						&& values[5].equalsIgnoreCase("SKU Code") && values[9].equalsIgnoreCase("Customer Name")
317
						&& values[13].equalsIgnoreCase("PIN Code") && values[14].equalsIgnoreCase("Selling Price Per Item")){
318
					System.out.println("Format Ok");
319
				}
320
				i++;
321
				continue;
322
			}
323
			SnapdealOrderUnit orderUnit = snapdealOrderUnitListMap.get(values[3]+values[4]);
324
			orderUnit.setCustomerName(values[9]);
325
			orderUnit.setShippingPincode(values[13]);
326
			if(!orderUnit.getSkuCode().equalsIgnoreCase(values[5])){
327
				orderUnit.setSkuCode(values[5]);
328
			}
329
			if(orderUnit.getPrice()!=Integer.parseInt(values[14])){
330
				orderUnit.setPrice(Integer.parseInt(values[14]));
331
			}
332
			snapdealOrderUnitListMap.put(values[3]+values[4], orderUnit);
333
			i++;
334
		}
335
		writer.close();
336
 
337
		snapdealOrderUnitsList.removeAll(snapdealOrderUnitsList);
338
		snapdealOrderUnitsList.addAll(snapdealOrderUnitListMap.values());
339
 
340
		for(SnapdealOrderUnit orderUnit : snapdealOrderUnitsList){
341
			System.out.print(orderUnit.getSuborderCode()+" "+ orderUnit.getSlpCode()+" "+orderUnit.getCustomerName() +" "+ orderUnit.getShippingPincode()+" ");
342
			System.out.println(orderUnit.getOrderCreatedDateString() +" "+ new Date(orderUnit.getProductSoldDate())+" "+ orderUnit.getProductName());
343
		}
344
		processSnapdealOrders(snapdealOrderUnitsList);
345
	}
346
	public static void main(String[] args) {
347
		try {
15587 manish.sha 348
			//handleLogin();
14630 manish.sha 349
			fetchOrders();
350
		} catch (ClientProtocolException e2) {
351
			System.out.println("Handle login failed");
352
			e2.printStackTrace();
353
		} catch (IOException e2) {
354
			System.out.println("Handle login failed");
355
			e2.printStackTrace();
356
		} catch (IllegalStateException e) {
357
			e.printStackTrace();
358
		} catch (JSONException e) {
359
			e.printStackTrace();
360
		}
361
	}
362
 
363
	public static void processSnapdealOrders(List<SnapdealOrderUnit> snapdealOrderUnitsList){
364
		SourceDetail sourceDetail = null;
365
		User user = null;
366
		TransactionClient tsc = null;
367
		try {
368
			tsc = new TransactionClient();
369
			sourceDetail = tsc.getClient().getSourceDetail(SNAPDEAL_SOURCE_ID);
370
		} catch (Exception e) {
371
			logger.error("Unable to establish connection to the transaction service while getting Snapdeal Source Detail ", e);
372
		}
373
		try {   
374
			in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
375
			user = userClient.getUserByEmail(sourceDetail.getEmail());
376
		} catch (Exception e) {
377
			logger.error("Unable to establish connection to the User service ", e);
378
		}
379
		int duplicate_orders = 0;
380
		int new_orders = 0;
381
		int processed_orders = 0;
382
		StringBuffer sb = new StringBuffer();
383
		LineItem lineItem = null;
384
		CatalogService.Client catalogClient = null;
385
		SnapdealItem snapdealItem = null;
386
		double SellingPrice = 0;
387
		long sku;
388
		String subOrderId;
389
		Client transaction_client = null;
390
		try {
391
			transaction_client = tsc.getClient();
392
		} catch (Exception e2) {
393
			e2.printStackTrace();
394
		}
395
 
396
		for(SnapdealOrderUnit snapdealOrderUnit : snapdealOrderUnitsList){
397
			subOrderId = snapdealOrderUnit.getSuborderCode();
398
 
399
			boolean flag = false;
400
			try {
401
				if(!transaction_client.isAlive()){
402
					transaction_client = tsc.getClient();
403
				}
404
			} catch (TException e1) {
405
				e1.printStackTrace();
406
			}
407
 
408
			try {
409
				flag = transaction_client.snapdealOrderExists(subOrderId.trim(), snapdealOrderUnit.getSlpCode().trim());
410
			} catch (TException e2) {
411
				try {
412
					flag = new TransactionClient().getClient().snapdealOrderExists(subOrderId.trim(), snapdealOrderUnit.getSlpCode().trim());
413
				} catch (TTransportException e) {
414
					logger.error("Problem with Transaction service " + subOrderId);
415
					e.printStackTrace();
416
					continue;
417
				} catch (TException e) {
418
					logger.error("Problem with Transaction service " + subOrderId);
419
					e.printStackTrace();
420
					continue;
421
 
422
				}
423
			}
424
 
425
			if(flag) {
426
				logger.error("Snapdeal suborder id exists " + subOrderId);
427
				duplicate_orders++;
428
				continue;
429
			}
430
			new_orders++;
431
 
432
			Transaction txn = new Transaction();
433
			txn.setShoppingCartid(user.getActiveCartId());
434
			txn.setCustomer_id(user.getUserId());
435
			System.out.println("User Id is " + user.getUserId());
436
			txn.setCreatedOn(new Date().getTime());
437
			txn.setTransactionStatus(TransactionStatus.INIT);
438
			txn.setStatusDescription("Order for Snapdeal ");
439
 
440
			List<in.shop2020.model.v1.order.Order> orderlist = new ArrayList<in.shop2020.model.v1.order.Order>();
441
			try {
442
				flag = true;
443
				while(flag){
444
					try{
445
						catalogClient =  new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
446
						snapdealItem = catalogClient.getSnapdealItembySkuAtSnapdeal(snapdealOrderUnit.getSkuCode());
447
						flag=false;
448
					}
449
					catch (TException e) {
450
					}
451
				}
452
				if(snapdealItem.getItem_id()!=0){
453
					sku = snapdealItem.getItem_id();
454
				}
455
				else{
456
					sb.append(subOrderId +" "+"SKU not found "+"\n");
457
					continue;
458
				}
459
				if(snapdealItem.getExceptionPrice()!=0 && snapdealItem.getItem_id()!=0 && (snapdealOrderUnit.getPrice() <  snapdealItem.getExceptionPrice())){
460
					SellingPrice = snapdealItem.getExceptionPrice();
461
				}
462
				else{
463
					SellingPrice = snapdealOrderUnit.getPrice();
464
				}
465
				try{
466
					lineItem = createLineItem(sku,SellingPrice);
467
				}
468
				catch (TException e) {
469
					logger.error("Unable to create order for suborderid  " + snapdealOrderUnit.getSuborderCode() , e);
470
					e.printStackTrace();
471
					sb.append(snapdealOrderUnit.getSuborderCode() + " " + "Exception while creating lineitem" + "\n");
472
					continue;
473
				}
474
				if(lineItem == null){
475
					sb.append(snapdealOrderUnit.getSuborderCode() +" "+"SKU not found "+"\n");
476
					continue;
477
				}
478
				lineItem.setExtra_info("SubOrderId = " + snapdealOrderUnit.getSuborderCode() + " ReferenceCode = " + snapdealOrderUnit.getSlpCode());
479
			} catch (CatalogServiceException e) {
480
				logger.error("Unable to create order for suborderid  " + snapdealOrderUnit.getSuborderCode() , e);
481
				e.printStackTrace();
482
				sb.append(snapdealOrderUnit.getSuborderCode() + " " + "Problem with catalog service" + "\n");
483
				continue;
484
			}
485
 
486
			in.shop2020.model.v1.order.Order t_order = new in.shop2020.model.v1.order.Order();
487
			t_order.setCustomer_id(user.getUserId());
488
			t_order.setCustomer_email(sourceDetail.getEmail());
489
			t_order.setCustomer_name(snapdealOrderUnit.getCustomerName());
490
			t_order.setCustomer_address1("");
491
			t_order.setCustomer_address2("");
492
			t_order.setCustomer_city(snapdealOrderUnit.getShippingCity());
493
			t_order.setCustomer_mobilenumber("+91-9999999999");
494
			t_order.setCustomer_state(snapdealOrderUnit.getShippingState());
495
			t_order.setCustomer_pincode(snapdealOrderUnit.getShippingPincode());
496
			t_order.setTotal_amount(SellingPrice);            
497
			t_order.setTotal_weight(lineItem.getTotal_weight());
498
			t_order.setLineitems(Collections.singletonList(lineItem));            
499
			t_order.setStatus(OrderStatus.PAYMENT_PENDING);
500
			t_order.setStatusDescription("Payment Pending");
501
			t_order.setCreated_timestamp(new Date().getTime());
502
			t_order.setOrderType(OrderType.B2C);
503
			t_order.setCod(false);
504
			System.out.println("t order created");
505
			Date snapdealTxnDate = new Date(snapdealOrderUnit.getProductSoldDate());
506
 
507
			try {
508
				Date shipDate = new Date(snapdealTxnDate.getTime()+172800000l);
509
				Calendar time = Calendar.getInstance();
510
				t_order.setPromised_shipping_time(shipDate.getTime());
511
				t_order.setExpected_shipping_time(shipDate.getTime());
512
				time.add(Calendar.DAY_OF_MONTH, 4);
513
				t_order.setPromised_delivery_time(time.getTimeInMillis());
514
				t_order.setExpected_delivery_time(time.getTimeInMillis());
515
				System.out.println("Dates set in transaction");
516
			} catch(Exception e) {	
517
				logger.error("Error in updating Shipping or Delivery Time for suborderid  " + snapdealOrderUnit.getSuborderCode());
518
				sb.append(snapdealOrderUnit.getSuborderCode() + " Could not update delivery time" + " " + "\n");
519
				continue;
520
			}
521
			InventoryService.Client inventoryClient = null;
522
			Warehouse fulfillmentWarehouse= null;
523
			try {
524
				inventoryClient = new InventoryClient().getClient();
525
				if(snapdealItem.getItem_id()!=0 && snapdealItem.getWarehouseId()!=0) {
526
					fulfillmentWarehouse = inventoryClient.getWarehouse(snapdealItem.getWarehouseId());
527
				} else {
528
					List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(sku, 1);
529
					fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
530
					if(fulfillmentWarehouse.getStateId()!=0){
531
						fulfillmentWarehouse = inventoryClient.getWarehouse(7);
532
					}
533
				}
534
				t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
535
				long billingWarehouseId = 0;
536
				if(fulfillmentWarehouse.getBillingWarehouseId()== 0) {
537
					inventoryClient = new InventoryClient().getClient();
538
					List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, fulfillmentWarehouse.getVendor().getId(), 0, 0);
539
					for(Warehouse warehouse : warehouses) {
540
						if(warehouse.getBillingWarehouseId()!=0) {
541
							billingWarehouseId = warehouse.getBillingWarehouseId();
542
							break;
543
						}
544
					}
545
				}else {
546
					billingWarehouseId = fulfillmentWarehouse.getBillingWarehouseId();
547
				}
548
 
549
				//logger.info("Billing warehouse id for suborderid  " + snapdealOrderUnit.getSuborderCode() + " is " + fulfillmentWarehouse.getBillingWarehouseId());
550
				t_order.setWarehouse_id(billingWarehouseId);
551
				VendorItemPricing vendorItemPricing = new VendorItemPricing();
552
				if(fulfillmentWarehouse.getId()==7) {
553
					Item item = new CatalogClient().getClient().getItem(lineItem.getItem_id());
554
					vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), item.getPreferredVendor());
555
				} else {
556
					vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), fulfillmentWarehouse.getVendor().getId());
557
				}
558
 
559
				t_order.getLineitems().get(0).setTransfer_price(vendorItemPricing.getTransferPrice());
560
				t_order.getLineitems().get(0).setNlc(vendorItemPricing.getNlc());
561
			} catch (InventoryServiceException e) {
562
				logger.error("Error connecting inventory service for suborderid  " + snapdealOrderUnit.getSuborderCode() , e);
563
				sb.append(snapdealOrderUnit.getSuborderCode() + " Inventory Service Exception" + " " + "\n");
564
				continue;
565
			} catch (TTransportException e) {
566
				logger.error("Transport Exception with Inventory Service for suborderid  " + snapdealOrderUnit.getSuborderCode() , e);
567
				sb.append(snapdealOrderUnit.getSuborderCode() + " Transport Exception with Inventory Service" + " " + "\n");
568
				continue;
569
			} catch (TException e) {
570
				logger.error("Exception with Inventory Service for suborderid  " + snapdealOrderUnit.getSuborderCode() , e);
571
				sb.append(snapdealOrderUnit.getSuborderCode() + " Exception in Inventory Service" + " " + "\n");
572
				continue;
573
			} catch (CatalogServiceException e) {
574
				logger.error("Exception with Catalog Service for suborderid  " + snapdealOrderUnit.getSuborderCode() + " while getting item " + lineItem.getItem_id(), e);
575
				sb.append(snapdealOrderUnit.getSuborderCode() + " Exception in Catalog Service" + " " + "\n");
576
				continue;
577
			}
578
			t_order.setLogistics_provider_id(44);
579
			t_order.setTotal_amount(SellingPrice);
580
			t_order.setOrderType(OrderType.B2C);
581
			t_order.setSource(SNAPDEAL_SOURCE_ID);
582
			t_order.setOrderType(OrderType.B2C);
583
			orderlist.add(t_order);
584
			txn.setOrders(orderlist);
585
			String referenceCode = snapdealOrderUnit.getSlpCode();
586
			String productName = snapdealOrderUnit.getProductName();
587
			try {
588
				transactionId =  String.valueOf(transaction_client.createTransaction(txn));
589
			} catch (TransactionServiceException e) {
590
				logger.error(snapdealOrderUnit.getSuborderCode() + " Could not create transaction " , e);
591
				sb.append(snapdealOrderUnit.getSuborderCode() + " Could not create transaction" +"\n");
592
				continue;
593
			} catch (TException e) {
594
				logger.error("Problem with transaction service while creating transaction", e);
595
				sb.append(snapdealOrderUnit.getSuborderCode() + " Transaction Service Exception could not create transaction" +"\n");
596
				continue;
597
			}
598
			try{
599
				paymentId = createPayment(user, (new Long(subOrderId)).toString(),lineItem.getTotal_price());
600
			}
601
			catch (NumberFormatException e) {
602
				logger.error("Could not create payment",e);
603
				sb.append(snapdealOrderUnit.getSuborderCode() + " Could not create payment");
604
				e.printStackTrace();
605
				continue;
606
			} catch (PaymentException e) {
607
				logger.error("Could not create payment payment exception",e);
608
				sb.append(snapdealOrderUnit.getSuborderCode() + " Could not create payment Payment exception");
609
				e.printStackTrace();
610
				continue;
611
			} catch (TException e) {
612
				logger.error("Could not create payment thrift exception",e);
613
				sb.append(snapdealOrderUnit.getSuborderCode() + " Could not create payment Thrift exception");
614
				e.printStackTrace();
615
				continue;
616
			}
617
			Transaction transaction = null;
618
			try {
619
				transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
620
			} catch (NumberFormatException e) {
621
				logger.error("Problem parsing transaction id " + transactionId);
622
				sb.append(snapdealOrderUnit.getSuborderCode() + " Problem parsing transaction id "+ transactionId +"\n");
623
				e.printStackTrace();
624
				continue;
625
			} catch (TransactionServiceException e) {
626
				logger.error("Problem getting transaction from service transaction id " + transactionId);
627
				sb.append(snapdealOrderUnit.getSuborderCode() + " Problem getting transaction id "+ transactionId +"\n");
628
				e.printStackTrace();
629
				continue;
630
			} catch (TException e) {
631
				logger.error("Problem with transaction service while getting transaction id " + transactionId);
632
				sb.append(snapdealOrderUnit.getSuborderCode() + " Problem with transaction service while getting transaction id "+ transactionId +"\n");
633
				e.printStackTrace();
634
				continue;
635
			}
636
			in.shop2020.model.v1.order.Order snapdealorder = transaction.getOrders().get(0);
637
			try {
638
				inventoryClient.reserveItemInWarehouse(lineItem.getItem_id(), fulfillmentWarehouse.getId(), 1, 
639
						snapdealorder.getId(), snapdealorder.getCreated_timestamp(), snapdealorder.getPromised_shipping_time(), snapdealorder.getLineitems().get(0).getQuantity());
640
			} catch (InventoryServiceException e1) {
641
				logger.error("Problem while reserving item in inventory service" + snapdealorder.getId());
642
				sb.append(snapdealOrderUnit.getSuborderCode() + " Could not reserve inventory for sku "+ sku +"\n");
643
				continue;
644
			} catch (TException e1) {
645
				logger.error("Problem with inventory service" + snapdealorder.getId());
646
				sb.append(snapdealOrderUnit.getSuborderCode() + " Problem with inventory service while reserving inventory for sku "+ sku +"\n");
647
				continue;
648
			}
649
			SnapdealOrder snapdealOrder = new SnapdealOrder();
650
			snapdealOrder.setOrderId(snapdealorder.getId());
651
			System.out.println("Sub Order Id... "+snapdealOrderUnit.getSuborderCode());
652
			snapdealOrder.setSubOrderId(snapdealOrderUnit.getSuborderCode());
653
			snapdealOrder.setReferenceCode(referenceCode);
654
			snapdealOrder.setProductName(productName);
655
			snapdealOrder.setSnapdealTxnDate(snapdealTxnDate.getTime());
656
			snapdealOrder.setListingPrice(snapdealOrderUnit.getPrice());
657
			snapdealOrder.setMaxNlc(snapdealItem.getMaxNlc());
658
			try {
659
				transaction_client.createSnapdealOrder(snapdealOrder);
660
				new PaymentClient().getClient().updatePaymentDetails(paymentId, null, null, null, null, null, null, subOrderId, null, PaymentStatus.SUCCESS, null, null);
661
 
662
			} catch (TException e) {
663
				logger.error("Could not create Snapdeal Order");
664
				sb.append(snapdealOrderUnit.getSuborderCode() + " Could not create snapdeal order"+"\n");
665
			} catch (PaymentException e) {
666
				logger.error("Could not update payment for Snapdeal Order");
667
				sb.append(snapdealOrderUnit.getSuborderCode() + " Could not update payment for snapdeal order"+"\n");
668
			}
669
			processed_orders++;
670
		}
671
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
672
		Calendar cal=GregorianCalendar.getInstance();
673
		String emailFromAddress = "adwords@shop2020.in";
674
		String password = "adwords_shop2020";
675
		GmailUtils mailer = new GmailUtils();
676
		//String sendTo[] = new String[]{"manish.sharma@shop2020.in"};
677
		String sendTo[] = new String[]{ "sandeep.sachdeva@shop2020.in", "manish.sharma@shop2020.in", "rajneesh.arora@shop2020.in",
678
				"khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
14631 manish.sha 679
				"yukti.jain@shop2020.in","yatin.singh@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in","anikendra.das@shop2020.in"};
14630 manish.sha 680
		try {
681
			if(new_orders==processed_orders && new_orders > 0){
682
				String emailSubjectTxt = "Snapdeal Orders Created Successfully "+sdf.format(cal.getTime());
683
				String text = "Total Orders Received : " + ( new_orders + duplicate_orders ) + "\n" + 
684
				"Orders Already Existing : " + duplicate_orders + "\n" +
685
				"Processed Orders : " + processed_orders + "\n" +
686
				"Failed Orders : " + (new_orders - processed_orders);
687
				mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
688
			}
689
			else if(new_orders > 0){
690
				String emailSubjectTxt = "Snapdeal Orders Failed while creation "+sdf.format(cal.getTime());
691
				String text = "Total Orders Received : " + ( new_orders + duplicate_orders ) + "\n" + 
692
				"Orders Already Existing : " + duplicate_orders + "\n" +
693
				"Processed Orders : " + processed_orders + "\n" +
694
				"Failed Orders : " + (new_orders - processed_orders) + "\n"+ "\n" +
695
				sb.toString();
696
				mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
697
			}
698
			else{
699
				String emailSubjectTxt = "No new Snapdeal Orders " + sdf.format(cal.getTime());
700
				String text = "Total Orders Received : " + ( new_orders + duplicate_orders ) + "\n" + 
701
				"Orders Already Existing : " + duplicate_orders + "\n" +
702
				"Processed Orders : " + processed_orders + "\n" +
703
				"Failed Orders : " + (new_orders - processed_orders) + "\n"+ "\n" +
704
				sb.toString();
705
				mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
706
			}
707
		}
708
		catch (Exception e) {
709
			e.printStackTrace();
710
		}
711
	}
712
 
713
	public static long createPayment(User user, String subOrderId, double amount) throws NumberFormatException, PaymentException, TException {
714
		in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
715
		return client.createPayment(user.getUserId(), amount, SNAPDEAL_GATEWAY_ID, Long.valueOf(transactionId), false);
716
 
717
	}   
718
 
719
	public static LineItem createLineItem(long itemId, double amount) throws CatalogServiceException, TException {
720
		LineItem lineItem = new LineItem();
721
		CatalogService.Client catalogClient = new CatalogClient().getClient();
722
		Item item = catalogClient.getItem(itemId);
723
		if(item.getId()==0){
724
			//in case item id is incorrect..
725
			return null;
726
		}
727
 
728
		lineItem.setProductGroup(item.getProductGroup());
729
		lineItem.setBrand(item.getBrand());
730
		lineItem.setModel_number(item.getModelNumber());
731
		lineItem.setModel_name(item.getModelName());
732
		lineItem.setExtra_info(item.getFeatureDescription());
733
		lineItem.setQuantity(1);
734
		lineItem.setItem_id(item.getId());
735
		lineItem.setUnit_weight(item.getWeight());
736
		lineItem.setTotal_weight(item.getWeight());
737
		lineItem.setUnit_price(amount);
738
		lineItem.setTotal_price(amount);
739
 
740
		if (item.getColor() == null || "NA".equals(item.getColor())) {
741
			lineItem.setColor("");
742
		} else {
743
			lineItem.setColor(item.getColor());
744
		}
745
		return lineItem;
746
	}
747
}