Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
12747 manish.sha 1
package in.shop2020.serving.services;
2
 
3
import in.shop2020.model.v1.catalog.CatalogService;
4
import in.shop2020.model.v1.catalog.CatalogServiceException;
5
import in.shop2020.model.v1.catalog.FlipkartItem;
6
import in.shop2020.model.v1.catalog.Item;
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.FlipkartOrder;
14
import in.shop2020.model.v1.order.LineItem;
15
import in.shop2020.model.v1.order.OrderStatus;
16
import in.shop2020.model.v1.order.OrderType;
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.Order;
26
import in.shop2020.serving.model.OrderItems;
27
import in.shop2020.thrift.clients.CatalogClient;
28
import in.shop2020.thrift.clients.InventoryClient;
29
import in.shop2020.thrift.clients.PaymentClient;
30
import in.shop2020.thrift.clients.TransactionClient;
31
import in.shop2020.thrift.clients.UserClient;
32
import in.shop2020.utils.GmailUtils;
33
import java.io.BufferedReader;
34
import java.io.File;
35
import java.io.FileInputStream;
36
import java.io.FileReader;
37
import java.io.IOException;
38
import java.io.InputStreamReader;
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.List;
47
import org.apache.http.client.HttpClient;
48
import org.apache.http.client.entity.UrlEncodedFormEntity;
49
import org.apache.http.client.methods.HttpGet;
50
import org.apache.http.client.methods.HttpPost;
51
import org.apache.http.impl.client.DefaultHttpClient;
52
import org.apache.http.message.BasicNameValuePair;
53
import org.apache.http.HttpResponse;
54
import org.apache.http.NameValuePair;
55
import org.apache.thrift.TException;
56
import org.apache.thrift.transport.TTransportException;
57
import org.slf4j.Logger;
58
import org.slf4j.LoggerFactory;
59
import com.google.gson.Gson;
60
 
61
 
62
 
