Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
8961 vikram.rag 1
package in.shop2020.support.controllers;
2
 
3
import in.shop2020.model.v1.catalog.Amazonlisted;
4
import in.shop2020.model.v1.catalog.CatalogService;
5
import in.shop2020.model.v1.catalog.CatalogServiceException;
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.AmazonFbaSalesSnapshot;
14
import in.shop2020.model.v1.order.FlipkartOrder;
15
import in.shop2020.model.v1.order.LineItem;
16
import in.shop2020.model.v1.order.OrderStatus;
17
import in.shop2020.model.v1.order.OrderType;
18
import in.shop2020.model.v1.order.SourceDetail;
19
import in.shop2020.model.v1.order.Transaction;
20
import in.shop2020.model.v1.order.TransactionServiceException;
21
import in.shop2020.model.v1.order.TransactionStatus;
22
import in.shop2020.model.v1.order.TransactionService.Client;
23
import in.shop2020.model.v1.user.User;
24
import in.shop2020.payments.PaymentException;
25
import in.shop2020.payments.PaymentStatus;
26
import in.shop2020.support.utils.ReportsUtils;
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
 
33
import java.io.BufferedInputStream;
34
import java.io.BufferedReader;
35
import java.io.File;
36
import java.io.FileInputStream;
37
import java.io.FileNotFoundException;
38
import java.io.FileOutputStream;
39
import java.io.FileReader;
40
import java.io.FileWriter;
41
import java.io.IOException;
42
import java.io.InputStream;
43
import java.io.Writer;
44
import java.text.ParseException;
45
import java.text.SimpleDateFormat;
46
import java.util.ArrayList;
47
import java.util.Arrays;
48
import java.util.Calendar;
49
import java.util.Collections;
50
import java.util.Date;
51
import java.util.HashMap;
52
import java.util.List;
53
import java.util.Map;
54
 
55
import javax.servlet.ServletContext;
56
import javax.servlet.ServletOutputStream;
57
import javax.servlet.http.HttpServletRequest;
58
import javax.servlet.http.HttpServletResponse;
59
import javax.servlet.http.HttpSession;
60
 
61
import org.apache.commons.io.FileUtils;
62
import org.apache.commons.lang.xwork.StringUtils;
63
import org.apache.poi.hssf.usermodel.HSSFRow;
64
import org.apache.poi.hssf.usermodel.HSSFSheet;
65
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
66
import org.apache.poi.ss.usermodel.Cell;
67
import org.apache.struts2.convention.annotation.InterceptorRef;
68
import org.apache.struts2.convention.annotation.InterceptorRefs;
69
import org.apache.struts2.interceptor.ServletRequestAware;
70
import org.apache.struts2.interceptor.ServletResponseAware;
71
import org.apache.struts2.util.ServletContextAware;
72
import org.apache.thrift.TException;
73
import org.apache.thrift.transport.TTransportException;
74
import org.slf4j.Logger;
75
import org.slf4j.LoggerFactory;
76
 
77
import au.com.bytecode.opencsv.CSVReader;
78
 
79
import com.opensymphony.xwork2.ValidationAwareSupport;
80
 
81
public class FlipkartDashboardController extends ValidationAwareSupport implements ServletRequestAware ,ServletResponseAware, ServletContextAware{
82
	private static Logger logger = LoggerFactory.getLogger(FlipkartDashboardController.class);
83
	private static final int FLIPKART_SOURCE_ID = 8;
8963 vikram.rag 84
	private static final int FLIPKART_GATEWAY_ID = 17;
8962 vikram.rag 85
	private static final int FLIPKART_LOGISTICS_ID = 19;
8961 vikram.rag 86
	private HttpServletRequest request;
87
	private HttpServletResponse response;
88
	private HttpSession session;
89
	private ServletContext context;
90
	private String url;
91
	private File file;
92
	private String errMsg;
93
	private String id;
94
	private static String transactionId;
95
	public String uploadorders(){
96
		if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
97
			logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
98
			return "authfail";
99
		}
100
		return "flipkart-upload-orders";
101
	}
