Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
8182 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;
8291 amar.kumar 23
import in.shop2020.model.v1.inventory.VendorItemPricing;
8182 amar.kumar 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.SourceDetail;
32
import in.shop2020.model.v1.order.Transaction;
33
import in.shop2020.model.v1.order.TransactionStatus;
34
import in.shop2020.model.v1.order.TransactionService.Client;
35
import in.shop2020.model.v1.user.Address;
36
import in.shop2020.model.v1.user.User;
37
import in.shop2020.payments.Attribute;
38
import in.shop2020.payments.PaymentException;
39
import in.shop2020.payments.PaymentStatus;
40
import in.shop2020.thrift.clients.CatalogClient;
41
import in.shop2020.thrift.clients.InventoryClient;
42
import in.shop2020.thrift.clients.LogisticsClient;
43
import in.shop2020.thrift.clients.PaymentClient;
44
import in.shop2020.thrift.clients.TransactionClient;
45
import in.shop2020.thrift.clients.UserClient;
46
import in.shop2020.support.utils.ReportsUtils;
47
 
48
import javax.servlet.http.HttpServletRequest;
49
import javax.servlet.http.HttpSession;
50
 
51
import org.apache.commons.io.FileUtils;
52
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
53
import org.apache.poi.ss.usermodel.Cell;
54
import org.apache.poi.ss.usermodel.Row;
55
import org.apache.poi.ss.usermodel.Sheet;
56
import org.apache.poi.ss.usermodel.Workbook;
57
import org.apache.struts2.convention.annotation.InterceptorRef;
58
import org.apache.struts2.convention.annotation.InterceptorRefs;
59
import org.apache.struts2.convention.annotation.Result;
60
import org.apache.struts2.convention.annotation.Results;
61
import org.apache.struts2.interceptor.ServletRequestAware;
62
import org.apache.thrift.TException;
63
import org.slf4j.Logger;
64
import org.slf4j.LoggerFactory;
65
 
66
import com.opensymphony.xwork2.ActionSupport;
67
 
68
@SuppressWarnings("serial")
69
@InterceptorRefs({
70
    @InterceptorRef("defaultStack"),
71
    @InterceptorRef("login")
72
})
73
@Results({
74
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
75
})
76
public class EbayPsOrderCreatorController extends ActionSupport implements ServletRequestAware {
77
 
78
	private static Logger logger = LoggerFactory.getLogger(EbayPsOrderCreatorController.class);
79
 
80
	private HttpServletRequest request;
81
    private HttpSession session;
82
 
83
    private static final int EBAY_SOURCE_ID = 6;
84
 
85
    private static final int SALES_RECORD_NUM_INDEX = 0;
86
    private static final int QUANTITY_INDEX = 2;
87
    private static final int AMOUNT_INDEX = 3;
88
    private static final int TRANSACTION_DATE_INDEX = 4;
89
    private static final int SHIP_DATE_INDEX = 5;
90
    private static final int PAISAPAY_ID_INDEX = 7;
91
    private static final int COURIER_INDEX = 8;
92
    private static final int CUST_MOBILE_INDEX = 13;
93
    private static final int EBAY_LISTINGID_INDEX = 14;
94
    private static final int AWB_INDEX = 15;
95
    private static final int WAREHOUSE_ID_INDEX = 17;
96
    private static final int LISTING_PRICE_INDEX = 18;
97
 
98
 
8196 amar.kumar 99
    private static final int EBAY_GATEWAY_ID = 16;
8182 amar.kumar 100
 
101
    private static final String bluedart = "BLUE DART";
102
    private static final String aramex = "ARAMEX";
103
    private static final String dtdc = "DTDC";
104
    private static final String fedex = "FEDEX";
105
 
106
    private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
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_"+EBAY_SOURCE_ID+"_"+(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 Ebay", 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 Ebay ", e);
8303 amar.kumar 135
            setErrorMsg(getErrorMsg() + "Error in opening File for Order creation");
8182 amar.kumar 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(EBAY_SOURCE_ID);
147
        } catch (Exception e) {
148
            logger.error("Unable to establish connection to the transaction service", e);
8303 amar.kumar 149
            setErrorMsg(getErrorMsg() + "Error in Order Service while getting Ebay Source Detail");
150
            addActionError("Error in Order Service");
8182 amar.kumar 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);
8303 amar.kumar 161
	        setErrorMsg(getErrorMsg() + "Unable to get Default Email for Ebay ");
162
	        addActionError("Unable to get Default Email for Ebay ");
8182 amar.kumar 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;
8303 amar.kumar 172
        	rowId++;
8182 amar.kumar 173
            if(row.equals(firstRow))
174
                continue;
