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 EbayNormalOrderCreatorController extends ActionSupport implements ServletRequestAware {
76
 
77
	private static Logger logger = LoggerFactory.getLogger(EbayNormalOrderCreatorController.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 BUYER_NAME_INDEX = 2;
86
    private static final int CUST_MOBILE_INDEX = 3;
87
    private static final int EMAIL_INDEX = 4;
88
    private static final int ADDR1_INDEX = 5;
89
    private static final int ADDR2_INDEX = 6;
90
    private static final int CITY_INDEX = 7;
91
    private static final int STATE_INDEX = 8;
92
    private static final int PINCODE_INDEX = 9;
93
    private static final int EBAY_LISTINGID_INDEX = 11;
94
    private static final int QUANTITY_INDEX = 14;
95
    private static final int AMOUNT_INDEX = 15;
96
    private static final int TRANSACTION_DATE_INDEX = 21;
97
    private static final int PAISAPAY_ID_INDEX = 28;
98
    private static final int TRANSACTION_ID_INDEX = 31;
99
 
100
    private static final int SHIP_DATE_INDEX = 24;
101
    private static final int WAREHOUSE_ID_INDEX = 34;
102
    private static final int LISTING_PRICE_INDEX = 35;
103
 
8196 amar.kumar 104
    private static final int EBAY_GATEWAY_ID = 16;
8182 amar.kumar 105
 
106
    private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
107
    private SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
108
 
109
    private File orderDataFile;
110
    private String orderDataFileName;
111
    private String transactionId;
112
    private String errorMsg = "";
113
    private Long rowId = 0L;
114
 
115
    public String create() throws TException {
116
        File fileToCreate = null;
117
        orderDataFileName = "OrderSheet_"+EBAY_SOURCE_ID+"_"+(new Date().toString());
118
        try {
119
            fileToCreate = new File("/tmp/", this.orderDataFileName);
120
            FileUtils.copyFile(this.orderDataFile, fileToCreate);
121
        } catch (Exception e) {
122
           logger.error("Error while writing order data file to the local file system for Ebay", e);
123
           addActionError("Error while writing order data file to the local file system");
124
        }
125
 
126
 
127
        if(checkForErrors())
128
            return "authsuccess";
129
 
130
        //Parse the file and submit the data for update to the transaction service
131
        Workbook wb = null;
132
        try {
133
            wb = new HSSFWorkbook(new FileInputStream(fileToCreate));
134
        } catch (Exception e) {
135
            logger.error("Unable to open the File for Order Creation for Ebay ", e);
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);
149
            addActionError("Unable to establish connection to the transaction service");
150
		}
151
 
152
        if(checkForErrors())
153
            return "authsuccess";
154
 
155
        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
156
	    try {   
157
	        userClient = new UserClient().getClient();
158
	    } catch (Exception e) {
159
	        logger.error("Unable to establish connection to the User service", e);
160
	        addActionError("Unable to establish connection to the User service");
161
		}
162
 
163
        if(checkForErrors())
164
            return "authsuccess";
165
 
166
        Sheet sheet = wb.getSheetAt(0);
167
        Row firstRow = sheet.getRow(0);
168
        logger.info("Last row number is:" + sheet.getLastRowNum());
169
        for (Row row : sheet) {
170
        	long orderCountForRow = 0;
171
            if(row.equals(firstRow))
172
                continue;
173
            rowId++;
174
            try {
175
	            //TODO Get this user from a different method
176
	            if (userClient.userExists(row.getCell(EMAIL_INDEX).getStringCellValue())) {
177
		        	user = userClient.getUserByEmail(row.getCell(EMAIL_INDEX).getStringCellValue());
178
		        } else {
179
		        	user = new User();
180
		        	user.setName(row.getCell(BUYER_NAME_INDEX).getStringCellValue());
181
		        	user.setEmail(row.getCell(EMAIL_INDEX).getStringCellValue());
182
		        	//TODO set mobileNumber for customer
183
		        	//TODO set password for user;
184
		        	user.setIsAnonymous(false);
185
		        	user = userClient.createUser(user);
186
		        }
187
            } catch(Exception e) {
188
	        	logger.error("Unable to establish connection to the User service for row number " + (rowId + 1), e);
189
    	        addActionError("Unable to establish connection to the User servicefor row number " + (rowId + 1));
190
    	        return "authsuccess";
191
	        }
192
            Transaction txn = new Transaction();
193
            txn.setShoppingCartid(user.getActiveCartId());
194
            txn.setCustomer_id(user.getUserId());
195
            txn.setCreatedOn(new Date().getTime());
196
            txn.setTransactionStatus(TransactionStatus.INIT);
197
            txn.setStatusDescription("Order for Ebay ");
198
 
199
            List<Order> orders = new ArrayList<Order>();
200
 
8241 amar.kumar 201
            double listingPrice = 0;
202
    		double overriddenPrice = 0;
203
    		double totalPrice = 0;
204
 
8182 amar.kumar 205
            row.getCell(EBAY_LISTINGID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
206
            String ebayListingId = row.getCell(EBAY_LISTINGID_INDEX).getStringCellValue();
207
    		CatalogService.Client catalogClient = new CatalogClient().getClient();
208
    		EbayItem ebayItem = catalogClient.getEbayItem(ebayListingId);
209
    		long quantity = new Double(row.getCell(QUANTITY_INDEX).getNumericCellValue()).longValue();
8241 amar.kumar 210
    		Cell overriddenPriceCell = row.getCell(LISTING_PRICE_INDEX);
211
        	if(overriddenPriceCell  != null && overriddenPriceCell .getCellType() != Cell.CELL_TYPE_BLANK) {
212
        		overriddenPrice = row.getCell(LISTING_PRICE_INDEX).getNumericCellValue();
213
        	}
8182 amar.kumar 214
    		String totalPriceString = row.getCell(AMOUNT_INDEX).getStringCellValue();
8241 amar.kumar 215
    		if(overriddenPrice>=1) {
216
    			totalPrice = overriddenPrice*quantity;
217
    			listingPrice = (Double.parseDouble(totalPriceString.substring(3).replace(",","")))/quantity;
218
    		} else {
219
    			totalPrice = Double.parseDouble(totalPriceString.substring(3).replace(",",""));
220
    			listingPrice = totalPrice/quantity;
221
    		}
8182 amar.kumar 222
        	LineItem lineItem = null;
223
        	try {
224
        		lineItem = createLineItem(ebayItem.getItemId(), quantity, totalPrice);
225
        	} catch (Exception tex) {
226
        		logger.error("Unable to establish connection to the Catalog service", tex);
227
    	        addActionError("Unable to establish connection to the Catalog service");
228
    	        return "authsuccess";
229
        	}
230
            Order order = new Order();
231
            order.setCustomer_id(user.getUserId());
232
            order.setCustomer_email(user.getEmail());
233
        	order.setCustomer_name(user.getName());
234
            try {
235
            	order.setCustomer_mobilenumber(new Double(row.getCell(CUST_MOBILE_INDEX).getNumericCellValue()).toString());
236
            } catch (Exception e) {
237
            	addActionError("Error in reading mobile Number for rowNumber " + row.getRowNum());
238
            	logger.error("Error in reading mobile Number for rowNumber " + row.getRowNum());
239
            }
240
            order.setCustomer_address1(row.getCell(ADDR1_INDEX).getStringCellValue());
241
        	order.setCustomer_address2(row.getCell(ADDR2_INDEX).getStringCellValue());
242
        	order.setCustomer_city(row.getCell(CITY_INDEX).getStringCellValue());
243
        	order.setCustomer_state(row.getCell(STATE_INDEX).getStringCellValue());
244
        	row.getCell(PINCODE_INDEX).setCellType(Cell.CELL_TYPE_STRING);
245
        	order.setCustomer_pincode(row.getCell(PINCODE_INDEX).getStringCellValue());
246
            order.setTotal_amount(totalPrice);            
247
            order.setTotal_weight(lineItem.getTotal_weight());
248
            order.setLineitems(Collections.singletonList(lineItem));            
249
            order.setStatus(OrderStatus.SUBMITTED_FOR_PROCESSING);
250
            order.setStatusDescription("In Process");
251
            order.setCreated_timestamp(new Date().getTime());
252
            try {
8254 amar.kumar 253
            	order.setPromised_shipping_time(row.getCell(SHIP_DATE_INDEX).getDateCellValue().getTime());
254
            	order.setExpected_shipping_time(row.getCell(SHIP_DATE_INDEX).getDateCellValue().getTime());
255
            	//order.setPromised_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());
256
            	//order.setExpected_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());
8182 amar.kumar 257
            	Calendar time = Calendar.getInstance();
258
            	time.setTimeInMillis(order.getExpected_shipping_time());
259
            	time.add(Calendar.DAY_OF_MONTH, 3);
260
            	order.setPromised_delivery_time(time.getTimeInMillis());
261
            	order.setExpected_delivery_time(time.getTimeInMillis());
262
            } catch(Exception e) {
8254 amar.kumar 263
            	addActionError("Error in updating Shipping Time for row number " + (rowId + 1));
8182 amar.kumar 264
            	logger.error("Error in updating Shipping Time for row number " + (rowId + 1),e);
265
            }
266
 
267
            //TODO Delivery time
268
            InventoryService.Client inventoryClient = null;
269
            Warehouse fulfillmentWarehouse= null; 
270
            try {
271
            	inventoryClient = new InventoryClient().getClient();
272
            	Cell warehouseCell = row.getCell(WAREHOUSE_ID_INDEX);
273
            	if(warehouseCell != null && warehouseCell.getCellType() != Cell.CELL_TYPE_BLANK) { 
274
            		fulfillmentWarehouse = inventoryClient.getWarehouse(new Double(row.getCell(WAREHOUSE_ID_INDEX).getNumericCellValue()).longValue());
275
 
276
            	} else if (ebayItem.getDefaultWarehouseId()!=0 ){
277
            		fulfillmentWarehouse = inventoryClient.getWarehouse(ebayItem.getDefaultWarehouseId());
278
            	} else {
279
            		List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(ebayItem.getItemId(), 1);
280
            		fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
281
            	}
282
            	order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
283
        		order.setWarehouse_id(fulfillmentWarehouse.getBillingWarehouseId());
284
			} catch (InventoryServiceException e) {
285
				addActionError("Error in updating WarehouseId for row number " + rowId + 1);
286
            	logger.error("Error in updating WarehouseId for row number " + (rowId + 1),e);
287
            	return "authsuccess";
288
			}
289
 
290
			//TODO set Provider Id
291
            order.setTotal_amount(totalPrice);
292
            order.setSource(EBAY_SOURCE_ID);
293
            orders.add(order);
294
            orderCountForRow++;
295
 
296
            txn.setOrders(orders);
297
            Client transaction_client = new TransactionClient().getClient();
298
            try {
299
            	long salesRecNumber = new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue();
300
            	if(transaction_client.ebayOrderExists(salesRecNumber, ebayItem.getEbayListingId())) {
301
            		throw new Exception("Duplicate order for salesRecNumber " + salesRecNumber + " and listingId " + ebayItem.getEbayListingId());
302
            	}
303
            	LogisticsService.Client logisticsClient = new LogisticsClient().getClient();
304
            	LogisticsInfo logisticsInfo = logisticsClient.getLogisticsInfo(order.getCustomer_pincode(), 
305
            			new Double(order.getLineitems().get(0).getQuantity()).longValue(), DeliveryType.PREPAID, PickUpType.COURIER);
306
            	order.setLogistics_provider_id(logisticsInfo.getProviderId());
307
            	transactionId =  String.valueOf(transaction_client.createTransaction(txn));
308
            	row.getCell(PAISAPAY_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
309
            	String paisaPayId = row.getCell(PAISAPAY_ID_INDEX).getStringCellValue();
310
            	createPayment(user, paisaPayId, totalPrice);
311
 
312
            	//TODO
313
            	/*in.shop2020.model.v1.order.Attribute orderAttribute = new in.shop2020.model.v1.order.Attribute();
314
                orderAttribute.setName("tinNumber");
315
                orderAttribute.setValue(sourceDetail.getTinNumber());
316
 
317
                if(!sourceDetail.getTinNumber().equals("") && !(sourceDetail.getTinNumber() == null)) {
318
                	transaction_client.setOrderAttributeForTransaction(Long.parseLong(transactionId), orderAttribute);
319
                }*/
320
            	//source
321
                //transaction_client.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.AUTHORIZED, "Ebay Order", 0L, OrderType.B2C, OrderSource.EBAY);
322
                //transaction_client.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS, "Ebay Order", 0L, OrderType.B2C, OrderSource.EBAY);
323
                logger.info("Successfully created transaction: " + transactionId + " for amount: " + totalPrice);
324
 
325
                Transaction transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
8209 amar.kumar 326
                order = transaction.getOrders().get(0);
8182 amar.kumar 327
                inventoryClient.reserveItemInWarehouse(ebayItem.getItemId(), fulfillmentWarehouse.getId(), 1, 
328
                		order.getId(), order.getCreated_timestamp(), order.getPromised_shipping_time(), order.getLineitems().get(0).getQuantity());
329
                transaction_client.updateOrderForEbay(order);
330
                EbayOrder ebayOrder = new EbayOrder();
331
                ebayOrder.setEbayListingId(ebayItem.getEbayListingId());
332
                ebayOrder.setSalesRecordNumber(new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue());
333
                row.getCell(TRANSACTION_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
334
                ebayOrder.setTransactionId(row.getCell(TRANSACTION_ID_INDEX).getStringCellValue());
335
                try {
8254 amar.kumar 336
                	ebayOrder.setEbayTxnDate(row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue().getTime());
8182 amar.kumar 337
                	//ebayOrder.setEbayTxnDate(sdf2.parse(row.getCell(TRANSACTION_DATE_INDEX).getStringCellValue()).getTime());
8254 amar.kumar 338
                	//ebayOrder.setEbayTxnDate(sdf.parse(row.getCell(TRANSACTION_DATE_INDEX).getStringCellValue()).getTime());
8182 amar.kumar 339
                } catch (Exception e) {
340
                	logger.error("Error in setting transaction date for Ebay Order with OrderId : " + order.getId());
341
                }
342
                ebayOrder.setOrderId(transaction.getOrders().get(0).getId());
343
                ebayOrder.setPaisaPayId(paisaPayId);
344
                ebayOrder.setSubsidyAmount(ebayItem.getSubsidy()*quantity);
345
                ebayOrder.setListingName(ebayItem.getListingName());
8241 amar.kumar 346
                ebayOrder.setListingPrice(listingPrice);
8182 amar.kumar 347
                transaction_client.createEbayOrder(ebayOrder);
348
            } catch (Exception e) {
349
                logger.error("Unable to establish connection to the transaction service", e);
350
                addActionError("Unable to establish connection to the transaction service");
351
                return "authsuccess";
352
    		}
353
        }
354
 
355
        checkForErrors();
356
        return "authsuccess";
357
    }
358
 
359
    private LineItem createLineItem(long itemId, long quantity, double amount) throws CatalogServiceException, TException {
360
    	LineItem lineItem = new LineItem();
361
    	CatalogService.Client catalogClient = new CatalogClient().getClient();
362
    	Item item = catalogClient.getItem(itemId);
363
 
364
    	lineItem.setProductGroup(item.getProductGroup());
365
        lineItem.setBrand(item.getBrand());
366
        lineItem.setModel_number(item.getModelNumber());
367
        lineItem.setModel_name(item.getModelName());
368
        lineItem.setExtra_info(item.getFeatureDescription());
369
        lineItem.setQuantity(quantity);
370
        lineItem.setItem_id(item.getId());
371
        lineItem.setUnit_weight(item.getWeight());
8241 amar.kumar 372
        lineItem.setTotal_weight(item.getWeight()*quantity);
8182 amar.kumar 373
        lineItem.setUnit_price(amount/quantity);
374
        lineItem.setTotal_price(amount);
375
 
376
        if (item.getColor() == null || "NA".equals(item.getColor())) {
377
            lineItem.setColor("");
378
        } else {
379
            lineItem.setColor(item.getColor());
380
        }
381
    	return lineItem;
382
	}
383
 
384
    private void createPayment(User user, String paisaPayId, double amount) throws NumberFormatException, PaymentException, TException {
385
        in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
386
        long paymentId = client.createPayment(user.getUserId(), amount, EBAY_GATEWAY_ID, Long.valueOf(transactionId), false);
387
        client.updatePaymentDetails(paymentId, null, null, null, null, null, null, paisaPayId, null, PaymentStatus.AUTHORIZED, null, null);
388
    }   
389
 
390
	public String index() {
391
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), "/ebay-dashboard"))
392
            return "authfail";
393
        checkForErrors();
394
        return "authsuccess";
395
    }
396
 
397
	private boolean checkForErrors(){
398
        Collection<String> actionErrors = getActionErrors();
399
        if(actionErrors != null && !actionErrors.isEmpty()){
400
            for (String str : actionErrors) {
401
                errorMsg += "<BR/>" + str;
402
            }
403
            if(rowId>1) {
404
            	errorMsg += "<BR/>" + "Error while processing rowNumber : " + rowId;
405
            }
406
            return true;
407
        }
408
        return false;
409
    }
410
 
411
	@Override
412
	public void setServletRequest(HttpServletRequest request) {
413
		this.request = request;
414
        this.session = request.getSession();
415
	}
416
 
417
	public String getErrorMsg() {
418
		return errorMsg;
419
	}
420
 
421
	public void setErrorMsg(String errorMsg) {
422
		this.errorMsg = errorMsg;
423
	}
424
 
425
	public Long getRowId() {
426
		return rowId;
427
	}
428
 
429
	public void setRowId(Long rowId) {
430
		this.rowId = rowId;
431
	}
432
 
433
	public File getOrderDataFile() {
434
		return orderDataFile;
435
	}
436
 
437
	public void setOrderDataFile(File orderDataFile) {
438
		this.orderDataFile = orderDataFile;
439
	}
440
 
441
}