102
	public String show() {
103
		logger.info("Before fetching role");
104
		logger.info(request.getSession().toString());
105
		logger.info(ReportsUtils.ROLE);
106
		logger.info(session.getAttribute(ReportsUtils.ROLE).toString());
107
		logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1]);
108
		if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1])) {
109
			logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1]);
110
			return "authfail";
111
		}
112
 
113
		if (StringUtils.equals(id, "flipkart-options")){
114
			return "flipkart-options";
115
		}
116
 
117
		return "id";
118
	}
119
	public void uploadOrdersFile() throws IOException, CatalogServiceException, TException{
120
		File fileToCreate = new File("/tmp/", "Flipkart-Orders.csv");
121
		FileUtils.copyFile(this.file, fileToCreate);
122
		FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
123
		CSVReader orderfilereader = null;
124
		replacecommas(fileToCreate);
125
		try {
126
			orderfilereader = new CSVReader(new FileReader("/tmp/formatted.csv"),'$');
127
		} catch (FileNotFoundException e) {
128
			// TODO Auto-generated catch block
129
			e.printStackTrace();
130
		}
131
		logger.info("Before Processing orders ");
132
		String [] nextLine;
133
		Writer sb = null;
134
		try {
135
			User user = null;
136
			TransactionClient tsc = null;
137
			SourceDetail sourceDetail = null;
138
			logger.info("Before Fetching sourcedetail");
139
			try {
140
				tsc = new TransactionClient();
141
				sourceDetail = tsc.getClient().getSourceDetail(FLIPKART_SOURCE_ID);
142
				logger.info("Flipkart sourcedetail " + sourceDetail.getEmail() + " " + sourceDetail.getName());
143
			} catch (Exception e) {
144
				logger.error("Unable to establish connection to the transaction service while getting Flipkart Source Detail ", e);
145
			}
146
			try {   
147
				in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
148
				logger.info("Before Fetching User by Email");
149
				user = userClient.getUserByEmail(sourceDetail.getEmail());
150
				logger.info("User is " + user.getEmail());
151
			} catch (Exception e) {
152
				logger.error("Unable to establish connection to the User service ", e);
153
			}
154
			logger.info("Before iterating orders in file");
155
			while ((nextLine = orderfilereader.readNext()) != null) {
156
				logger.info("Order file entry  ");
157
				String orderId,subOrderId,create_date;
158
				long sku;
159
				logger.info("Processing order " + nextLine[3]+ " " + nextLine[4]);
160
				if(nextLine[3].length()==0 || nextLine[4].length()==0 ){
161
					sb.append(" Could not parse order id " + nextLine[3]+ " " + nextLine[4] + "\n");
162
					logger.info("Processing order " + nextLine[3]+ " " + nextLine[4]);
163
					continue;
164
				}
165
				else{
166
					orderId = nextLine[3];
167
					subOrderId = nextLine[4];
168
				}
169
 
170
				if(nextLine[0].length()!=0){
171
					create_date = nextLine[0];
172
				}
173
				else{
174
					sb.append(orderId+" "+subOrderId + " Could not parse order date" +"\n");
175
					logger.info(orderId+" "+subOrderId + " Could not parse order date");
176
					continue;
177
				}
178
				if(nextLine[5].length()==0){
179
					sb.append(orderId+" "+subOrderId + " Could not parse sku" +"\n");
180
					logger.info(orderId+" "+subOrderId + " Could not parse sku");
181
					continue;
182
				}
183
				else{
184
					sku =  Long.parseLong(nextLine[5]);
185
					logger.info(orderId+" "+subOrderId + " Processing  sku " + sku);
186
				}
187
				if(nextLine[6].length()!=0 && nextLine[6].equalsIgnoreCase("Approved")){
188
					String status = nextLine[6];	
189
				}
190
				else{
191
					if(nextLine[6].length()==0){
192
						sb.append(orderId+" "+subOrderId + " Could not parse status" +"\n");
193
						logger.info(orderId+" "+subOrderId + " Could not parse status" +"\n");
194
					}
195
					continue;
196
				}
197
				double unitSellingPrice,shippingPrice,octroiFee,emiFee;
198
				if(nextLine[7].length()!=0 ){
199
					if(Double.parseDouble(nextLine[7]) > 0){
200
						unitSellingPrice =  Double.parseDouble(nextLine[7]);
201
					}
202
					else{
203
						sb.append(orderId+" "+subOrderId + " Unit Price set to 0 " +"\n");
204
						logger.info(orderId+" "+subOrderId + " Unit Price set to 0 " +"\n");
205
						continue;
206
					}
207
				}
208
				else{
209
					sb.append(orderId+" "+subOrderId + " Unit Price not set " +"\n");
210
					logger.info(orderId+" "+subOrderId + " Unit Price not set " +"\n");
211
					continue;
212
				}
213
				if(nextLine[8].length()!=0){
214
					shippingPrice  =  Double.parseDouble(nextLine[8]);
215
				}
216
				else{
217
					shippingPrice=0;
218
				}
219
				if(nextLine[9].length()!=0){
220
					octroiFee =  Double.parseDouble(nextLine[9]);
221
					if(octroiFee >0){
222
						sb.append(orderId+" "+subOrderId + " OctroiFee :"+ octroiFee +"\n");
223
						logger.info(orderId+" "+subOrderId + " OctroiFee :"+ octroiFee +"\n");
224
					}
225
				}
226
				else{
227
					octroiFee=0;
228
				}
229
				if(nextLine[10].length()!=0){
230
					emiFee =  Double.parseDouble(nextLine[10]);
231
					if(emiFee >0){
232
						sb.append(orderId+" "+subOrderId + " EMI :"+ emiFee +"\n");
233
						logger.info(orderId+" "+subOrderId + " EMI :"+ emiFee +"\n");
234
					}
235
				}
236
				else{
237
					emiFee = 0;
238
				}
239
				int quantity;
240
				if(nextLine[11].length()!=0){
241
					quantity = Integer.parseInt(nextLine[11]);
242
					if(quantity > 1){
243
						sb.append(orderId+" "+subOrderId + " Quantity > 1 " +"\n");
244
						logger.info(orderId+" "+subOrderId + " Quantity > 1 " +"\n");
245
					}
246
					else{
247
						if(quantity==0){
248
							sb.append(orderId+" "+subOrderId + " Quantity not set " +"\n");
249
							logger.info(orderId+" "+subOrderId + " Quantity not set " +"\n");
250
							continue;
251
						}
252
					}
253
				}
254
				else{
255
					sb.append(orderId+" "+subOrderId + " Quantity not set " +"\n");
256
					logger.info(orderId+" "+subOrderId + " Quantity not set " +"\n");
257
					continue;
258
				}
259
				double totalsellingPrice; 
260
				if(nextLine[12].length()!=0){
261
					totalsellingPrice= Double.parseDouble(nextLine[12]);
262
					if(totalsellingPrice==0){
263
						sb.append(orderId+" "+subOrderId + " Total Selling Price set to 0 " +"\n");
264
						logger.info(orderId+" "+subOrderId + " Total Selling Price set to 0 " +"\n");
265
						continue;
266
					}
267
				}
268
				else{
269
					sb.append(orderId+" "+subOrderId + " Total Selling Price not set " +"\n");
270
					logger.info(orderId+" "+subOrderId + " Total Selling Price not set " +"\n");
271
					continue;
272
				}
273
				//String buyerName = nextLine[17];
274
				String shipToName,addressLine1,addressLine2,city,state,pincode;
275
				if(nextLine[18].length()>0){
276
					shipToName = nextLine[18];
277
				}
278
				else{
279
					sb.append(orderId+" "+subOrderId + " Ship to Name not set " +"\n");
280
					logger.info(orderId+" "+subOrderId + " Ship to Name not set " +"\n");
281
					continue;
282
				}
283
				if(nextLine[19].length()>0){
284
					addressLine1 = nextLine[19];
285
				}
286
				else{
287
					addressLine1 ="";
288
				}
289
				if(nextLine[20].length()>0){
290
					addressLine2 = nextLine[20];
291
				}
292
				else{
293
					addressLine2 ="";
294
				}
295
				if(nextLine[21].length()>0){
296
					city = nextLine[21];
297
				}
298
				else{
299
					sb.append(orderId+" "+subOrderId + " City not set " +"\n");
300
					logger.info(orderId+" "+subOrderId + " City not set " +"\n");
301
					continue;
302
				}
303
				if(nextLine[22].length()>0){
304
					state = nextLine[22];
305
				}
306
				else{
307
					sb.append(orderId+" "+subOrderId + " State not set " +"\n");
308
					logger.info(orderId+" "+subOrderId + " State not set " +"\n");
309
					continue;
310
				}
311
				if(nextLine[23].length()>0){
312
					pincode = nextLine[23];
313
				}
314
				else{
315
					sb.append(orderId+" "+subOrderId + " Pincode not set " +"\n");
316
					logger.info(orderId+" "+subOrderId + " Pincode not set " +"\n");
317
					continue;
318
				}
319
				int sla; 
320
				if(nextLine[23].length()>0){
321
					sla = Integer.parseInt(nextLine[24]);
322
				}
323
				else{
324
					sb.append(orderId+" "+subOrderId + " Ship to date not available " +"\n");
325
					logger.info(orderId+" "+subOrderId + " Ship to date not available " +"\n");
326
					continue;
327
				}
328
				//String shipByDate = nextLine[26];
329
				Client transaction_client = null;
330
				try {
331
					transaction_client = new TransactionClient().getClient();
332
					if(transaction_client.flipkartOrderExists(orderId,subOrderId)) {
333
						logger.error("Flipkart order exists " + "id : " + orderId + " suborder id : ");
334
						continue;
335
					}
336
 
337
				} catch (TTransportException e1) {
338
					logger.error("Problem with Transaction service " , e1);
339
					e1.printStackTrace();
340
				} catch (TException e) {
341
					logger.error("Problem.. thrift exception with Transaction service " , e);
342
					e.printStackTrace();
343
				}
344
				SimpleDateFormat istFormatter = new SimpleDateFormat("MMM dd, yyyy");
345
				Date flipkartTxnDate = null;
346
				try {
347
					create_date = create_date.replaceAll("\"","");
348
					flipkartTxnDate = istFormatter.parse(create_date);
349
				} catch (ParseException e) {
350
					logger.error(orderId+" "+subOrderId + " Could not parse flipkart order date from file " , e);
351
					sb.append(orderId+" "+subOrderId + " Could not parse order date" +"\n");
352
					continue;
353
				}
354
				Transaction txn = new Transaction();
355
				txn.setShoppingCartid(user.getActiveCartId());
356
				txn.setCustomer_id(user.getUserId());
357
				System.out.println("User Id is " + user.getUserId());
358
				txn.setCreatedOn(new Date().getTime());
359
				txn.setTransactionStatus(TransactionStatus.INIT);
360
				txn.setStatusDescription("Order for flipkart ");
361
				List<in.shop2020.model.v1.order.Order> orderlist = new ArrayList<in.shop2020.model.v1.order.Order>();
362
				double total_price=0;
363
				InventoryService.Client inventoryClient = null;
364
				Warehouse fulfillmentWarehouse= null;
365
				for(int i=0;i<quantity;i++){
366
					LineItem lineItem = null;
367
					lineItem = createLineItem(sku,unitSellingPrice);
368
					lineItem.setExtra_info("flipkartOrderId = " + orderId + " flipkartsubOrderId = " + subOrderId);
369
					in.shop2020.model.v1.order.Order t_order = new in.shop2020.model.v1.order.Order();
370
					t_order.setCustomer_id(user.getUserId());
371
					t_order.setCustomer_email(sourceDetail.getEmail());
372
					t_order.setCustomer_name(shipToName);
373
					addressLine1 = addressLine1.replaceAll("\"",""); 
374
					t_order.setCustomer_address1(addressLine1);
375
					addressLine2 = addressLine2.replaceAll("\"","");
376
					t_order.setCustomer_address2(addressLine2);
377
					t_order.setCustomer_city(city);
378
					t_order.setCustomer_state(state);
379
					t_order.setCustomer_pincode(pincode);
380
					t_order.setTotal_amount(unitSellingPrice);            
381
					t_order.setTotal_weight(lineItem.getTotal_weight());
382
					t_order.setLineitems(Collections.singletonList(lineItem));            
383
					t_order.setStatus(OrderStatus.PAYMENT_PENDING);
384
					t_order.setStatusDescription("Payment Pending");
385
					t_order.setCreated_timestamp(new Date().getTime());
386
					t_order.setOrderType(OrderType.B2C);
387
					t_order.setCod(false);
388
					try {
389
						Date shipDate = new Date();
390
						shipDate.setTime( flipkartTxnDate.getTime() + sla*24*60*60*1000);
391
						Calendar time = Calendar.getInstance();
392
						t_order.setPromised_shipping_time(shipDate.getTime());
393
						t_order.setExpected_shipping_time(shipDate.getTime());
394
						time.add(Calendar.DAY_OF_MONTH, 4);
395
						t_order.setPromised_delivery_time(time.getTimeInMillis());
396
						t_order.setExpected_delivery_time(time.getTimeInMillis());
397
					} catch(Exception e) {	
398
						logger.error("Error in updating Shipping or Delivery Time for suborderid  " + subOrderId);
399
						sb.append(orderId + " "+ subOrderId  + " Could not update delivery time" + " " + "\n");
400
						continue;
401
					}
402
					try {
403
						inventoryClient = new InventoryClient().getClient();
404
						List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(sku, 1);
405
						fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
406
						if(fulfillmentWarehouse.getStateId()!=0){
407
							fulfillmentWarehouse = inventoryClient.getWarehouse(7);
408
						}
409
						t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
410
						long billingWarehouseId = 0;
411
						if(fulfillmentWarehouse.getBillingWarehouseId()== 0) {
412
							inventoryClient = new InventoryClient().getClient();
413
							List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, fulfillmentWarehouse.getVendor().getId(), 0, 0);
414
							for(Warehouse warehouse : warehouses) {
415
								if(warehouse.getBillingWarehouseId()!=0) {
416
									billingWarehouseId = warehouse.getBillingWarehouseId();
417
									break;
418
								}
419
							}
420
						}else {
421
							billingWarehouseId = fulfillmentWarehouse.getBillingWarehouseId();
422
						}
423
 
424
						t_order.setWarehouse_id(billingWarehouseId);
425
						VendorItemPricing vendorItemPricing = new VendorItemPricing();
426
						if(fulfillmentWarehouse.getId()==7) {
427
							Item item = new CatalogClient().getClient().getItem(lineItem.getItem_id());
428
							vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), item.getPreferredVendor());
429
						} else {
430
							vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), fulfillmentWarehouse.getVendor().getId());
431
						}
