Subversion Repositories SmartDukaan

Rev

Rev 8196 | Go to most recent revision | Details | 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
 
98
    private static final int EBAY_GATEWAY_ID = 6;
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);
189
    		long quantity = new Double(row.getCell(QUANTITY_INDEX).getNumericCellValue()).longValue();
190
    		String totalPriceString = row.getCell(AMOUNT_INDEX).getStringCellValue();
191
    		double totalPrice = Double.parseDouble(totalPriceString.substring(3).replace(",","")); 
192
 
193
        	LineItem lineItem = null;
194
        	try {
195
        		lineItem = createLineItem(ebayItem.getItemId(), quantity, totalPrice);
196
        	} catch (Exception tex) {
197
        		logger.error("Unable to create order for sales Rec Number " + row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue(), tex);
198
    	        addActionError("Unable to create order for sales Rec Number " + row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue());
199
    	        return "authsuccess";
200
        	}
201
            Order t_order = new Order();
202
            t_order.setCustomer_id(user.getUserId());
203
            t_order.setCustomer_email(sourceDetail.getEmail());
204
        	t_order.setCustomer_name("Ebay");
205
            try {
206
            	row.getCell(CUST_MOBILE_INDEX).setCellType(Cell.CELL_TYPE_STRING);
207
            	t_order.setCustomer_mobilenumber(row.getCell(CUST_MOBILE_INDEX).getStringCellValue());
208
            } catch (Exception e) {
209
            	addActionError("Error in reading mobile Number for rowNumber " + row.getRowNum());
210
            	logger.error("Error in reading mobile Number for rowNumber " + row.getRowNum());
211
            }	
212
            //t_order.setTotal_amount(lineItem.getTotal_price());            
213
            t_order.setTotal_weight(lineItem.getTotal_weight());
214
            t_order.setLineitems(Collections.singletonList(lineItem));            
215
            t_order.setStatus(OrderStatus.PAYMENT_PENDING);
216
            t_order.setStatusDescription("Payment Pending");
217
            t_order.setCreated_timestamp(new Date().getTime());
218
            try {
219
            	t_order.setPromised_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());
220
            	t_order.setExpected_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());
221
            	Calendar time = Calendar.getInstance();
222
            	time.setTimeInMillis(t_order.getExpected_shipping_time());
223
            	time.add(Calendar.DAY_OF_MONTH, 3);
224
            	t_order.setPromised_delivery_time(time.getTimeInMillis());
225
            	t_order.setExpected_delivery_time(time.getTimeInMillis());
226
            } catch(Exception e) {
227
            	addActionError("Error in updating Shipping Time for row number " + (rowId + 1));
228
            	logger.error("Error in updating Shipping Time for row number " + (rowId + 1),e);
229
            }
230
 
231
            //TODO Delivery time
232
            InventoryService.Client inventoryClient = null;
233
            Warehouse fulfillmentWarehouse= null; 
234
            try {
235
            	inventoryClient = new InventoryClient().getClient();
236
            	Cell warehouseCell = row.getCell(WAREHOUSE_ID_INDEX);
237
            	if(warehouseCell != null && warehouseCell.getCellType() != Cell.CELL_TYPE_BLANK) { 
238
            		fulfillmentWarehouse = inventoryClient.getWarehouse(new Double(row.getCell(WAREHOUSE_ID_INDEX).getNumericCellValue()).longValue());
239
 
240
            	} else if (ebayItem.getDefaultWarehouseId()!=0 ){
241
            		fulfillmentWarehouse = inventoryClient.getWarehouse(ebayItem.getDefaultWarehouseId());
242
            	} else {
243
            		List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(ebayItem.getItemId(), 1);
244
            		fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
245
            	}
246
            	t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
247
        		t_order.setWarehouse_id(fulfillmentWarehouse.getBillingWarehouseId());
248
			} catch (InventoryServiceException e) {
249
				addActionError("Error in updating WarehouseId for row number " + (rowId + 1));
250
            	logger.error("Error in updating WarehouseId for row number " + (rowId + 1),e);
251
            	return "authsuccess";
252
			}
253
 
254
			String provider = row.getCell(COURIER_INDEX).getStringCellValue();
255
			if(provider.equals(bluedart)) {
256
				t_order.setLogistics_provider_id(8);
257
			} else if(provider.equals(aramex)) {
258
				t_order.setLogistics_provider_id(9);
259
			} else if(provider.equals(dtdc)) {
260
				t_order.setLogistics_provider_id(10);
261
			} else if(provider.equals(fedex)) {
262
				t_order.setLogistics_provider_id(11);
263
			} else {
264
				//TODO Continue and proceed with next row
265
			}
266
 
267
			row.getCell(AWB_INDEX).setCellType(Cell.CELL_TYPE_STRING);
268
			t_order.setAirwaybill_no(row.getCell(AWB_INDEX).getStringCellValue());
269
			t_order.setTracking_id(row.getCell(AWB_INDEX).getStringCellValue());
270
            t_order.setTotal_amount(totalPrice);
271
            t_order.setOrderType(OrderType.B2C);
272
            t_order.setSource(EBAY_SOURCE_ID);
273
            orders.add(t_order);
274
            orderCountForRow++;
275
 
276
            txn.setOrders(orders);
277
            Client transaction_client = new TransactionClient().getClient();
