Subversion Repositories SmartDukaan

Rev

Rev 8802 | Rev 9110 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
8488 amar.kumar 1
package in.shop2020.support.controllers;
2
 
3
import java.io.File;
4
import java.io.FileInputStream;
5
import java.text.SimpleDateFormat;
6
import java.util.ArrayList;
7
import java.util.Calendar;
8
import java.util.Collection;
9
import java.util.Collections;
10
import java.util.Date;
11
import java.util.List;
12
 
13
import in.shop2020.logistics.DeliveryType;
14
import in.shop2020.logistics.LogisticsInfo;
15
import in.shop2020.logistics.LogisticsService;
16
import in.shop2020.logistics.PickUpType;
17
import in.shop2020.model.v1.catalog.CatalogService;
18
import in.shop2020.model.v1.catalog.CatalogServiceException;
19
import in.shop2020.model.v1.catalog.EbayItem;
20
import in.shop2020.model.v1.catalog.Item;
21
import in.shop2020.model.v1.inventory.InventoryService;
22
import in.shop2020.model.v1.inventory.InventoryServiceException;
8892 amar.kumar 23
import in.shop2020.model.v1.inventory.InventoryType;
8488 amar.kumar 24
import in.shop2020.model.v1.inventory.VendorItemPricing;
25
import in.shop2020.model.v1.inventory.Warehouse;
8892 amar.kumar 26
import in.shop2020.model.v1.inventory.WarehouseType;
8488 amar.kumar 27
import in.shop2020.model.v1.order.LineItem;
28
import in.shop2020.model.v1.order.Order;
29
import in.shop2020.model.v1.order.OrderSource;
30
import in.shop2020.model.v1.order.OrderStatus;
31
import in.shop2020.model.v1.order.OrderType;
32
import in.shop2020.model.v1.order.SnapdealOrder;
33
import in.shop2020.model.v1.order.SourceDetail;
34
import in.shop2020.model.v1.order.Transaction;
35
import in.shop2020.model.v1.order.TransactionStatus;
36
import in.shop2020.model.v1.order.TransactionService.Client;
37
import in.shop2020.model.v1.user.Address;
38
import in.shop2020.model.v1.user.User;
39
import in.shop2020.payments.Attribute;
40
import in.shop2020.payments.PaymentException;
41
import in.shop2020.payments.PaymentStatus;
42
import in.shop2020.thrift.clients.CatalogClient;
43
import in.shop2020.thrift.clients.InventoryClient;
44
import in.shop2020.thrift.clients.LogisticsClient;
45
import in.shop2020.thrift.clients.PaymentClient;
46
import in.shop2020.thrift.clients.TransactionClient;
47
import in.shop2020.thrift.clients.UserClient;
48
import in.shop2020.support.utils.ReportsUtils;
49
 
50
import javax.servlet.http.HttpServletRequest;
51
import javax.servlet.http.HttpSession;
52
 
53
import org.apache.commons.io.FileUtils;
54
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
55
import org.apache.poi.ss.usermodel.Cell;
56
import org.apache.poi.ss.usermodel.Row;
57
import org.apache.poi.ss.usermodel.Sheet;
58
import org.apache.poi.ss.usermodel.Workbook;
59
import org.apache.struts2.convention.annotation.InterceptorRef;
60
import org.apache.struts2.convention.annotation.InterceptorRefs;
61
import org.apache.struts2.convention.annotation.Result;
62
import org.apache.struts2.convention.annotation.Results;
63
import org.apache.struts2.interceptor.ServletRequestAware;
64
import org.apache.thrift.TException;
65
import org.slf4j.Logger;
66
import org.slf4j.LoggerFactory;
67
 
68
import com.opensymphony.xwork2.ActionSupport;
69
 