432
 
433
						t_order.getLineitems().get(0).setTransfer_price(vendorItemPricing.getTransferPrice());
434
						t_order.getLineitems().get(0).setNlc(vendorItemPricing.getNlc());
435
					} catch (InventoryServiceException e) {
436
						logger.error("Error connecting inventory service for suborderid  " + orderId + " " + subOrderId , e);
437
						sb.append(orderId + " " + subOrderId+ " Inventory Service Exception" + " " + "\n");
438
						continue;
439
					} catch (TTransportException e) {
440
						logger.error("Transport Exception with Inventory Service for suborderid  " + orderId + " " + subOrderId , e);
441
						sb.append(orderId + " " + subOrderId + " Transport Exception with Inventory Service" + " " + "\n");
442
						continue;
443
					} catch (TException e) {
444
						logger.error("Exception with Inventory Service for suborderid  " + orderId + " " + subOrderId , e);
445
						sb.append(orderId + " " + subOrderId + " Exception in Inventory Service" + " " + "\n");
446
						continue;
447
					} catch (CatalogServiceException e) {
448
						logger.error("Exception with Catalog Service for   " + orderId + " " + subOrderId + " while getting item " + lineItem.getItem_id(), e);
449
						sb.append(orderId + " " + subOrderId + " Exception in Catalog Service" + " " + "\n");
450
						continue;
451
					}
