Subversion Repositories SmartDukaan

Rev

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