Subversion Repositories SmartDukaan

Rev

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