8962 vikram.rag 452
					t_order.setLogistics_provider_id(FLIPKART_LOGISTICS_ID);
8961 vikram.rag 453
					t_order.setAirwaybill_no("");
454
					t_order.setTracking_id("");
455
					t_order.setTotal_amount(unitSellingPrice);
456
					t_order.setOrderType(OrderType.B2C);
457
					t_order.setSource(FLIPKART_SOURCE_ID);
458
					t_order.setOrderType(OrderType.B2C);
459
					total_price = total_price + unitSellingPrice;
460
					orderlist.add(t_order);
461
				}
462
				txn.setOrders(orderlist);
463
				String transactionId;
464
				try {
465
					transactionId =  String.valueOf(transaction_client.createTransaction(txn));
466
				} catch (TransactionServiceException e) {
467
					logger.error(orderId+" "+subOrderId + " Could not create transaction " , e);
468
					sb.append(orderId+" "+subOrderId + " Could not create transaction" +"\n");
469
					logger.info(orderId+" "+subOrderId + " Could not create transaction" +"\n");
470
					continue;
471
				} catch (TException e) {
472
					logger.error("Problem with transaction service while creating transaction", e);
473
					sb.append(orderId+" "+subOrderId + " Transaction Service Exception could not create transaction" +"\n");
474
					logger.info(orderId+" "+subOrderId + " Transaction Service Exception could not create transaction" +"\n");
475
					continue;
476
				}