175
        	try {
8303 amar.kumar 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 Ebay ");
182
 
183
	            List<Order> orders = new ArrayList<Order>();
184
 
185
	            row.getCell(EBAY_LISTINGID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
186
	            String ebayListingId = row.getCell(EBAY_LISTINGID_INDEX).getStringCellValue();
187
	    		CatalogService.Client catalogClient = new CatalogClient().getClient();
188
	    		EbayItem ebayItem = catalogClient.getEbayItem(ebayListingId);
189
	    		double listingPrice = 0;
190
	    		double overriddenPrice = 0;
191
	    		double totalPrice = 0;
192
	    		Cell overriddenPriceCell = row.getCell(LISTING_PRICE_INDEX);
193
	        	if(overriddenPriceCell  != null && overriddenPriceCell .getCellType() != Cell.CELL_TYPE_BLANK) {
194
	        		overriddenPrice = row.getCell(LISTING_PRICE_INDEX).getNumericCellValue();
195
	        	}
196
 
197
	    		long quantity = new Double(row.getCell(QUANTITY_INDEX).getNumericCellValue()).longValue();
198
	    		String totalPriceString = row.getCell(AMOUNT_INDEX).getStringCellValue();
199
	    		if(overriddenPrice>=1) {
200
	    			totalPrice = overriddenPrice*quantity;
201
	    			listingPrice = (Double.parseDouble(totalPriceString.substring(3).replace(",","")))/quantity;
202
	    		} else {
203
	    			totalPrice = Double.parseDouble(totalPriceString.substring(3).replace(",",""));
204
	    			listingPrice = totalPrice/quantity;
205
	    		}
206
 
207
	        	LineItem lineItem = null;
208
	        	try {
209
	        		lineItem = createLineItem(ebayItem.getItemId(), quantity, totalPrice);
210
	        	} catch (Exception tex) {
211
	        		logger.error("Unable to create order for sales Rec Number " + row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue(), tex);
212
	        		setErrorMsg(getErrorMsg() + "<br>Unable to create lineitem using catalog info for RowId " + rowId);
213
	    	        addActionError("Unable to create order for sales Rec Number " + row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue());
214
	    	        continue;
215
	        	}
216
	            Order t_order = new Order();
217
	            t_order.setCustomer_id(user.getUserId());
218
	            t_order.setCustomer_email(sourceDetail.getEmail());
219
	        	t_order.setCustomer_name("Ebay");
220
	            try {
221
	            	row.getCell(CUST_MOBILE_INDEX).setCellType(Cell.CELL_TYPE_STRING);
222
	            	t_order.setCustomer_mobilenumber(row.getCell(CUST_MOBILE_INDEX).getStringCellValue());
223
	            } catch (Exception e) {
224
	            	addActionError("Error in reading mobile Number for rowNumber " + row.getRowNum());
225
	            	setErrorMsg(getErrorMsg() + "<br>Unable to create lineitem using catalog info for RowId " + rowId);
226
	            	logger.error("Error in reading mobile Number for rowNumber " + row.getRowNum());
227
	            }	
228
	            //t_order.setTotal_amount(lineItem.getTotal_price());            
229
	            t_order.setTotal_weight(lineItem.getTotal_weight());
230
	            t_order.setLineitems(Collections.singletonList(lineItem));            
231
	            t_order.setStatus(OrderStatus.PAYMENT_PENDING);
232
	            t_order.setStatusDescription("Payment Pending");
233
	            t_order.setCreated_timestamp(new Date().getTime());
234
	            t_order.setCod(false);
235
	            try {
236
	            	Date shippingDate = interchangeDateAndMonth(row.getCell(SHIP_DATE_INDEX).getDateCellValue());
237
	            	t_order.setPromised_shipping_time(shippingDate.getTime());
238
	            	t_order.setExpected_shipping_time(shippingDate.getTime());
239
	            	/*t_order.setPromised_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());
240
	            	t_order.setExpected_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());*/
241
	            	Calendar time = Calendar.getInstance();
242
	            	time.setTimeInMillis(t_order.getExpected_shipping_time());
243
	            	time.add(Calendar.DAY_OF_MONTH, 3);
244
	            	t_order.setPromised_delivery_time(time.getTimeInMillis());
245
	            	t_order.setExpected_delivery_time(time.getTimeInMillis());
246
	            } catch(Exception e) {
247
	            	addActionError("Error in updating Shipping Time for row number " + rowId);
248
	            	logger.error("Error in updating Shipping Time for row number " + rowId,e);
8343 amar.kumar 249
	            	continue;
8303 amar.kumar 250
	            }
251
 
252
	            //TODO Delivery time
253
	            InventoryService.Client inventoryClient = null;
254
	            Warehouse fulfillmentWarehouse= null; 
255
	            try {
256
	            	inventoryClient = new InventoryClient().getClient();
257
	            	Cell warehouseCell = row.getCell(WAREHOUSE_ID_INDEX);
258
	            	if(warehouseCell != null && warehouseCell.getCellType() != Cell.CELL_TYPE_BLANK) { 
259
	            		fulfillmentWarehouse = inventoryClient.getWarehouse(new Double(row.getCell(WAREHOUSE_ID_INDEX).getNumericCellValue()).longValue());
260
 
261
	            	} else if (ebayItem.getDefaultWarehouseId()!=0 ){
262
	            		fulfillmentWarehouse = inventoryClient.getWarehouse(ebayItem.getDefaultWarehouseId());
263
	            	} else {
264
	            		List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(ebayItem.getItemId(), 1);
265
	            		fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
266
	            	}
267
	            	t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
268
	        		t_order.setWarehouse_id(fulfillmentWarehouse.getBillingWarehouseId());
269
 
270
	        		VendorItemPricing vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), fulfillmentWarehouse.getVendor().getId());
271
	        		t_order.getLineitems().get(0).setTransfer_price(vendorItemPricing.getTransferPrice());
272
	        		t_order.getLineitems().get(0).setNlc(vendorItemPricing.getNlc());
273
				} catch (InventoryServiceException e) {
274
					addActionError("Error in updating WarehouseId for row number " + rowId);
275
					setErrorMsg(getErrorMsg() + "<br>Error in updating WarehouseId for row number  " + rowId);
276
	            	logger.error("Error in updating WarehouseId for row number " + rowId,e);
277
	            	return "authsuccess";
278
				}
