Subversion Repositories SmartDukaan

Rev

Rev 8995 | Rev 9001 | 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 {
8999 vikram.rag 419
						logger.info("Snapdeal Item id is " + snapdealItem.getItem_id());
8994 vikram.rag 420
						if(snapdealItem.getItem_id()!=0 && snapdealItem.getWarehouseId()!=0) {
8999 vikram.rag 421
							logger.info("SnapdealItem Warehouse Id " + snapdealItem.getWarehouseId());
8994 vikram.rag 422
							fulfillmentWarehouse = inventoryClient.getWarehouse(snapdealItem.getWarehouseId());
8999 vikram.rag 423
							logger.info("fulfillmentWarehouse is " + fulfillmentWarehouse.getId() + " " + fulfillmentWarehouse.getDisplayName() );
424
 
8994 vikram.rag 425
						} else {
426
							List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(sku, 1);
427
							fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
428
							if(fulfillmentWarehouse.getStateId()!=0){
429
								fulfillmentWarehouse = inventoryClient.getWarehouse(7);
430
							}
8961 vikram.rag 431
						}
432
						t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
433
						long billingWarehouseId = 0;
434
						if(fulfillmentWarehouse.getBillingWarehouseId()== 0) {
435
							inventoryClient = new InventoryClient().getClient();
436
							List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, fulfillmentWarehouse.getVendor().getId(), 0, 0);
437
							for(Warehouse warehouse : warehouses) {
438
								if(warehouse.getBillingWarehouseId()!=0) {
439
									billingWarehouseId = warehouse.getBillingWarehouseId();
8994 vikram.rag 440
					                break;
8961 vikram.rag 441
								}
442
							}
443
						}else {
444
							billingWarehouseId = fulfillmentWarehouse.getBillingWarehouseId();
445
						}
8994 vikram.rag 446
 
447
						//logger.info("Billing warehouse id for suborderid  " + order.getSuborderId() + " is " + fulfillmentWarehouse.getBillingWarehouseId());
8961 vikram.rag 448
						t_order.setWarehouse_id(billingWarehouseId);
449
						VendorItemPricing vendorItemPricing = new VendorItemPricing();
450
						if(fulfillmentWarehouse.getId()==7) {
451
							Item item = new CatalogClient().getClient().getItem(lineItem.getItem_id());
452
							vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), item.getPreferredVendor());
453
						} else {
454
							vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), fulfillmentWarehouse.getVendor().getId());
455
						}
8994 vikram.rag 456
 
8961 vikram.rag 457
						t_order.getLineitems().get(0).setTransfer_price(vendorItemPricing.getTransferPrice());
458
						t_order.getLineitems().get(0).setNlc(vendorItemPricing.getNlc());
459
					} catch (InventoryServiceException e) {
460
						logger.error("Error connecting inventory service for suborderid  " + orderId + " " + subOrderId , e);
461
						sb.append(orderId + " " + subOrderId+ " Inventory Service Exception" + " " + "\n");
462
						continue;
463
					} catch (TTransportException e) {
464
						logger.error("Transport Exception with Inventory Service for suborderid  " + orderId + " " + subOrderId , e);
465
						sb.append(orderId + " " + subOrderId + " Transport Exception with Inventory Service" + " " + "\n");
466
						continue;
467
					} catch (TException e) {
468
						logger.error("Exception with Inventory Service for suborderid  " + orderId + " " + subOrderId , e);
469
						sb.append(orderId + " " + subOrderId + " Exception in Inventory Service" + " " + "\n");
470
						continue;
471
					} catch (CatalogServiceException e) {
472
						logger.error("Exception with Catalog Service for   " + orderId + " " + subOrderId + " while getting item " + lineItem.getItem_id(), e);
473
						sb.append(orderId + " " + subOrderId + " Exception in Catalog Service" + " " + "\n");
474
						continue;
475
					}
8962 vikram.rag 476
					t_order.setLogistics_provider_id(FLIPKART_LOGISTICS_ID);
8961 vikram.rag 477
					t_order.setAirwaybill_no("");
478
					t_order.setTracking_id("");
479
					t_order.setTotal_amount(unitSellingPrice);
480
					t_order.setOrderType(OrderType.B2C);
481
					t_order.setSource(FLIPKART_SOURCE_ID);
482
					t_order.setOrderType(OrderType.B2C);
483
					total_price = total_price + unitSellingPrice;
484
					orderlist.add(t_order);
485
				}
486
				txn.setOrders(orderlist);