63
public class FetchNewFlipkartOrdersNew {
64
	private static final long FLIPKART_SOURCE_ID = 8;
65
	private static final int FLIPKART_GATEWAY_ID = 17;
66
	private static final int FLIPKART_LOGISTICS_ID = 19;
67
	private static String transactionId;
68
 
69
	private static Logger logger = LoggerFactory.getLogger(FetchNewFlipkartOrdersNew .class);
70
	private static long paymentId;	
71
	public static void main(String[] args) throws  CatalogServiceException, TException, IOException {
72
 
12750 manish.sha 73
		File fileToCreate = new File("/tmp/NewOrders.txt");
12747 manish.sha 74
		try{
75
			BufferedReader rd = new BufferedReader(new FileReader(fileToCreate));
76
			String line;
77
 
78
			Gson gson;
79
			List<Order> orders = new ArrayList<Order>(); 
80
			OrderItems new_orders;
81
			while((line = rd.readLine())!=null){
82
				gson = new Gson();
83
				new_orders = (OrderItems) gson.fromJson(line, OrderItems.class);
84
				if(new_orders.getOrder_items().size()>0){
85
					orders.addAll(new_orders.getOrder_items());
86
				}
87
				else{
88
					break;
89
				}
90
			}
91
			for(Order order:orders){
92
				System.out.println("Order  " + order.getExternalId() +" "+order.getOrderItemId() + " : "+ order.getStatus() + " "+order.getStatusDateMessage() + " "
93
						+ order.getStatusLabel() + " " + order.getPickup_by_date() + " "+ order.getTrackingId());
94
				/*if(order.getFreebie_items()!=null && order.getFreebie_items().size()>0){
95
					System.out.println("Freebie Item ID :"+order.getFreebie_items().get(0).getSku());
96
				}*/
97
			}
98
			processOrders(orders);
99
		} catch (IOException e) {
100
			e.printStackTrace();
101
		}
102
	}
103
 
104
	public static void processOrders(List<Order> orders) throws IOException, CatalogServiceException, TException{
105
		logger.info("Before Processing orders ");
106
		StringBuffer sb = new StringBuffer();
107
		String order_string = "";
108
		User user = null;
109
		TransactionClient tsc = null;
110
		SourceDetail sourceDetail = null;
111
		logger.info("Before Fetching sourcedetail");
112
		try {
113
			tsc = new TransactionClient();
114
			sourceDetail = tsc.getClient().getSourceDetail(FLIPKART_SOURCE_ID);
115
			logger.info("Flipkart sourcedetail " + sourceDetail.getEmail() + " " + sourceDetail.getName());
116
		} catch (Exception e) {
117
			logger.error("Unable to establish connection to the transaction service while getting Flipkart Source Detail ", e);
118
		}
119
		try {   
120
			in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
121
			logger.info("Before Fetching User by Email");
122
			user = userClient.getUserByEmail(sourceDetail.getEmail());
123
			logger.info("User is " + user.getEmail());
124
		} catch (Exception e) {
125
			logger.error("Unable to establish connection to the User service ", e);
126
		}
127
		logger.info("Before iterating orders in file");
128
		FlipkartItem flipkartItem;
129
		String orderId,subOrderId,create_date,ship_date = null,skuAtFlipkart;
130
		long sku = 0;
131
		int total_orders = 0;
132
		int duplicate_orders = 0;
133
		int orders_processed = 0;
134
		int not_approved = 0;
135
		for(Order order : orders){
136
			String status = "";
137
			boolean isHold = false;
138
			total_orders++;
139
			if(order.getExternalId().length()==0 || order.getOrderItemId().length()==0 ){
140
				sb.append(" Could not parse order id " + order.getExternalId()+ " " + order.getExternalId() + "\n");
141
				continue;
142
			}
143
			else{
144
				logger.info("Processing Order  " +  order.getExternalId() + " " + order.getOrderItemId());
145
				orderId = order.getExternalId();
146
				subOrderId = order.getOrderItemId();
147
			}
148
 
149
			if(order.getCreatedDate()!=null){
150
				create_date = order.getCreatedDate()+" "+order.getCreatedTime();
151
			}
152
			else{
153
				sb.append(orderId+" "+subOrderId + " Could not parse order date" +"\n");
154
				logger.info(orderId+" "+subOrderId + " Could not parse order date");
155
				continue;
156
			}
157
 
158
			if(order.getService_profile()!=null && "NON_FBF".equalsIgnoreCase(order.getService_profile())){
159
				String fulfillByUs = order.getService_profile();
160
			} else {
161
				sb.append(orderId+" "+subOrderId + " Could not parse FBF Condition" +"\n");
162
				logger.info(orderId+" "+subOrderId + " Could not parse FBF Condition");
163
				continue;
164
			}
165
			if(order.getPickup_by_date()!=null){
166
				ship_date = order.getPickup_by_date();
167
			}
168
			if(order.getSku().equals("")){
169
				sb.append(orderId+" "+subOrderId + " Could not parse sku" +"\n");
170
				logger.info(orderId+" "+subOrderId + " Could not parse sku");
171
				continue;
172
			}
173
			else{
174
				skuAtFlipkart =  order.getSku();
175
				logger.info(orderId+" "+subOrderId + " Processing  sku " + skuAtFlipkart);
176
			}
177
			if(order.getStatusLabel().length()!=0 && (order.getStatusLabel().equalsIgnoreCase("Approved") || order.getStatusLabel().equalsIgnoreCase("On hold") || order.getStatusLabel().equalsIgnoreCase("confirmed"))){
178
				status = order.getStatus();	
179
				if("on_hold".equalsIgnoreCase(status)){
180
					isHold = true;
181
				}
182
			}
183
			else{
184
				sb.append(orderId+" "+subOrderId + " Could not parse status " + "\n");
185
				logger.info(orderId+" "+subOrderId + " Could not parse status " +"\n");
186
				continue;
187
			}
188
			double unitSellingPrice,shippingPrice,octroiFee,emiFee;
189
			if(order.getListPrice()!=0 ){
190
				if(order.getListPrice() > 0){
191
					unitSellingPrice =  order.getListPrice();
192
				}
193
				else{
194
					sb.append(orderId+" "+subOrderId + " Unit Price set to 0 " +"\n");
195
					logger.info(orderId+" "+subOrderId + " Unit Price set to 0 " +"\n");
196
					continue;
197
				}
198
			}
199
			else{
200
				sb.append(orderId+" "+subOrderId + " Unit Price not set " +"\n");
201
				logger.info(orderId+" "+subOrderId + " Unit Price not set " +"\n");
202
				continue;
203
			}
204
			if(order.getShippingFees() > 0){
205
				shippingPrice  =  order.getShippingFees();
206
				//sb.append(orderId+" "+subOrderId + " Shipping Fee :"+ shippingPrice +"\n");
207
				logger.info(orderId+" "+subOrderId + " Shipping Fee :"+ shippingPrice +"\n");
208
 
209
			}
210
			else{
211
				shippingPrice=0;
212
			}
213
			if(order.getOctroi()!=0){
214
				octroiFee =  order.getOctroi();
215
				if(octroiFee >0){
216
					//sb.append(orderId+" "+subOrderId + " OctroiFee :"+ octroiFee +"\n");
217
					logger.info(orderId+" "+subOrderId + " OctroiFee :"+ octroiFee +"\n");
218
				}
219
			}
220
			else{
221
				octroiFee=0;
222
			}
223
			if(order.getEmi()!=0){
224
				emiFee =  order.getEmi();
225
				if(emiFee >0){
226
					//sb.append(orderId+" "+subOrderId + " EMI :"+ emiFee +"\n");
227
					logger.info(orderId+" "+subOrderId + " EMI :"+ emiFee +"\n");
228
				}
229
			}
230
			else{
231
				emiFee = 0;
232
			}
233
			int quantity;
234
			if(order.getQuantity()!=0){
235
				quantity = order.getQuantity();
236
				if(quantity > 1){
237
					//sb.append(orderId+" "+subOrderId + " Quantity > 1 " +quantity+"\n");
238
					logger.info(orderId+" "+subOrderId + " Quantity > 1 " +quantity+"\n");
239
				}
240
				else{
241
					if(quantity==0){
242
						sb.append(orderId+" "+subOrderId + " Quantity not set " +quantity+"\n");
243
						logger.info(orderId+" "+subOrderId + " Quantity not set " +quantity+"\n");
244
						continue;
245
					}
246
				}
247
			}
248
			else{
249
				sb.append(orderId+" "+subOrderId + " Quantity not set " + "0" +"\n");
250
				logger.info(orderId+" "+subOrderId + " Quantity not set " +"0"+"\n");
251
				continue;
252
			}
253
			double totalsellingPrice; 
254
			if(order.getTotalPrice()!=0){
255
				totalsellingPrice= order.getTotalPrice();
256
				if(totalsellingPrice==0){
257
					sb.append(orderId+" "+subOrderId + " Total Selling Price set to 0 " +"\n");
258
					logger.info(orderId+" "+subOrderId + " Total Selling Price set to 0 " +"\n");
259
					continue;
260
				}
261
			}
262
			else{
263
				sb.append(orderId+" "+subOrderId + " Total Selling Price not set " +"\n");
264
				logger.info(orderId+" "+subOrderId + " Total Selling Price not set " +"\n");
265
				continue;
266
			}
267
 
268
			String shipToName,addressLine1,addressLine2,city,state,pincode,buyerName="unknown";
269
			if(order.getCustomerName().length() > 0){
270
				buyerName = order.getCustomerName();
271
			}
272
			else{
273
				sb.append(orderId+" "+subOrderId + " Buyer Name not set " +"\n");
274
				logger.info(orderId+" "+subOrderId + " Buyer Name not set " +"\n");
275
			}
276
			if(order.getShippingAddressName().length() > 0){
277
				shipToName = order.getShippingAddressName();
278
			}
279
			else{
280
				sb.append(orderId+" "+subOrderId + " Ship to Name not set " +"\n");
281
				logger.info(orderId+" "+subOrderId + " Ship to Name not set " +"\n");
282
				continue;
283
			}
284
			if(buyerName.contains("unknown")){
285
				buyerName = shipToName;
286
			}
287
			if(order.getShippingAddressLine1()!=null && order.getShippingAddressLine1().length() > 0){
288
				addressLine1 = order.getShippingAddressLine1();
289
			}
290
			else{
291
				addressLine1 ="";
292
			}
293
			if(order.getShippingAddressLine2()!=null && order.getShippingAddressLine2().length() > 0){
294
				addressLine2 = order.getShippingAddressLine2();
295
			}
296
			else{
297
				addressLine2 ="";
298
			}
299
			if(order.getShippingAddressCity()!=null && order.getShippingAddressCity().length()>0){
300
				city = order.getShippingAddressCity();
301
			}
302
			else{
303
				sb.append(orderId+" "+subOrderId + " City not set " +"\n");
304
				logger.info(orderId+" "+subOrderId + " City not set " +"\n");
305
				continue;
306
			}
307
			if(order.getShippingAddressState().length()>0){
308
				state = order.getShippingAddressState();
309
			}
310
			else{
311
				sb.append(orderId+" "+subOrderId + " State not set " +"\n");
312
				logger.info(orderId+" "+subOrderId + " State not set " +"\n");
313
				continue;
314
			}
315
			if(order.getShippingAddressPincode().length()>0){
316
				pincode = order.getShippingAddressPincode();
317
			}
318
			else{
319
				sb.append(orderId+" "+subOrderId + " Pincode not set " +"\n");
320
				logger.info(orderId+" "+subOrderId + " Pincode not set " +"\n");
321
				continue;
322
			}
323
			int sla; 
324
			if(order.getSla()>0){
325
				sla = order.getSla();
326
			}
327
			else{
328
				sb.append(orderId+" "+subOrderId + " Ship to date not available " +"\n");
329
				logger.info(orderId+" "+subOrderId + " Ship to date not available " +"\n");
330
				continue;
331
			}
332
			//String shipByDate = nextLine[26];
333
			SimpleDateFormat createDateFormatter = new SimpleDateFormat("MMM dd, yyyy hh:mm aaa");
334
			SimpleDateFormat shipDateFormatter = new SimpleDateFormat("MMM dd, yyyy");
335
			Date flipkartTxnDate = null;
336
			Date shipByDate = null;
337
			try {
338
				flipkartTxnDate = createDateFormatter.parse(create_date);
339
			} catch (ParseException e) {
340
				logger.error(orderId+" "+subOrderId + " Could not parse flipkart order date from file " , e);
341
				sb.append(orderId+" "+subOrderId + " Could not parse order date" +"\n");
342
				continue;
343
			}
344
			if(ship_date!=null){
345
				try {
346
					shipByDate = shipDateFormatter.parse(ship_date);
347
				} catch (ParseException e) {
348
					logger.error(orderId+" "+subOrderId + " ship date " , e);
349
					sb.append(orderId+" "+subOrderId + "cannot parse ship date" +"\n");
350
					continue;
351
				}
352
			}
353
			Client transaction_client = null;
354
			try {
355
				transaction_client = new TransactionClient().getClient();
356
				boolean flag = false;
357
				try{
358
					flag = transaction_client.flipkartOrderExists(orderId,subOrderId);
359
				}
360
				catch(Exception e){
361
					continue;
362
				}
363
				if(flag) {
364
					if(shipByDate!=null && order.getTrackingId()!=null){
365
						transaction_client.updateFlipkartOrderDatesAndAWB(orderId, subOrderId, shipByDate.getTime(), order.getTrackingId());
366
						logger.error("Order exists updating info " + "id : " + orderId + " suborder id : " + subOrderId);
367
						//sb.append("Order exists updating info " + orderId+" "+subOrderId+"\n");
368
					}
369
					else{
370
						logger.error("Flipkart order exists " + "id : " + orderId + " suborder id : " + subOrderId);
371
						//sb.append("Flipkart order exists " + orderId+" "+subOrderId+"\n");
372
					}
373
					duplicate_orders++;
374
					continue;
375
				}
376
 
377
			} catch (TTransportException e1) {
378
				logger.error("Problem with Transaction service " , e1);
379
				e1.printStackTrace();
380
				continue;
381
			} catch (TException e) {
382
				logger.error("Problem.. thrift exception with Transaction service " , e);
383
				e.printStackTrace();
384
				continue;
385
			}
12749 manish.sha 386
			flipkartItem = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient().getFlipkartItemBySkyAtFlipkart(skuAtFlipkart);
387
			//flipkartItem = new CatalogClient().getClient().getFlipkartItemBySkyAtFlipkart(skuAtFlipkart);
12747 manish.sha 388
			sku = flipkartItem.getItem_id();
389
			if(sku==0){
390
				System.out.println("SKU Mapping doesnt exists " + skuAtFlipkart);
391
				sb.append(orderId + " "+ subOrderId  + " SKU Mapping doesnt exist" + " " +skuAtFlipkart+ "\n");
392
				continue;
393
			}
394
 
395
			Transaction txn = new Transaction();
396
			txn.setShoppingCartid(user.getActiveCartId());
397
			txn.setCustomer_id(user.getUserId());
398
			System.out.println("User Id is " + user.getUserId());
399
			txn.setCreatedOn(new Date().getTime());
400
			txn.setTransactionStatus(TransactionStatus.INIT);
401
			txn.setStatusDescription("Order for flipkart ");
402
			List<in.shop2020.model.v1.order.Order> orderlist = new ArrayList<in.shop2020.model.v1.order.Order>();
403
			double total_price=0;
404
			InventoryService.Client inventoryClient = null;
405
			Warehouse fulfillmentWarehouse= null;
406
			LineItem lineItem = null;
407
			lineItem = createLineItem(sku,unitSellingPrice,quantity);
408
			logger.info(orderId+" "+subOrderId + "sku and Price " + sku + " " + unitSellingPrice);
409
			lineItem.setExtra_info("flipkartOrderId = " + orderId + " flipkartsubOrderId = " + subOrderId);
410
			in.shop2020.model.v1.order.Order t_order = new in.shop2020.model.v1.order.Order();
411
			t_order.setCustomer_id(user.getUserId());
412
			t_order.setCustomer_email(sourceDetail.getEmail());
413
			t_order.setCustomer_mobilenumber(order.getPhone());
414
			t_order.setCustomer_name(shipToName);
415
			t_order.setCustomer_address1(addressLine1);
416
			t_order.setCustomer_address2(addressLine2);
417
			t_order.setCustomer_city(city);
418
			t_order.setCustomer_state(state);
419
			t_order.setCustomer_pincode(pincode);
420
			t_order.setTotal_weight(lineItem.getTotal_weight());
421
			t_order.setLineitems(Collections.singletonList(lineItem));            
422
			t_order.setStatus(OrderStatus.PAYMENT_PENDING);
423
			t_order.setCreated_timestamp(new Date().getTime());
424
			t_order.setOrderType(OrderType.B2C);
425
			/*if(order.getFreebie_items().size()>0){
426
				System.out.println("Freebie found");
427
				FlipkartItem freebieItem = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient().getFlipkartItemBySkyAtFlipkart(order.getFreebie_items().get(0).getSku());
428
				if(freebieItem.getItem_id()!=0){
429
					t_order.setFreebieItemId(freebieItem.getItem_id());
430
				}
431
			}
432
			else{
433
				System.out.println("No Freebie");
434
			}*/
435
			if(isHold){
436
				t_order.setCod(true);
437
				t_order.setStatusDescription("Cod Verification Pending");
438
			} else {
439
				t_order.setStatusDescription("In Process");
440
				t_order.setCod(false);
441
			}
442
			if(shipByDate!=null){
443
				t_order.setPromised_shipping_time(shipByDate.getTime());
444
				t_order.setExpected_shipping_time(shipByDate.getTime());
445
				t_order.setPromised_delivery_time(shipByDate.getTime()+ 4*24*60*60);
446
				t_order.setExpected_delivery_time(shipByDate.getTime()+ 4*24*60*60);
447
			}
448
			else{
449
				try {
450
					Date shipDate = new Date();
451
					shipDate.setTime( flipkartTxnDate.getTime() + sla*24*60*60*1000);
452
					Calendar calendar = Calendar.getInstance();
453
					calendar.setTime(shipDate);
454
					if(calendar.get(Calendar.DAY_OF_WEEK)!=1){
455
						t_order.setPromised_shipping_time(shipDate.getTime());
456
						t_order.setExpected_shipping_time(shipDate.getTime());
457
					}
458
					else{
459
						t_order.setPromised_shipping_time(shipDate.getTime()+24*60*60*1000);
460
						t_order.setExpected_shipping_time(shipDate.getTime()+24*60*60*1000);
461
					}
462
					calendar = Calendar.getInstance();
463
					calendar.add(Calendar.DAY_OF_MONTH, 4);
464
					t_order.setPromised_delivery_time(calendar.getTimeInMillis());
465
					t_order.setExpected_delivery_time(calendar.getTimeInMillis());
466
				} catch(Exception e) {	
467
					logger.error("Error in updating Shipping or Delivery Time for suborderid  " + subOrderId);
468
					sb.append(orderId + " "+ subOrderId  + " Could not update delivery time" + " " + "\n");
469
					continue;
470
				}
471
			}
472
			inventoryClient = new InventoryClient().getClient();
473
			try {
474
				logger.info("Flipkart Item id is " + flipkartItem.getItem_id());
475
				if(flipkartItem.getItem_id()!=0 && flipkartItem.getWarehouseId()!=0) {
476
					logger.info("Flipkart Warehouse Id " + flipkartItem.getWarehouseId());
477
					fulfillmentWarehouse = inventoryClient.getWarehouse(flipkartItem.getWarehouseId());
478
					logger.info("fulfillmentWarehouse is " + fulfillmentWarehouse.getId() + " " + fulfillmentWarehouse.getDisplayName() );
479
 
480
				} else {
481
					List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(sku, 1);
482
					fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
483
					if(fulfillmentWarehouse.getStateId()!=0){
484
						fulfillmentWarehouse = inventoryClient.getWarehouse(7);
485
					}
486
				}
487
				t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
488
				long billingWarehouseId = 0;
489
				if(fulfillmentWarehouse.getBillingWarehouseId()== 0) {
490
					List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, fulfillmentWarehouse.getVendor().getId(), 0, 0);
491
					for(Warehouse warehouse : warehouses) {
492
						if(warehouse.getBillingWarehouseId()!=0) {
493
							billingWarehouseId = warehouse.getBillingWarehouseId();
494
							break;
495
						}
496
					}
497
				}else {
498
					billingWarehouseId = fulfillmentWarehouse.getBillingWarehouseId();
499
				}
500
 
501
				//logger.info("Billing warehouse id for suborderid  " + order.getSuborderId() + " is " + fulfillmentWarehouse.getBillingWarehouseId());
502
				t_order.setWarehouse_id(billingWarehouseId);
503
				VendorItemPricing vendorItemPricing = new VendorItemPricing();
504
				Item item = new CatalogClient().getClient().getItem(lineItem.getItem_id());
505
				if(fulfillmentWarehouse.getId()==7) {
506
 
507
					try{
508
						vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), item.getPreferredVendor());
509
					}
510
					catch(TTransportException e){
511
						inventoryClient = new InventoryClient().getClient();
512
						vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), item.getPreferredVendor());
513
					}