279
 
280
				String provider = row.getCell(COURIER_INDEX).getStringCellValue();
281
				if(provider.equals(bluedart)) {
282
					t_order.setLogistics_provider_id(8);
283
				} else if(provider.equals(aramex)) {
284
					t_order.setLogistics_provider_id(9);
285
				} else if(provider.equals(dtdc)) {
286
					t_order.setLogistics_provider_id(10);
287
				} else if(provider.equals(fedex)) {
288
					t_order.setLogistics_provider_id(11);
289
				} else {
290
					//TODO Continue and proceed with next row
291
				}
292
 
293
				row.getCell(AWB_INDEX).setCellType(Cell.CELL_TYPE_STRING);
294
				t_order.setAirwaybill_no(row.getCell(AWB_INDEX).getStringCellValue());
295
				t_order.setTracking_id(row.getCell(AWB_INDEX).getStringCellValue());
296
	            t_order.setTotal_amount(totalPrice);
297
	            t_order.setOrderType(OrderType.B2C);
298
	            t_order.setSource(EBAY_SOURCE_ID);
299
	            orders.add(t_order);
300
	            orderCountForRow++;
301
 
302
	            txn.setOrders(orders);
303
	            Client transaction_client = new TransactionClient().getClient();
304
	            try {
305
	            	long salesRecNumber = new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue();
306
	            	if(transaction_client.ebayOrderExists(salesRecNumber, ebayItem.getEbayListingId())) {
307
	            		setErrorMsg(getErrorMsg() + "<br>Duplicate order for salesRecNumber " + salesRecNumber + " and listingId " + ebayItem.getEbayListingId() + " for row number  " + rowId);
308
	            		logger.error("Duplicate order for salesRecNumber " + salesRecNumber + " and listingId " + ebayItem.getEbayListingId());
8342 amar.kumar 309
	            		continue;
8303 amar.kumar 310
	            	}
311
 
312
	            	transactionId =  String.valueOf(transaction_client.createTransaction(txn));
313
	            	row.getCell(PAISAPAY_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
314
	            	String paisaPayId = row.getCell(PAISAPAY_ID_INDEX).getStringCellValue();
315
	            	createPayment(user, paisaPayId, totalPrice);
316
 
317
	                logger.info("Successfully created transaction: " + transactionId + " for amount: " + totalPrice);
318
 
319
	                Transaction transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
320
	                Order order = transaction.getOrders().get(0);
321
 
322
	                inventoryClient.reserveItemInWarehouse(ebayItem.getItemId(), fulfillmentWarehouse.getId(), 1, 
323
	                		order.getId(), order.getCreated_timestamp(), order.getPromised_shipping_time(), order.getLineitems().get(0).getQuantity());
324
 
325
	                EbayOrder ebayOrder = new EbayOrder();
326
	                ebayOrder.setEbayListingId(ebayItem.getEbayListingId());
327
	                ebayOrder.setSalesRecordNumber(new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue());
328
	                try {
329
	                	Date ebayTransactionDate = interchangeDateAndMonth(row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue());
330
	                	ebayOrder.setEbayTxnDate(ebayTransactionDate.getTime());
331
	                } catch (Exception e) {
332
	                	logger.error("Error in setting transaction date for Ebay Order with OrderId : " + order.getId());
333
	                }
334
	                ebayOrder.setOrderId(order.getId());
335
	                ebayOrder.setPaisaPayId(paisaPayId);
336
	                ebayOrder.setListingName(ebayItem.getListingName());
337
	                ebayOrder.setSubsidyAmount(ebayItem.getSubsidy()*quantity);
338
	                ebayOrder.setListingPrice(listingPrice);
339
	                transaction_client.createEbayOrder(ebayOrder);
340
	            } catch (Exception e) {
341
	                logger.error("Error while creating order for rowId " + rowId, e);
342
	                addActionError("Error while creating order for rowId " + rowId);
343
	                setErrorMsg(getErrorMsg() + "<br>Error while creating order for row number " + rowId);
344
	                continue;
345
	    		}
346
        	} catch (Exception e) {
347
        		logger.error("Error while creating order for row number " + rowId);
348
        		setErrorMsg(getErrorMsg() + "<br>Error while creating order for row number " + rowId);
349
        		continue;
8182 amar.kumar 350
        	}