487
				try {
488
					transactionId =  String.valueOf(transaction_client.createTransaction(txn));
8965 vikram.rag 489
					logger.info("Transaction id is : " + transactionId);
8961 vikram.rag 490
				} catch (TransactionServiceException e) {
491
					logger.error(orderId+" "+subOrderId + " Could not create transaction " , e);
492
					sb.append(orderId+" "+subOrderId + " Could not create transaction" +"\n");
493
					logger.info(orderId+" "+subOrderId + " Could not create transaction" +"\n");
494
					continue;
495
				} catch (TException e) {
496
					logger.error("Problem with transaction service while creating transaction", e);
497
					sb.append(orderId+" "+subOrderId + " Transaction Service Exception could not create transaction" +"\n");
498
					logger.info(orderId+" "+subOrderId + " Transaction Service Exception could not create transaction" +"\n");
499
					continue;
500
				}
501
				try{
8965 vikram.rag 502
					logger.info("Creating payment for suborder id " + subOrderId);
8964 vikram.rag 503
					createPayment(user,subOrderId,unitSellingPrice);
8961 vikram.rag 504
				}
505
				catch (NumberFormatException e) {
506
					logger.error("Could not create payment",e);
507
					sb.append(orderId+" "+subOrderId + " Could not create payment");
508
					e.printStackTrace();
509
					continue;
510
				} catch (PaymentException e) {
511
					logger.error("Could not create payment payment exception",e);
512
					sb.append(orderId+" "+subOrderId + " Could not create payment Payment exception");
513
					e.printStackTrace();
514
					continue;
515
				} catch (TException e) {
516
					logger.error("Could not create payment thrift exception",e);
517
					sb.append(orderId+" "+subOrderId + " Could not create payment Thrift exception");
518
					e.printStackTrace();
519
					continue;
520
				}
521
				Transaction transaction = null;
522
				try {
523
					transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
524
				} catch (NumberFormatException e) {
525
					logger.error("Problem parsing transaction id " + transactionId);
526
					sb.append(orderId+" "+subOrderId  + " Problem parsing transaction id "+ transactionId +"\n");
527
					e.printStackTrace();
528
					continue;
529
				} catch (TransactionServiceException e) {
530
					logger.error("Problem getting transaction from service transaction id " + transactionId);
531
					sb.append(orderId+" "+subOrderId  + " Problem getting transaction id "+ transactionId +"\n");
532
					e.printStackTrace();
533
					continue;
534
				} catch (TException e) {
535
					logger.error("Problem with transaction service while getting transaction id " + transactionId);
536
					sb.append(orderId+" "+subOrderId + " Problem with transaction service while getting transaction id "+ transactionId +"\n");
537
					e.printStackTrace();
538
					continue;
539
				}
540
				List<in.shop2020.model.v1.order.Order> flipkartorders = transaction.getOrders();
541
				for(in.shop2020.model.v1.order.Order flipkartorder:flipkartorders){
542
					try {
8973 vikram.rag 543
						List<in.shop2020.model.v1.order.Attribute> attributeList = new ArrayList<in.shop2020.model.v1.order.Attribute>();
8961 vikram.rag 544
						inventoryClient.reserveItemInWarehouse(flipkartorder.getLineitems().get(0).getItem_id(), fulfillmentWarehouse.getId(), 1, 
545
								flipkartorder.getId(), flipkartorder.getCreated_timestamp(), flipkartorder.getPromised_shipping_time(), flipkartorder.getLineitems().get(0).getQuantity());
546
						FlipkartOrder flipkartOrder = new FlipkartOrder();
547
						flipkartOrder.setOrderId(flipkartorder.getId());
548
						flipkartOrder.setFlipkartOrderId(orderId);
549
						flipkartOrder.setFlipkartSubOrderId(subOrderId);
550
						flipkartOrder.setFlipkartTxnDate(flipkartTxnDate.getTime());
551
						flipkartOrder.setEmiFee(emiFee);
552
						flipkartOrder.setOctroiFee(octroiFee);
553
						flipkartOrder.setShippingPrice(shippingPrice);
8973 vikram.rag 554
						in.shop2020.model.v1.order.Attribute attribute = new in.shop2020.model.v1.order.Attribute();
555
						attribute.setName("Buyer Name");
556
						attribute.setValue(buyerName);
557
						attributeList.add(attribute);
8961 vikram.rag 558
						try {
559
							transaction_client.createFlipkartOrder(flipkartOrder);
8973 vikram.rag 560
							transaction_client.setOrderAttributes(flipkartOrder.getOrderId(),attributeList);
8974 vikram.rag 561
							orders_processed++;
8961 vikram.rag 562
						} catch (TException e) {
563
							logger.error("Could not create flipkart order");
564
							sb.append(orderId+" "+subOrderId + " Could not create flipkart order"+"\n");
565
							continue;
566
						}
567
 
568
					} catch (InventoryServiceException e1) {
569
						logger.error("Problem while reserving item in inventory service" + flipkartorder.getId());
570
						sb.append(orderId+" "+subOrderId + " Could not reserve inventory for sku "+ sku +"\n");
571
						continue;
572
					} catch (TException e1) {
573
						logger.error("Problem with inventory service" + flipkartorder.getId());
574
						sb.append(orderId+" "+subOrderId + " Problem with inventory service while reserving inventory for sku "+ sku +"\n");
575
						continue;
576
					}
577
				}