514
				} 
515
				else {
516
					try{
517
						vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), item.getPreferredVendor());
518
					}
519
					catch(TTransportException e){
520
						inventoryClient = new InventoryClient().getClient();
521
						vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), fulfillmentWarehouse.getVendor().getId());
522
					}
523
				}
524
				t_order.getLineitems().get(0).setTransfer_price(vendorItemPricing.getTransferPrice());
525
				t_order.getLineitems().get(0).setNlc(vendorItemPricing.getNlc());
526
			} catch (InventoryServiceException e) {
527
				logger.error("Error connecting inventory service for suborderid  " + orderId + " " + subOrderId , e);
528
				sb.append(orderId + " " + subOrderId+ " Inventory Service Exception" + " " + "\n");
529
				continue;
530
			} catch (TTransportException e) {
531
				logger.error("Transport Exception with Inventory Service for suborderid  " + orderId + " " + subOrderId , e);
532
				sb.append(orderId + " " + subOrderId + " Transport Exception with Inventory Service" + " " + "\n");
533
				continue;
534
			} catch (TException e) {
535
				logger.error("Exception with Inventory Service for suborderid  " + orderId + " " + subOrderId , e);
536
				sb.append(orderId + " " + subOrderId + " Exception in Inventory Service" + " " + "\n");
537
				continue;
538
			} catch (CatalogServiceException e) {
539
				logger.error("Exception with Catalog Service for   " + orderId + " " + subOrderId + " while getting item " + lineItem.getItem_id(), e);
540
				sb.append(orderId + " " + subOrderId + " Exception in Catalog Service" + " " + "\n");
541
				continue;
542
			}