477
				try{
478
					createPayment(user,orderId,unitSellingPrice);
479
				}
480
				catch (NumberFormatException e) {
481
					logger.error("Could not create payment",e);
482
					sb.append(orderId+" "+subOrderId + " Could not create payment");
483
					e.printStackTrace();
484
					continue;
485
				} catch (PaymentException e) {
486
					logger.error("Could not create payment payment exception",e);
487
					sb.append(orderId+" "+subOrderId + " Could not create payment Payment exception");
488
					e.printStackTrace();
489
					continue;
490
				} catch (TException e) {
491
					logger.error("Could not create payment thrift exception",e);
492
					sb.append(orderId+" "+subOrderId + " Could not create payment Thrift exception");
493
					e.printStackTrace();
494
					continue;
495
				}
496
				Transaction transaction = null;
497
				try {
498
					transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
499
				} catch (NumberFormatException e) {
500
					logger.error("Problem parsing transaction id " + transactionId);
501
					sb.append(orderId+" "+subOrderId  + " Problem parsing transaction id "+ transactionId +"\n");
502
					e.printStackTrace();
503
					continue;
504
				} catch (TransactionServiceException e) {
505
					logger.error("Problem getting transaction from service transaction id " + transactionId);
506
					sb.append(orderId+" "+subOrderId  + " Problem getting transaction id "+ transactionId +"\n");
507
					e.printStackTrace();
508
					continue;
509
				} catch (TException e) {
510
					logger.error("Problem with transaction service while getting transaction id " + transactionId);
511
					sb.append(orderId+" "+subOrderId + " Problem with transaction service while getting transaction id "+ transactionId +"\n");
512
					e.printStackTrace();
513
					continue;
514
				}