70
@SuppressWarnings("serial")
71
@InterceptorRefs({
72
    @InterceptorRef("defaultStack"),
73
    @InterceptorRef("login")
74
})
75
@Results({
76
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
77
})
78
public class SnapdealOrderCreatorController extends ActionSupport implements ServletRequestAware {
79
 
80
	private static Logger logger = LoggerFactory.getLogger(SnapdealOrderCreatorController.class);
81
 
82
	private HttpServletRequest request;
83
    private HttpSession session;
84
 
85
    private static final int SNAPDEAL_SOURCE_ID = 7;
86
 
87
    private static final int COURIER_INDEX = 0;
88
    private static final int PRODUCT_NAME_INDEX = 1;
89
    private static final int REFERENCE_CODE_INDEX = 2;
90
    private static final int SUBORDER_ID_INDEX = 3;
91
    private static final int ITEMID_INDEX = 4;
92
    private static final int AWB_INDEX = 5;
93
    private static final int TRANSACTION_DATE_INDEX = 6;
94
    private static final int BUYER_NAME_INDEX = 8;
95
    private static final int CITY_INDEX = 9;
96
    private static final int STATE_INDEX = 10;
97
    private static final int PINCODE_INDEX = 11;
98
    private static final int AMOUNT_INDEX = 12;
99
    private static final int WAREHOUSE_ID_INDEX = 14;
100
    private static final int OVERRIDE_BILLING_PRICE_INDEX = 15;
101
 
102
 
103
    private static final int SNAPDEAL_GATEWAY_ID = 18;
104
 
105
    private static final String FIRSTFLIGHT = "First Flight";
8797 anupam.sin 106
    private static final String DELHIVERY = "Delhivery";
8508 amar.kumar 107
    private static final String BLUEDART = "Bluedart";
8796 anupam.sin 108
    private static final String ECOM = "Ecom Express";
8488 amar.kumar 109
 
110
    private File orderDataFile;
111
    private String orderDataFileName;
112
    private String transactionId;
113
    private String errorMsg = "";
114
    private Long rowId = 0L;
115
 
116
    public String create() throws TException {
117
        File fileToCreate = null;
118
        orderDataFileName = "OrderSheet_Snapdeal_"+(new Date().toString());
119
        try {
120
            fileToCreate = new File("/tmp/", this.orderDataFileName);
121
            FileUtils.copyFile(this.orderDataFile, fileToCreate);
122
        } catch (Exception e) {
123
           logger.error("Error while writing order data file to the local file system for Snapdeal", e);
124
           addActionError("Error while writing order data file to the local file system");
125
        }
126
 
127
 
128
        if(checkForErrors())
129
            return "authsuccess";
130
 
131
        //Parse the file and submit the data for update to the transaction service
132
        Workbook wb = null;
133
        try {
134
            wb = new HSSFWorkbook(new FileInputStream(fileToCreate));
135
        } catch (Exception e) {
136
            logger.error("Unable to open the File for Order Creation for Snapdeal ", e);
137
            setErrorMsg(getErrorMsg() + "Error in opening File for Order creation");
138
            addActionError("Unable to open the File for Order creation");
139
        }
140
        if(checkForErrors())
141
            return "authsuccess";
142
 
143
        SourceDetail sourceDetail = null;
144
        User user = null;
145
        TransactionClient tsc = null;
146
        try {
147
            tsc = new TransactionClient();
148
			sourceDetail = tsc.getClient().getSourceDetail(SNAPDEAL_SOURCE_ID);
149
        } catch (Exception e) {
150
            logger.error("Unable to establish connection to the transaction service while getting Snapdeal Source Detail", e);
151
            setErrorMsg(getErrorMsg() + "Error in Order Service while getting Snapdeal Source Detail");
152
            addActionError("Error in connecting to Order Service");
153
		}
154
 
155
        if(checkForErrors())
156
            return "authsuccess";
157
 
158
	    try {   
159
	        in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
160
	        user = userClient.getUserByEmail(sourceDetail.getEmail());
161
	    } catch (Exception e) {
162
	        logger.error("Unable to establish connection to the User service", e);
163
	        setErrorMsg(getErrorMsg() + "Unable to get Default Email for Snapdeal ");
164
	        addActionError("Unable to get Default Email for Snapdeal ");
165
		}
166
 
167
        if(checkForErrors())
168
            return "authsuccess";
169
 
170
        Sheet sheet = wb.getSheetAt(0);
171
        Row firstRow = sheet.getRow(0);
172
        for (Row row : sheet) {
173
        	long orderCountForRow = 0;
174
        	rowId++;
175
            if(row.equals(firstRow))
176
                continue;
177
        	try {
178
	            Transaction txn = new Transaction();
179
	            txn.setShoppingCartid(user.getActiveCartId());
180
	            txn.setCustomer_id(user.getUserId());
181
	            txn.setCreatedOn(new Date().getTime());
182
	            txn.setTransactionStatus(TransactionStatus.INIT);
183
	            txn.setStatusDescription("Order for Snapdeal ");
184
 
185
	            List<Order> orders = new ArrayList<Order>();
186
 
187
	            row.getCell(ITEMID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
188
	            Long itemId = Long.parseLong(row.getCell(ITEMID_INDEX).getStringCellValue());
189
	    		double listingPrice = 0;
190
	    		double overriddenPrice = 0;
191
	    		double totalPrice = 0;
192
	    		Cell overriddenPriceCell = row.getCell(OVERRIDE_BILLING_PRICE_INDEX);
193
	        	if(overriddenPriceCell  != null && overriddenPriceCell .getCellType() != Cell.CELL_TYPE_BLANK) {
194
	        		overriddenPrice = row.getCell(OVERRIDE_BILLING_PRICE_INDEX).getNumericCellValue();
195
	        	}
196
 
197
	    		totalPrice = row.getCell(AMOUNT_INDEX).getNumericCellValue();
198
	    		listingPrice = totalPrice;
199
	    		if(overriddenPrice>=1) {
200
	    			totalPrice = overriddenPrice;
201
	    		}
202
	        	LineItem lineItem = null;
203
	        	try {
204
	        		lineItem = createLineItem(itemId, totalPrice);
8569 amar.kumar 205
	        		Double subOrderId = row.getCell(SUBORDER_ID_INDEX).getNumericCellValue();
206
	            	String refCode = row.getCell(REFERENCE_CODE_INDEX).getStringCellValue();
207
	        		lineItem.setExtra_info("SubOrderId = " + subOrderId + " ReferenceCode = " + refCode);
8488 amar.kumar 208
	        	} catch (Exception tex) {
209
	        		logger.error("Unable to create order for RowId " + rowId, tex);
210
	        		setErrorMsg(getErrorMsg() + "<br>Unable to create lineitem using catalog info for RowId " + rowId);
211
	    	        continue;
212
	        	}
213
	            Order t_order = new Order();
214
	            t_order.setCustomer_id(user.getUserId());
215
	            t_order.setCustomer_email(sourceDetail.getEmail());
216
	            row.getCell(BUYER_NAME_INDEX).setCellType(Cell.CELL_TYPE_STRING);
217
	        	t_order.setCustomer_name(row.getCell(BUYER_NAME_INDEX).getStringCellValue());
218
	        	t_order.setCustomer_address1("");
219
	        	t_order.setCustomer_address2("");
220
	        	t_order.setCustomer_city(row.getCell(CITY_INDEX).getStringCellValue());
221
	        	t_order.setCustomer_state(row.getCell(STATE_INDEX).getStringCellValue());
222
	        	row.getCell(PINCODE_INDEX).setCellType(Cell.CELL_TYPE_STRING);
223
	        	t_order.setCustomer_pincode(row.getCell(PINCODE_INDEX).getStringCellValue());
224
	            t_order.setTotal_amount(lineItem.getTotal_price());            
225
	            t_order.setTotal_weight(lineItem.getTotal_weight());
226
	            t_order.setLineitems(Collections.singletonList(lineItem));            
8761 vikram.rag 227
	            t_order.setStatus(OrderStatus.PAYMENT_PENDING);
8488 amar.kumar 228
	            t_order.setStatusDescription("In Process");
229
	            t_order.setCreated_timestamp(new Date().getTime());
230
	            t_order.setOrderType(OrderType.B2C);
231
	            t_order.setCod(false);
232
	            try {
233
	            	Calendar time = Calendar.getInstance();
234
	            	time.add(Calendar.DAY_OF_MONTH, 1);
235
	            	t_order.setPromised_shipping_time(time.getTimeInMillis());
236
	            	t_order.setExpected_shipping_time(time.getTimeInMillis());
237
	            	time.add(Calendar.DAY_OF_MONTH, 3);
238
	            	t_order.setPromised_delivery_time(time.getTimeInMillis());
239
	            	t_order.setExpected_delivery_time(time.getTimeInMillis());
240
	            } catch(Exception e) {
241
	            	addActionError("Error in updating Shipping or Delivery Time for row number " + rowId);
242
	            	logger.error("Error in updating Shipping or Delivery Time for row number " + rowId,e);
243
	            	continue;
244
	            }
245
 
246
	            InventoryService.Client inventoryClient = null;
247
	            Warehouse fulfillmentWarehouse= null; 
248
	            try {
249
	            	inventoryClient = new InventoryClient().getClient();
250
	            	Cell warehouseCell = row.getCell(WAREHOUSE_ID_INDEX);
251
	            	if(warehouseCell != null && warehouseCell.getCellType() != Cell.CELL_TYPE_BLANK) {
252
	            		fulfillmentWarehouse = inventoryClient.getWarehouse(new Double(row.getCell(WAREHOUSE_ID_INDEX).getNumericCellValue()).longValue());
253
	            	} else {
254
	            		List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(itemId, 1);
255
	            		fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
256
	            	}
257
	            	t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
8892 amar.kumar 258
 
259
					long billingWarehouseId = 0;
260
					if(fulfillmentWarehouse.getBillingWarehouseId()== 0) {
261
						inventoryClient = new InventoryClient().getClient();
262
						List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, fulfillmentWarehouse.getVendor().getId(), 0, 0);
263
						for(Warehouse warehouse : warehouses) {
264
							if(warehouse.getBillingWarehouseId()!=0) {
265
								billingWarehouseId = warehouse.getBillingWarehouseId();
266
				                break;
267
							}
268
						}
269
					} else {
270
						billingWarehouseId = fulfillmentWarehouse.getBillingWarehouseId();
271
					}
272
 
273
					t_order.setWarehouse_id(billingWarehouseId);
274
					//t_order.setWarehouse_id(fulfillmentWarehouse.getBillingWarehouseId());
8488 amar.kumar 275
	        		VendorItemPricing vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), fulfillmentWarehouse.getVendor().getId());
276
	        		t_order.getLineitems().get(0).setTransfer_price(vendorItemPricing.getTransferPrice());
277
	        		t_order.getLineitems().get(0).setNlc(vendorItemPricing.getNlc());
278
				} catch (InventoryServiceException e) {
279
					addActionError("Error in updating WarehouseId for row number " + rowId);
280
					setErrorMsg(getErrorMsg() + "<br>Error in updating WarehouseId for row number  " + rowId);
281
	            	logger.error("Error in updating WarehouseId for row number " + rowId,e);
282
	            	continue;
283
				}
284
 
285
				String provider = row.getCell(COURIER_INDEX).getStringCellValue();
286
				if(provider.equals(FIRSTFLIGHT)) {
287
					t_order.setLogistics_provider_id(12);
288
				} else if(provider.equals(DELHIVERY)) {
289
					t_order.setLogistics_provider_id(13);
8508 amar.kumar 290
				} else if(provider.equals(BLUEDART)) {
291
					t_order.setLogistics_provider_id(14);
8796 anupam.sin 292
				} else if(provider.equals(ECOM)) {
293
                    t_order.setLogistics_provider_id(18);
294
                } else {
8488 amar.kumar 295
					addActionError("Unknown logistics provider found for row number " + rowId);
296
					setErrorMsg(getErrorMsg() + "<br>Unknown logistics provider found for row number " + rowId);
297
	            	logger.error("Unknown logistics provider found for row number " + rowId);
298
	            	continue;
299
				}
300
 
301
				row.getCell(AWB_INDEX).setCellType(Cell.CELL_TYPE_STRING);
302
				t_order.setAirwaybill_no(row.getCell(AWB_INDEX).getStringCellValue());
303
				t_order.setTracking_id(row.getCell(AWB_INDEX).getStringCellValue());
304
	            t_order.setTotal_amount(totalPrice);
305
	            t_order.setOrderType(OrderType.B2C);
306
	            t_order.setSource(SNAPDEAL_SOURCE_ID);
307
	            t_order.setOrderType(OrderType.B2C);
308
	            orders.add(t_order);
309
	            orderCountForRow++;
310
 
311
	            txn.setOrders(orders);
312
	            Client transaction_client = new TransactionClient().getClient();
313
	            try {
314
	            	long subOrderId = new Double(row.getCell(SUBORDER_ID_INDEX).getNumericCellValue()).longValue();
315
	            	String referenceCode = row.getCell(REFERENCE_CODE_INDEX).getStringCellValue();
316
	            	String productName = row.getCell(PRODUCT_NAME_INDEX).getStringCellValue();
317
	            	Date snapdealTxnDate = row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue();
318
 
8802 amar.kumar 319
	            	if(transaction_client.snapdealOrderExists(subOrderId, referenceCode)) {
8488 amar.kumar 320
	            		setErrorMsg(getErrorMsg() + "<br>Duplicate order for subOrderId " + subOrderId + " for row number  " + rowId);
321
	            		logger.error("Duplicate order for subOrderId " + subOrderId + " for row number  " + rowId);
322
	            		continue;
323
	            	}
324
 
325
	            	transactionId =  String.valueOf(transaction_client.createTransaction(txn));
326
	            	createPayment(user, (new Long(subOrderId)).toString(), totalPrice);
327
 
328
	                logger.info("Successfully created transaction: " + transactionId + " for amount: " + totalPrice);
329
 
330
	                Transaction transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
331
	                Order order = transaction.getOrders().get(0);
332
 
333
	                inventoryClient.reserveItemInWarehouse(itemId, fulfillmentWarehouse.getId(), 1, 
334
	                		order.getId(), order.getCreated_timestamp(), order.getPromised_shipping_time(), order.getLineitems().get(0).getQuantity());
335
 
336
 
337
	                SnapdealOrder snapdealOrder = new SnapdealOrder();
338
	                snapdealOrder.setOrderId(order.getId());
339
	                snapdealOrder.setSubOrderId(subOrderId);
340
	                snapdealOrder.setReferenceCode(referenceCode);
341
	                snapdealOrder.setProductName(productName);
342
	                snapdealOrder.setSnapdealTxnDate(snapdealTxnDate.getTime());
343
	                snapdealOrder.setListingPrice(listingPrice);
344
	                transaction_client.createSnapdealOrder(snapdealOrder);
345
 
346
 
347
	            } catch (Exception e) {
348
	                logger.error("Error while creating order for rowId " + rowId, e);
349
	                addActionError("Error while creating order for rowId " + rowId);
350
	                setErrorMsg(getErrorMsg() + "<br>Error while creating order for row number " + rowId);
351
	                continue;
352
	    		}
353
        	} catch (Exception e) {
8748 amar.kumar 354
        		logger.error("Error while creating order for row number " + rowId, e);
8488 amar.kumar 355
        		setErrorMsg(getErrorMsg() + "<br>Error while creating order for row number " + rowId);
356
        		continue;
357
        	}
358
        }