543
			t_order.setLogistics_provider_id(FLIPKART_LOGISTICS_ID);
544
			t_order.setAirwaybill_no("");
545
			t_order.setTracking_id("");
546
			t_order.setTotal_amount(unitSellingPrice*quantity);
547
			t_order.setOrderType(OrderType.B2C);
548
			t_order.setSource(FLIPKART_SOURCE_ID);
549
			t_order.setOrderType(OrderType.B2C);
550
			total_price = unitSellingPrice*quantity;
551
			orderlist.add(t_order);
552
			txn.setOrders(orderlist);
553
			try {
554
				transactionId =  String.valueOf(transaction_client.createTransaction(txn));
555
				logger.info("Transaction id is : " + transactionId);
556
			} catch (TransactionServiceException e) {
557
				logger.error(orderId+" "+subOrderId + " Could not create transaction " , e);
558
				sb.append(orderId+" "+subOrderId + " Could not create transaction" +"\n");
559
				continue;
560
			} catch (TException e) {
561
				transaction_client = new TransactionClient().getClient();
562
				try {
563
					transactionId =  String.valueOf(transaction_client.createTransaction(txn));
564
				} catch (TransactionServiceException e1) {
565
					sb.append(orderId+" "+subOrderId + " Transaction Service Exception could not create transaction" +"\n");
566
					logger.info(orderId+" "+subOrderId + " Transaction Service Exception could not create transaction" +"\n" , e);
567
					continue;
568
				}
569
			}