515
				List<in.shop2020.model.v1.order.Order> flipkartorders = transaction.getOrders();
516
				for(in.shop2020.model.v1.order.Order flipkartorder:flipkartorders){
517
					try {
518
						inventoryClient.reserveItemInWarehouse(flipkartorder.getLineitems().get(0).getItem_id(), fulfillmentWarehouse.getId(), 1, 
519
								flipkartorder.getId(), flipkartorder.getCreated_timestamp(), flipkartorder.getPromised_shipping_time(), flipkartorder.getLineitems().get(0).getQuantity());
520
						FlipkartOrder flipkartOrder = new FlipkartOrder();
521
						flipkartOrder.setOrderId(flipkartorder.getId());
522
						flipkartOrder.setFlipkartOrderId(orderId);
523
						flipkartOrder.setFlipkartSubOrderId(subOrderId);
524
						flipkartOrder.setFlipkartTxnDate(flipkartTxnDate.getTime());
525
						flipkartOrder.setEmiFee(emiFee);
526
						flipkartOrder.setOctroiFee(octroiFee);
527
						flipkartOrder.setShippingPrice(shippingPrice);
528
						try {
529
							transaction_client.createFlipkartOrder(flipkartOrder);
530
						} catch (TException e) {
531
							logger.error("Could not create flipkart order");
532
							sb.append(orderId+" "+subOrderId + " Could not create flipkart order"+"\n");
533
							continue;
534
						}
535
 
536
					} catch (InventoryServiceException e1) {
537
						logger.error("Problem while reserving item in inventory service" + flipkartorder.getId());
538
						sb.append(orderId+" "+subOrderId + " Could not reserve inventory for sku "+ sku +"\n");
539
						continue;
540
					} catch (TException e1) {
541
						logger.error("Problem with inventory service" + flipkartorder.getId());
542
						sb.append(orderId+" "+subOrderId + " Problem with inventory service while reserving inventory for sku "+ sku +"\n");
543
						continue;
544
					}
545
				}
