Subversion Repositories SmartDukaan

Rev

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