570
			try{
571
				logger.info("Creating payment for suborder id " + subOrderId +" ");
572
				paymentId = createPayment(user,subOrderId,total_price);
573
			}
574
			catch (NumberFormatException e) {
575
				logger.error("Could not create payment",e);
576
				sb.append(orderId+" "+subOrderId + " Could not create payment");
577
				e.printStackTrace();
578
				continue;
579
			} catch (PaymentException e) {
580
				logger.error("Could not create payment payment exception",e);
581
				sb.append(orderId+" "+subOrderId + " Could not create payment Payment exception");
582
				e.printStackTrace();
583
				continue;
584
			} catch (TException e) {
585
				logger.error("Could not create payment thrift exception",e);
586
				sb.append(orderId+" "+subOrderId + " Could not create payment Thrift exception"+"\n");
587
				e.printStackTrace();
588
				continue;
589
			}
590
			Transaction transaction = null;
591
			try {
592
				transaction_client = tsc.getClient();
593
				transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
594
			} catch (NumberFormatException e) {
595
				logger.error("Problem parsing transaction id " + transactionId +" ", e);
596
				sb.append(orderId+" "+subOrderId  + " Problem parsing transaction id "+ transactionId +"\n");
597
				e.printStackTrace();
598
				continue;
599
			} catch (TransactionServiceException e) {
600
				logger.error("Problem getting transaction from service transaction id " + transactionId +" ",e);
601
				sb.append(orderId+" "+subOrderId  + " Problem getting transaction id "+ transactionId +"\n");
602
				e.printStackTrace();
603
				continue;
604
			} catch (TException e) {
605
				logger.error("	 " + transactionId + " " , e);
606
				sb.append(orderId+" "+subOrderId + " Problem with transaction service while getting transaction id "+ transactionId +"\n");
607
				e.printStackTrace();
608
				continue;
609
			}