278
            try {
279
            	long salesRecNumber = new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue();
280
            	if(transaction_client.ebayOrderExists(salesRecNumber, ebayItem.getEbayListingId())) {
281
            		throw new Exception("Duplicate order for salesRecNumber " + salesRecNumber + " and listingId " + ebayItem.getEbayListingId());
282
            	}
283
 
284
            	transactionId =  String.valueOf(transaction_client.createTransaction(txn));
285
            	row.getCell(PAISAPAY_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
286
            	String paisaPayId = row.getCell(PAISAPAY_ID_INDEX).getStringCellValue();
287
            	createPayment(user, paisaPayId, totalPrice);
288
 
289
            	/*in.shop2020.model.v1.order.Attribute orderAttribute = new in.shop2020.model.v1.order.Attribute();
290
                orderAttribute.setName("tinNumber");
291
                orderAttribute.setValue(sourceDetail.getTinNumber());
292
 
293
                if(!sourceDetail.getTinNumber().equals("") && !(sourceDetail.getTinNumber() == null)) {
294
                	transaction_client.setOrderAttributeForTransaction(Long.parseLong(transactionId), orderAttribute);
295
                }*/
296
                //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()));
297
                //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()));
298
                logger.info("Successfully created transaction: " + transactionId + " for amount: " + totalPrice);
299
 
300
                Transaction transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
301
                Order order = transaction.getOrders().get(0);
302
 
303
                inventoryClient.reserveItemInWarehouse(ebayItem.getItemId(), fulfillmentWarehouse.getId(), 1, 
304
                		order.getId(), order.getCreated_timestamp(), order.getPromised_shipping_time(), order.getLineitems().get(0).getQuantity());
305
 
306
                EbayOrder ebayOrder = new EbayOrder();
307
                ebayOrder.setEbayListingId(ebayItem.getEbayListingId());
308
                ebayOrder.setSalesRecordNumber(new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue());
309
                try {
310
                	ebayOrder.setEbayTxnDate(sdf.parse(row.getCell(TRANSACTION_DATE_INDEX).getStringCellValue()).getTime());
311
                } catch (Exception e) {
312
                	logger.error("Error in setting transaction date for Ebay Order with OrderId : " + order.getId());
313
                }
314
                ebayOrder.setOrderId(order.getId());
315
                ebayOrder.setPaisaPayId(paisaPayId);
316
                ebayOrder.setListingName(ebayItem.getListingName());
317
                ebayOrder.setSubsidyAmount(ebayItem.getSubsidy()*quantity);
318
                transaction_client.createEbayOrder(ebayOrder);
319
            } catch (Exception e) {
320
                logger.error("Unable to create order for rowId " + (rowId + 1), e);
321
                addActionError("Unable to create order for rowId " + (rowId + 1));
322
                return "authsuccess";
323
    		}
324
        }
325
 
326
        checkForErrors();
327
        return "authsuccess";
328
    }
329
 
330
    private LineItem createLineItem(long itemId, long quantity, double amount) throws CatalogServiceException, TException {
331
    	LineItem lineItem = new LineItem();
332
    	CatalogService.Client catalogClient = new CatalogClient().getClient();
333
    	Item item = catalogClient.getItem(itemId);
334
 
335
    	lineItem.setProductGroup(item.getProductGroup());
336
        lineItem.setBrand(item.getBrand());
337
        lineItem.setModel_number(item.getModelNumber());
338
        lineItem.setModel_name(item.getModelName());
339
        lineItem.setExtra_info(item.getFeatureDescription());
340
        lineItem.setQuantity(quantity);
341
        lineItem.setItem_id(item.getId());
342
        lineItem.setTotal_weight(item.getWeight());
343
        lineItem.setUnit_price(amount/quantity);
344
        lineItem.setTotal_price(amount);
345
 
346
        if (item.getColor() == null || "NA".equals(item.getColor())) {
347
            lineItem.setColor("");
348
        } else {
349
            lineItem.setColor(item.getColor());
350
        }
351
    	return lineItem;
352
	}
353
 
354
    private void createPayment(User user, String paisaPayId, double amount) throws NumberFormatException, PaymentException, TException {
355
        in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
356
        long paymentId = client.createPayment(user.getUserId(), amount, EBAY_GATEWAY_ID, Long.valueOf(transactionId), false);
357
        client.updatePaymentDetails(paymentId, null, null, null, null, null, null, paisaPayId, null, PaymentStatus.PENDING, null, null);
358
    }   
359
 
360
	public String index() {
361
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), "/ebay-dashboard"))
362
            return "authfail";
363
        checkForErrors();
364
        return "authsuccess";
365
    }
366
 
367
	private boolean checkForErrors(){
368
        Collection<String> actionErrors = getActionErrors();
369
        if(actionErrors != null && !actionErrors.isEmpty()){
370
            for (String str : actionErrors) {
371
                errorMsg += "<BR/>" + str;
372
            }
373
            if(rowId>1) {
374
            	errorMsg += "<BR/>" + "Error while processing rowNumber : " + rowId;
375
            }
376
            return true;
377
        }
378
        return false;
379
    }
380
 
381
	@Override
382
	public void setServletRequest(HttpServletRequest request) {
383
		this.request = request;
384
        this.session = request.getSession();
385
	}
386
 
387
	public String getErrorMsg() {
388
		return errorMsg;
389
	}
390
 
391
	public void setErrorMsg(String errorMsg) {
392
		this.errorMsg = errorMsg;
393
	}
394
 
395
	public Long getRowId() {
396
		return rowId;
397
	}
398
 
399
	public void setRowId(Long rowId) {
400
		this.rowId = rowId;
401
	}
402
 
403
	public File getOrderDataFile() {
404
		return orderDataFile;
405
	}
406
 
407
	public void setOrderDataFile(File orderDataFile) {
408
		this.orderDataFile = orderDataFile;
409
	}
410
 
411
 
412
}