578
			}
579
			response.setHeader("Content-Type", "text/javascript");
580
 
581
			ServletOutputStream sos;
582
			try {
583
				sos = response.getOutputStream();
8968 vikram.rag 584
				if(sb!=null){
585
					sos.write(sb.toString().getBytes());
586
				}
587
				else{
8974 vikram.rag 588
					if(orders_processed!=0){
589
						sos.write("Orders Created Successfully".toString().getBytes());
590
					}
591
					else{
592
						sos.write("Zero Approved Orders".toString().getBytes());
593
					}
8968 vikram.rag 594
				}
8961 vikram.rag 595
				sos.flush();
596
			} catch (IOException e) {
597
				System.out.println("Unable to stream the manifest file");
598
			}   
599
 
600
		}
601
		catch (FileNotFoundException e) {
602
			// TODO Auto-generated catch block
603
			e.printStackTrace();
604
		}
605
 
8995 vikram.rag 606
 
607
 
608
 
609
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
610
		Calendar cal=GregorianCalendar.getInstance();
611
		String emailFromAddress = "flipkart-alerts";
612
		String password = "cafe@nes";
613
		GmailUtils mailer = new GmailUtils();
614
		String sendTo[] = new String[]{"vikram.raghav@shop2020.in"};
615
		/*String sendTo[] = new String[]{ "sandeep.sachdeva@shop2020.in", "vikram.raghav@shop2020.in", "rajneesh.arora@shop2020.in",
616
				"khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
617
				"yukti.jain@shop2020.in","manisha.sharma@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in","amar.kumar@shop2020.in"};
618
		*/		
619
		try {
620
			if(sb!=null){
621
				String emailSubjectTxt = "Flipkart Orders Created Successfully (Check Alerts)"+sdf.format(cal.getTime());
622
				mailer.sendSSLMessage(sendTo, emailSubjectTxt, sb.toString(), emailFromAddress, password, new ArrayList<File>());
623
			}
624
			else{
625
				if(orders_processed!=0){
626
					String emailSubjectTxt = "Flipkart Orders Created Successfully"+sdf.format(cal.getTime());
627
					mailer.sendSSLMessage(sendTo, emailSubjectTxt,"No Alerts", emailFromAddress, password, new ArrayList<File>());
628
 
629
				}
630
				else{
631
					String emailSubjectTxt = "No New Approved Orders"+sdf.format(cal.getTime());
632
					mailer.sendSSLMessage(sendTo, emailSubjectTxt,"No Alerts", emailFromAddress, password, new ArrayList<File>());
633
 
634
				}
635
			}
8961 vikram.rag 636
 
8995 vikram.rag 637
			}
638
			catch (Exception e) {
639
				e.printStackTrace();
640
			}
8961 vikram.rag 641
	}
642
 
643
	public static Logger getLogger() {
644
		return logger;
645
	}
646
	public static void setLogger(Logger logger) {
647
		FlipkartDashboardController.logger = logger;
648
	}
649
	public HttpServletRequest getRequest() {
650
		return request;
651
	}
652
	public void setRequest(HttpServletRequest request) {
653
		this.request = request;
654
	}
655
	public HttpServletResponse getResponse() {
656
		return response;
657
	}
658
	public void setResponse(HttpServletResponse response) {
659
		this.response = response;
660
	}
661
	public HttpSession getSession() {
662
		return session;
663
	}
664
	public void setSession(HttpSession session) {
665
		this.session = session;
666
	}
667
	public ServletContext getContext() {
668
		return context;
669
	}
670
	public void setContext(ServletContext context) {
671
		this.context = context;
672
	}
673
	public String getUrl() {
674
		return url;
675
	}
676
	public void setUrl(String url) {
677
		this.url = url;
678
	}
679
	public File getFile() {
680
		return file;
681
	}
682
	public void setFile(File file) {
683
		this.file = file;
684
	}
685
	public String getErrMsg() {
686
		return errMsg;
687
	}
688
	public void setErrMsg(String errMsg) {
689
		this.errMsg = errMsg;
690
	}
691
	public String getId() {
692
		return id;
693
	}
