Subversion Repositories SmartDukaan

Rev

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