Subversion Repositories SmartDukaan

Rev

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