610
			List<in.shop2020.model.v1.order.Order> flipkartorders = transaction.getOrders();
611
			for(in.shop2020.model.v1.order.Order flipkartorder:flipkartorders){
612
				try {
613
					List<in.shop2020.model.v1.order.Attribute> attributeList = new ArrayList<in.shop2020.model.v1.order.Attribute>();
614
					try{
615
						inventoryClient.reserveItemInWarehouse(flipkartorder.getLineitems().get(0).getItem_id(), fulfillmentWarehouse.getId(), 1, 
616
								flipkartorder.getId(), flipkartorder.getCreated_timestamp(), flipkartorder.getPromised_shipping_time(), flipkartorder.getLineitems().get(0).getQuantity());
617
					}
618
					catch(TTransportException e){
619
						new InventoryClient().getClient().reserveItemInWarehouse(flipkartorder.getLineitems().get(0).getItem_id(), fulfillmentWarehouse.getId(), 1, 
620
								flipkartorder.getId(), flipkartorder.getCreated_timestamp(), flipkartorder.getPromised_shipping_time(), flipkartorder.getLineitems().get(0).getQuantity());
621
					}
622
					FlipkartOrder flipkartOrder = new FlipkartOrder();
623
					flipkartOrder.setOrderId(flipkartorder.getId());
624
					flipkartOrder.setFlipkartOrderId(orderId);
625
					flipkartOrder.setFlipkartSubOrderId(subOrderId);
626
					flipkartOrder.setFlipkartTxnDate(flipkartTxnDate.getTime());
627
					flipkartOrder.setEmiFee(emiFee);
628
					flipkartOrder.setOctroiFee(octroiFee);
629
					flipkartOrder.setShippingPrice(shippingPrice);
630
					flipkartOrder.setMaxNlc(flipkartItem.getMaxNlc()); 
631
					in.shop2020.model.v1.order.Attribute attribute = new in.shop2020.model.v1.order.Attribute();
632
					attribute.setName("Buyer Name");
633
					attribute.setValue(buyerName);
634
					attributeList.add(attribute);
635
					try {
636
						transaction_client.createFlipkartOrder(flipkartOrder);
637
						transaction_client.setOrderAttributes(flipkartOrder.getOrderId(),attributeList);
638
						logger.info("transaction id : " + Long.valueOf(transactionId) + " Payment id : " + paymentId);
639
						new PaymentClient().getClient().updatePaymentDetails(paymentId, null, null, null, null, null, null, subOrderId, null, PaymentStatus.SUCCESS, null, null);
640
					} catch (TException e) {
641
						logger.error("Could not create flipkart order ",e);
642
						sb.append(orderId+" "+subOrderId + " Could not create flipkart order"+"\n");
643
						continue;
644
					} catch (PaymentException e) {
645
						logger.error("Could not update flipkart order payment ",e);
646
						sb.append(orderId+" "+subOrderId + " Could not update flipkart order payment"+"\n");
647
						continue;
648
					}
649
 
650
				} catch (InventoryServiceException e1) {
651
					logger.error("Problem while reserving item in inventory service" + flipkartorder.getId() + " ",e1);
652
					sb.append(orderId+" "+subOrderId + " Could not reserve inventory for sku "+ sku +"\n");
653
					continue;
654
				} catch (TException e1) {
655
					logger.error("Problem with inventory service" + flipkartorder.getId()+" ",e1);
656
					sb.append(orderId+" "+subOrderId + " Problem with inventory service while reserving inventory for sku "+ sku +"\n");
657
					continue;
658
				}
659
				orders_processed++;
660
			}