546
			}
547
			response.setHeader("Content-Type", "text/javascript");
548
 
549
			ServletOutputStream sos;
550
			try {
551
				sos = response.getOutputStream();
552
				sos.write(sb.toString().getBytes());
553
				sos.flush();
554
			} catch (IOException e) {
555
				System.out.println("Unable to stream the manifest file");
556
			}   
557
 
558
		}
559
		catch (FileNotFoundException e) {
560
			// TODO Auto-generated catch block
561
			e.printStackTrace();
562
		}
563
 
564
 
565
	}
566
 
567
	public static Logger getLogger() {
568
		return logger;
569
	}
570
	public static void setLogger(Logger logger) {
571
		FlipkartDashboardController.logger = logger;
572
	}
573
	public HttpServletRequest getRequest() {
574
		return request;
575
	}
576
	public void setRequest(HttpServletRequest request) {
577
		this.request = request;
578
	}
579
	public HttpServletResponse getResponse() {
580
		return response;
581
	}
582
	public void setResponse(HttpServletResponse response) {
583
		this.response = response;
584
	}
585
	public HttpSession getSession() {
586
		return session;
587
	}
588
	public void setSession(HttpSession session) {
589
		this.session = session;
590
	}
591
	public ServletContext getContext() {
592
		return context;
593
	}
594
	public void setContext(ServletContext context) {
595
		this.context = context;
596
	}
