Subversion Repositories SmartDukaan

Rev

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