661
 
662
		}
663
 
664
		if(orders_processed==1){
665
			order_string = "Order";
666
		}
667
		else{
668
			order_string = "Orders";
669
		}
670
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
671
		Calendar cal=GregorianCalendar.getInstance();
672
		String emailFromAddress = "build@shop2020.in";
673
		String password = "cafe@nes";
674
		GmailUtils mailer = new GmailUtils();
675
		//String sendTo[] = new String[]{"manish.sharama@shop2020.in"};
12971 amit.gupta 676
		String sendTo[] = new String[]{ "sandeep.sachdeva@shop2020.in",  "rajneesh.arora@shop2020.in",
12747 manish.sha 677
				"khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
678
				"yukti.jain@shop2020.in","manish.sharma@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in","anikendra.das@shop2020.in"};
679
		try {
680
			logger.info("Before Sending Emails");
681
			String ordersProcessingStatus = "Total Orders : " + total_orders +"\n"+ 
682
			"Processed Orders : " + orders_processed +"\n"+
683
			"Existing Orders : " + duplicate_orders +"\n"+
684
			"Failed Orders :" + (total_orders - orders_processed - duplicate_orders - not_approved)+"\n"+
685
			"Unapproved Orders :" + not_approved;
686
 
687
			if(sb.toString().equalsIgnoreCase("")){
688
				if(orders_processed!=0){
689
					String emailSubjectTxt = orders_processed + " Flipkart " + order_string + " Created "+sdf.format(cal.getTime());
690
					mailer.sendSSLMessage(sendTo, emailSubjectTxt,"Orders Created Successfully (No Alerts)"+"\n"+ordersProcessingStatus, emailFromAddress, password, new ArrayList<File>());
691
					logger.info("Sending Email Flipkart Orders Created Successfully (No Alerts)");
692
				}
693
				else{
694
					String emailSubjectTxt = "No new Flipkart orders created "+sdf.format(cal.getTime());
695
					mailer.sendSSLMessage(sendTo, emailSubjectTxt,"No new orders created"+"\n\n"+ordersProcessingStatus, emailFromAddress, password, new ArrayList<File>());
696
					logger.info("Sending Email Flipkart Orders Created Successfully (No Alerts)");
697
				}
698
			}
699
			else{
700
				if(orders_processed!=0){
701
					/*String emailSubjectTxt = orders_processed + " Flipkart " + order_string + " Created "+sdf.format(cal.getTime());
702
					mailer.sendSSLMessage(sendTo, emailSubjectTxt,ordersProcessingStatus+"\n"+sb.toString(), emailFromAddress, password, new ArrayList<File>());
703
					logger.info("Sending Email Flipkart Orders Created Successfully (Check Alerts)");
704
					*/int failed_orders = (total_orders - orders_processed - duplicate_orders - not_approved);
705
					if(failed_orders==1){
706
						order_string = "Order";
707
					}
708
					else{
709
						order_string = "Orders";
710
					}
711
					String emailSubjectTxt = failed_orders + " Flipkart " + order_string + " Failed while creation  "+sdf.format(cal.getTime());
712
					mailer.sendSSLMessage(sendTo, emailSubjectTxt,ordersProcessingStatus+"\n"+sb.toString(), emailFromAddress, password, new ArrayList<File>());
713
					logger.info("Sending Email Flipkart Orders Failed while creation");
714
				}
715
				else{
716
					String emailSubjectTxt = "No new Flipkart orders created "+sdf.format(cal.getTime());
717
					mailer.sendSSLMessage(sendTo, emailSubjectTxt,ordersProcessingStatus+"\n"+sb.toString(), emailFromAddress, password, new ArrayList<File>());
718
					logger.info("Sending Email Flipkart Orders Created Successfully (Check Alerts)");
719
				}
720
			}
721
		}
