Subversion Repositories SmartDukaan

Rev

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