359
 
360
        checkForErrors();
361
        return "authsuccess";
362
    }
363
 
364
    private Date interchangeDateAndMonth(Date date) {
365
		Date updatedDate = new Date(date.getTime());
366
		updatedDate.setDate(date.getMonth() + 1);
367
		updatedDate.setMonth(date.getDate() - 1);
368
		return updatedDate;
369
	}
370
 
371
	private LineItem createLineItem(long itemId, double amount) throws CatalogServiceException, TException {
372
    	LineItem lineItem = new LineItem();
373
    	CatalogService.Client catalogClient = new CatalogClient().getClient();
374
    	Item item = catalogClient.getItem(itemId);
375
 
376
    	lineItem.setProductGroup(item.getProductGroup());
377
        lineItem.setBrand(item.getBrand());
378
        lineItem.setModel_number(item.getModelNumber());
379
        lineItem.setModel_name(item.getModelName());
380
        lineItem.setExtra_info(item.getFeatureDescription());
381
        lineItem.setQuantity(1);
382
        lineItem.setItem_id(item.getId());
383
        lineItem.setUnit_weight(item.getWeight());
384
        lineItem.setTotal_weight(item.getWeight());
385
        lineItem.setUnit_price(amount);
386
        lineItem.setTotal_price(amount);
387
 
388
        if (item.getColor() == null || "NA".equals(item.getColor())) {
389
            lineItem.setColor("");
390
        } else {
391
            lineItem.setColor(item.getColor());
392
        }
393
    	return lineItem;
394
	}
