Subversion Repositories SmartDukaan

Rev

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