597
	public String getUrl() {
598
		return url;
599
	}
600
	public void setUrl(String url) {
601
		this.url = url;
602
	}
603
	public File getFile() {
604
		return file;
605
	}
606
	public void setFile(File file) {
607
		this.file = file;
608
	}
609
	public String getErrMsg() {
610
		return errMsg;
611
	}
612
	public void setErrMsg(String errMsg) {
613
		this.errMsg = errMsg;
614
	}
615
	public String getId() {
616
		return id;
617
	}
618
	public void setId(String id) {
619
		this.id = id;
620
	}
621
	@Override
622
	public void setServletContext(ServletContext arg0) {
623
		// TODO Auto-generated method stub
624
 
625
	}
626
	@Override
627
	public void setServletResponse(HttpServletResponse response) {
628
		this.response = response;
629
	}
630
	@Override
631
	public void setServletRequest(HttpServletRequest request) {
632
		this.request = request;
633
		this.session = request.getSession();        
634
 
635
	}
636
	public static LineItem createLineItem(long itemId, double amount) throws CatalogServiceException, TException {
637
		LineItem lineItem = new LineItem();
638
		CatalogService.Client catalogClient = new CatalogClient().getClient();
639
		Item item = catalogClient.getItem(itemId);
640
		if(item.getId()==0){
641
			//in case item id is incorrect..
642
			return null;
643
		}
644
 
645
		lineItem.setProductGroup(item.getProductGroup());
646
		lineItem.setBrand(item.getBrand());
647
		lineItem.setModel_number(item.getModelNumber());
648
		lineItem.setModel_name(item.getModelName());
649
		lineItem.setExtra_info(item.getFeatureDescription());
650
		lineItem.setQuantity(1);
651
		lineItem.setItem_id(item.getId());
652
		lineItem.setUnit_weight(item.getWeight());
653
		lineItem.setTotal_weight(item.getWeight());
654
		lineItem.setUnit_price(amount);
655
		lineItem.setTotal_price(amount);
656
 
657
		if (item.getColor() == null || "NA".equals(item.getColor())) {
658
			lineItem.setColor("");
659
		} else {
660
			lineItem.setColor(item.getColor());
661
		}
662
		return lineItem;
663
	}
664
 
665
	public static void replacecommas (File file) throws IOException {
666
		BufferedReader br = null;
667
		File tempFile = new File("/tmp/formatted.csv");
668
		FileWriter fw = new FileWriter(tempFile);
669
		String line;	
670
		br = new BufferedReader(new FileReader(file));
671
		boolean replace = false;
672
		char [] lineChars; 
673
		while ((line = br.readLine()) != null) {
674
 
675
			if(line.contains("Ordered On")){
676
				continue;
677
			}
678
			else{
679
				lineChars = line.toCharArray();
680
 
681
				int count = 0;
682
				for(int i=0;i<lineChars.length;i++)  
683
				{
684
					if(lineChars[i]=='"'){
685
						count++;
686
					}
687
					if(count%2==1){
688
						replace=false;
689
					}
690
					if(count%2==0){
691
						replace=true;
692
					}
693
					if(replace && lineChars[i] == ','){
694
						lineChars[i]='$';
695
					}
696
				}
697
			}
698
			line = String.valueOf(lineChars);
699
			fw.write(line+"\n");
700
		}
701
		if (br != null)br.close();
702
		if (fw != null)fw.close();
703
	}		
704
 
705
	public static void createPayment(User user, String subOrderId, double amount) throws NumberFormatException, PaymentException, TException {
706
		in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
707
		long paymentId = client.createPayment(user.getUserId(), amount, FLIPKART_GATEWAY_ID, Long.valueOf(transactionId), false);
708
		client.updatePaymentDetails(paymentId, null, null, null, null, null, null, subOrderId, null, PaymentStatus.AUTHORIZED, null, null);
709
	}   
710
 
711
 
712
}