395
 
396
    private void createPayment(User user, String subOrderId, double amount) throws NumberFormatException, PaymentException, TException {
397
        in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
398
        long paymentId = client.createPayment(user.getUserId(), amount, SNAPDEAL_GATEWAY_ID, Long.valueOf(transactionId), false);
399
        client.updatePaymentDetails(paymentId, null, null, null, null, null, null, subOrderId, null, PaymentStatus.AUTHORIZED, null, null);
400
    }   
401
 
402
	public String index() {
403
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), "/ebay-dashboard"))
404
            return "authfail";
405
        checkForErrors();
406
        return "authsuccess";
407
    }
408
 
409
	private boolean checkForErrors(){
410
        Collection<String> actionErrors = getActionErrors();
411
        if(actionErrors != null && !actionErrors.isEmpty()){
412
            for (String str : actionErrors) {
413
                errorMsg += "<BR/>" + str;
414
            }
415
            return true;
416
        }
417
        return false;
418
    }
419
 
420
	@Override
421
	public void setServletRequest(HttpServletRequest request) {
422
		this.request = request;
423
        this.session = request.getSession();
424
	}
425
 
426
	public String getErrorMsg() {
427
		return errorMsg;
428
	}
429
 
430
	public void setErrorMsg(String errorMsg) {
431
		this.errorMsg = errorMsg;
432
	}
433
 
434
	public Long getRowId() {
435
		return rowId;
436
	}
437
 
438
	public void setRowId(Long rowId) {
439
		this.rowId = rowId;
440
	}
441
 
442
	public File getOrderDataFile() {
443
		return orderDataFile;
444
	}
445
 
446
	public void setOrderDataFile(File orderDataFile) {
447
		this.orderDataFile = orderDataFile;
448
	}
449
 
450
}