351
        }
352
 
353
        checkForErrors();
354
        return "authsuccess";
355
    }
356
 
8281 amar.kumar 357
    private Date interchangeDateAndMonth(Date date) {
358
		Date updatedDate = new Date(date.getTime());
8286 amar.kumar 359
		updatedDate.setDate(date.getMonth() + 1);
360
		updatedDate.setMonth(date.getDate() - 1);
8281 amar.kumar 361
		return updatedDate;
362
	}
363
 
364
	private LineItem createLineItem(long itemId, long quantity, double amount) throws CatalogServiceException, TException {
8182 amar.kumar 365
    	LineItem lineItem = new LineItem();
366
    	CatalogService.Client catalogClient = new CatalogClient().getClient();
367
    	Item item = catalogClient.getItem(itemId);
368
 
369
    	lineItem.setProductGroup(item.getProductGroup());
370
        lineItem.setBrand(item.getBrand());
371
        lineItem.setModel_number(item.getModelNumber());
372
        lineItem.setModel_name(item.getModelName());
373
        lineItem.setExtra_info(item.getFeatureDescription());
374
        lineItem.setQuantity(quantity);
375
        lineItem.setItem_id(item.getId());
8241 amar.kumar 376
        lineItem.setUnit_weight(item.getWeight());
377
        lineItem.setTotal_weight(item.getWeight()*quantity);
8182 amar.kumar 378
        lineItem.setUnit_price(amount/quantity);
379
        lineItem.setTotal_price(amount);
380
 
381
        if (item.getColor() == null || "NA".equals(item.getColor())) {
382
            lineItem.setColor("");
383
        } else {
384
            lineItem.setColor(item.getColor());
385
        }
386
    	return lineItem;
387
	}
388
 
389
    private void createPayment(User user, String paisaPayId, double amount) throws NumberFormatException, PaymentException, TException {
390
        in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
391
        long paymentId = client.createPayment(user.getUserId(), amount, EBAY_GATEWAY_ID, Long.valueOf(transactionId), false);
392
        client.updatePaymentDetails(paymentId, null, null, null, null, null, null, paisaPayId, null, PaymentStatus.PENDING, null, null);
393
    }   
394
 
395
	public String index() {
396
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), "/ebay-dashboard"))
397
            return "authfail";
398
        checkForErrors();
399
        return "authsuccess";
400
    }
401
 
402
	private boolean checkForErrors(){
403
        Collection<String> actionErrors = getActionErrors();
404
        if(actionErrors != null && !actionErrors.isEmpty()){
405
            for (String str : actionErrors) {
406
                errorMsg += "<BR/>" + str;
407
            }
408
            if(rowId>1) {
409
            	errorMsg += "<BR/>" + "Error while processing rowNumber : " + rowId;
410
            }
411
            return true;
412
        }
413
        return false;
414
    }
415
 
416
	@Override
417
	public void setServletRequest(HttpServletRequest request) {
418
		this.request = request;
419
        this.session = request.getSession();
420
	}
421
 
422
	public String getErrorMsg() {
423
		return errorMsg;
424
	}
425
 
426
	public void setErrorMsg(String errorMsg) {
427
		this.errorMsg = errorMsg;
428
	}
429
 
430
	public Long getRowId() {
431
		return rowId;
432
	}
433
 
434
	public void setRowId(Long rowId) {
435
		this.rowId = rowId;
436
	}
437
 
438
	public File getOrderDataFile() {
439
		return orderDataFile;
440
	}
441
 
442
	public void setOrderDataFile(File orderDataFile) {
443
		this.orderDataFile = orderDataFile;
444
	}
445
 
8303 amar.kumar 446
 
8182 amar.kumar 447
 
448
}