Subversion Repositories SmartDukaan

Rev

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