Subversion Repositories SmartDukaan

Rev

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