694
	public void setId(String id) {
695
		this.id = id;
696
	}
697
	@Override
698
	public void setServletContext(ServletContext arg0) {
699
		// TODO Auto-generated method stub
700
 
701
	}
702
	@Override
703
	public void setServletResponse(HttpServletResponse response) {
704
		this.response = response;
705
	}
706
	@Override
707
	public void setServletRequest(HttpServletRequest request) {
708
		this.request = request;
709
		this.session = request.getSession();        
710
 
711
	}
712
	public static LineItem createLineItem(long itemId, double amount) throws CatalogServiceException, TException {
713
		LineItem lineItem = new LineItem();
714
		CatalogService.Client catalogClient = new CatalogClient().getClient();
715
		Item item = catalogClient.getItem(itemId);
716
		if(item.getId()==0){
717
			//in case item id is incorrect..
718
			return null;
719
		}
720
 
721
		lineItem.setProductGroup(item.getProductGroup());
722
		lineItem.setBrand(item.getBrand());
723
		lineItem.setModel_number(item.getModelNumber());
724
		lineItem.setModel_name(item.getModelName());
725
		lineItem.setExtra_info(item.getFeatureDescription());
726
		lineItem.setQuantity(1);
727
		lineItem.setItem_id(item.getId());
728
		lineItem.setUnit_weight(item.getWeight());
729
		lineItem.setTotal_weight(item.getWeight());
730
		lineItem.setUnit_price(amount);
731
		lineItem.setTotal_price(amount);
732
 
733
		if (item.getColor() == null || "NA".equals(item.getColor())) {
734
			lineItem.setColor("");
735
		} else {
736
			lineItem.setColor(item.getColor());
737
		}
738
		return lineItem;
739
	}
740
 
741
	public static void replacecommas (File file) throws IOException {
742
		BufferedReader br = null;
743
		File tempFile = new File("/tmp/formatted.csv");
744
		FileWriter fw = new FileWriter(tempFile);
745
		String line;	
746
		br = new BufferedReader(new FileReader(file));
747
		boolean replace = false;
748
		char [] lineChars; 
8991 vikram.rag 749
		int counter=1;
750
		String completeorder = null;
8961 vikram.rag 751
		while ((line = br.readLine()) != null) {
8991 vikram.rag 752
			if(counter!=1){
753
				if(line.endsWith(",,,,,,,,")){
754
					completeorder = completeorder.concat(line);
755
					if(line.contains("Ordered On")){
756
						continue;
8961 vikram.rag 757
					}
8991 vikram.rag 758
					else{
759
						lineChars = completeorder.toCharArray();
760
						int count = 0;
761
						for(int i=0;i<lineChars.length;i++)  
762
						{
763
							if(lineChars[i]=='"'){
764
								count++;
765
							}
766
							if(count%2==1){
767
								replace=false;
768
							}
769
							if(count%2==0){
770
								replace=true;
771
							}
772
							if(replace && lineChars[i] == ','){
773
								lineChars[i]='$';
774
							}
775
						}
8961 vikram.rag 776
					}
8991 vikram.rag 777
					line = String.valueOf(lineChars);
778
					System.out.println(" Line and Length " + line + " " + line.length());
779
					fw.write(line+"\n");
780
					completeorder="";
781
				}
782
				else{
783
					line = line.replace("\n","");
784
					if(completeorder==null){
785
						completeorder = line;
8961 vikram.rag 786
					}
8991 vikram.rag 787
					else{
788
						completeorder = completeorder.concat(line);;
8961 vikram.rag 789
					}
790
				}
791
			}
8991 vikram.rag 792
			counter++;
793
		}		if (br != null)br.close();
8961 vikram.rag 794
		if (fw != null)fw.close();
795
	}		
796
 
8966 vikram.rag 797
	public static void createPayment(User user, String subOrderId, double amount) throws PaymentException, TException {
8961 vikram.rag 798
		in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
8967 vikram.rag 799
		logger.info("Creating payment for user id " + user.getUserId() + " Gateway id " + FLIPKART_GATEWAY_ID);
8966 vikram.rag 800
		logger.info("Long value of transaction id : " + Long.valueOf(transactionId));
8961 vikram.rag 801
		long paymentId = client.createPayment(user.getUserId(), amount, FLIPKART_GATEWAY_ID, Long.valueOf(transactionId), false);
8966 vikram.rag 802
		logger.info("transaction id : " + Long.valueOf(transactionId) + " Payment id : " + paymentId);
8961 vikram.rag 803
		client.updatePaymentDetails(paymentId, null, null, null, null, null, null, subOrderId, null, PaymentStatus.AUTHORIZED, null, null);
804
	}   
805
 
806
 
807
}