Subversion Repositories SmartDukaan

Rev

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