722
		catch (Exception e) {
723
			e.printStackTrace();
724
			logger.error("Exception ",e);
725
		}
726
 
727
	}
728
 
729
	public static LineItem createLineItem(long itemId, double amount,int qty) throws CatalogServiceException, TException {
730
		LineItem lineItem = new LineItem();
731
		CatalogService.Client catalogClient = new CatalogClient().getClient();
732
		Item item = catalogClient.getItem(itemId);
733
		if(item.getId()==0){
734
			//in case item id is incorrect..
735
			return null;
736
		}
737
		lineItem.setProductGroup(item.getProductGroup());
738
		lineItem.setBrand(item.getBrand());
739
		lineItem.setModel_number(item.getModelNumber());
740
		lineItem.setModel_name(item.getModelName());
741
		lineItem.setExtra_info(item.getFeatureDescription());
742
		lineItem.setQuantity(qty);
743
		lineItem.setItem_id(item.getId());
744
		lineItem.setUnit_weight(item.getWeight());
745
		lineItem.setTotal_weight(item.getWeight());
746
		lineItem.setUnit_price(amount);
747
		lineItem.setTotal_price(amount*qty);
748
		if (item.getColor() == null || "NA".equals(item.getColor())) {
749
			lineItem.setColor("");
750
		} else {
751
			lineItem.setColor(item.getColor());
752
		}
753
		return lineItem;
754
	}
755
	public static long createPayment(User user, String subOrderId, double amount) throws PaymentException, TException {
756
		in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
757
		logger.info("Creating payment for user id " + user.getUserId() + " Gateway id " + FLIPKART_GATEWAY_ID);
758
		logger.info("Long value of transaction id : " + Long.valueOf(transactionId));
759
		long paymentId = client.createPayment(user.getUserId(), amount, FLIPKART_GATEWAY_ID, Long.valueOf(transactionId), false);
760
		return paymentId;
761
	}   
762
 
763
 
764
 
765
}