Subversion Repositories SmartDukaan

Rev

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