Subversion Repositories SmartDukaan

Rev

Rev 8209 | Rev 8254 | 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 {
253
            	order.setPromised_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());
254
            	order.setExpected_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());
255
            	Calendar time = Calendar.getInstance();
256
            	time.setTimeInMillis(order.getExpected_shipping_time());
257
            	time.add(Calendar.DAY_OF_MONTH, 3);
258
            	order.setPromised_delivery_time(time.getTimeInMillis());
259
            	order.setExpected_delivery_time(time.getTimeInMillis());
260
            } catch(Exception e) {
261
            	addActionError("Error in updating Shipping Time for row number " + rowId + 1);
262
            	logger.error("Error in updating Shipping Time for row number " + (rowId + 1),e);
263
            }
264
 
265
            //TODO Delivery time
266
            InventoryService.Client inventoryClient = null;
267
            Warehouse fulfillmentWarehouse= null; 
268
            try {
269
            	inventoryClient = new InventoryClient().getClient();
270
            	Cell warehouseCell = row.getCell(WAREHOUSE_ID_INDEX);
271
            	if(warehouseCell != null && warehouseCell.getCellType() != Cell.CELL_TYPE_BLANK) { 
272
            		fulfillmentWarehouse = inventoryClient.getWarehouse(new Double(row.getCell(WAREHOUSE_ID_INDEX).getNumericCellValue()).longValue());
273
 
274
            	} else if (ebayItem.getDefaultWarehouseId()!=0 ){
275
            		fulfillmentWarehouse = inventoryClient.getWarehouse(ebayItem.getDefaultWarehouseId());
276
            	} else {
277
            		List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(ebayItem.getItemId(), 1);
278
            		fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
279
            	}
280
            	order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
281
        		order.setWarehouse_id(fulfillmentWarehouse.getBillingWarehouseId());
282
			} catch (InventoryServiceException e) {
283
				addActionError("Error in updating WarehouseId for row number " + rowId + 1);
284
            	logger.error("Error in updating WarehouseId for row number " + (rowId + 1),e);
285
            	return "authsuccess";
286
			}
287
 
288
			//TODO set Provider Id
289
            order.setTotal_amount(totalPrice);
290
            order.setSource(EBAY_SOURCE_ID);
291
            orders.add(order);
292
            orderCountForRow++;
293
 
294
            txn.setOrders(orders);
295
            Client transaction_client = new TransactionClient().getClient();
296
            try {
297
            	long salesRecNumber = new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue();
298
            	if(transaction_client.ebayOrderExists(salesRecNumber, ebayItem.getEbayListingId())) {
299
            		throw new Exception("Duplicate order for salesRecNumber " + salesRecNumber + " and listingId " + ebayItem.getEbayListingId());
300
            	}
301
            	LogisticsService.Client logisticsClient = new LogisticsClient().getClient();
302
            	LogisticsInfo logisticsInfo = logisticsClient.getLogisticsInfo(order.getCustomer_pincode(), 
303
            			new Double(order.getLineitems().get(0).getQuantity()).longValue(), DeliveryType.PREPAID, PickUpType.COURIER);
304
            	order.setLogistics_provider_id(logisticsInfo.getProviderId());
305
            	transactionId =  String.valueOf(transaction_client.createTransaction(txn));
306
            	row.getCell(PAISAPAY_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
307
            	String paisaPayId = row.getCell(PAISAPAY_ID_INDEX).getStringCellValue();
308
            	createPayment(user, paisaPayId, totalPrice);
309
 
310
            	//TODO
311
            	/*in.shop2020.model.v1.order.Attribute orderAttribute = new in.shop2020.model.v1.order.Attribute();
312
                orderAttribute.setName("tinNumber");
313
                orderAttribute.setValue(sourceDetail.getTinNumber());
314
 
315
                if(!sourceDetail.getTinNumber().equals("") && !(sourceDetail.getTinNumber() == null)) {
316
                	transaction_client.setOrderAttributeForTransaction(Long.parseLong(transactionId), orderAttribute);
317
                }*/
318
            	//source
319
                //transaction_client.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.AUTHORIZED, "Ebay Order", 0L, OrderType.B2C, OrderSource.EBAY);
320
                //transaction_client.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS, "Ebay Order", 0L, OrderType.B2C, OrderSource.EBAY);
321
                logger.info("Successfully created transaction: " + transactionId + " for amount: " + totalPrice);
322
 
323
                Transaction transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
8209 amar.kumar 324
                order = transaction.getOrders().get(0);
8182 amar.kumar 325
                inventoryClient.reserveItemInWarehouse(ebayItem.getItemId(), fulfillmentWarehouse.getId(), 1, 
326
                		order.getId(), order.getCreated_timestamp(), order.getPromised_shipping_time(), order.getLineitems().get(0).getQuantity());
327
                transaction_client.updateOrderForEbay(order);
328
                EbayOrder ebayOrder = new EbayOrder();
329
                ebayOrder.setEbayListingId(ebayItem.getEbayListingId());
330
                ebayOrder.setSalesRecordNumber(new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue());
331
                row.getCell(TRANSACTION_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
332
                ebayOrder.setTransactionId(row.getCell(TRANSACTION_ID_INDEX).getStringCellValue());
333
                try {
334
                	//ebayOrder.setEbayTxnDate(row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue().getTime());
335
                	//ebayOrder.setEbayTxnDate(sdf2.parse(row.getCell(TRANSACTION_DATE_INDEX).getStringCellValue()).getTime());
336
                	ebayOrder.setEbayTxnDate(sdf.parse(row.getCell(TRANSACTION_DATE_INDEX).getStringCellValue()).getTime());
337
                } catch (Exception e) {
338
                	logger.error("Error in setting transaction date for Ebay Order with OrderId : " + order.getId());
339
                }
340
                ebayOrder.setOrderId(transaction.getOrders().get(0).getId());
341
                ebayOrder.setPaisaPayId(paisaPayId);
342
                ebayOrder.setSubsidyAmount(ebayItem.getSubsidy()*quantity);
343
                ebayOrder.setListingName(ebayItem.getListingName());
8241 amar.kumar 344
                ebayOrder.setListingPrice(listingPrice);
8182 amar.kumar 345
                transaction_client.createEbayOrder(ebayOrder);
346
            } catch (Exception e) {
347
                logger.error("Unable to establish connection to the transaction service", e);
348
                addActionError("Unable to establish connection to the transaction service");
349
                return "authsuccess";
350
    		}
351
        }
352
 
353
        checkForErrors();
354
        return "authsuccess";
355
    }
356
 
357
    private LineItem createLineItem(long itemId, long quantity, double amount) throws CatalogServiceException, TException {
358
    	LineItem lineItem = new LineItem();
359
    	CatalogService.Client catalogClient = new CatalogClient().getClient();
360
    	Item item = catalogClient.getItem(itemId);
361
 
362
    	lineItem.setProductGroup(item.getProductGroup());
363
        lineItem.setBrand(item.getBrand());
364
        lineItem.setModel_number(item.getModelNumber());
365
        lineItem.setModel_name(item.getModelName());
366
        lineItem.setExtra_info(item.getFeatureDescription());
367
        lineItem.setQuantity(quantity);
368
        lineItem.setItem_id(item.getId());
369
        lineItem.setUnit_weight(item.getWeight());
8241 amar.kumar 370
        lineItem.setTotal_weight(item.getWeight()*quantity);
8182 amar.kumar 371
        lineItem.setUnit_price(amount/quantity);
372
        lineItem.setTotal_price(amount);
373
 
374
        if (item.getColor() == null || "NA".equals(item.getColor())) {
375
            lineItem.setColor("");
376
        } else {
377
            lineItem.setColor(item.getColor());
378
        }
379
    	return lineItem;
380
	}
381
 
382
    private void createPayment(User user, String paisaPayId, double amount) throws NumberFormatException, PaymentException, TException {
383
        in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
384
        long paymentId = client.createPayment(user.getUserId(), amount, EBAY_GATEWAY_ID, Long.valueOf(transactionId), false);
385
        client.updatePaymentDetails(paymentId, null, null, null, null, null, null, paisaPayId, null, PaymentStatus.AUTHORIZED, null, null);
386
    }   
387
 
388
	public String index() {
389
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), "/ebay-dashboard"))
390
            return "authfail";
391
        checkForErrors();
392
        return "authsuccess";
393
    }
394
 
395
	private boolean checkForErrors(){
396
        Collection<String> actionErrors = getActionErrors();
397
        if(actionErrors != null && !actionErrors.isEmpty()){
398
            for (String str : actionErrors) {
399
                errorMsg += "<BR/>" + str;
400
            }
401
            if(rowId>1) {
402
            	errorMsg += "<BR/>" + "Error while processing rowNumber : " + rowId;
403
            }
404
            return true;
405
        }
406
        return false;
407
    }
408
 
409
	@Override
410
	public void setServletRequest(HttpServletRequest request) {
411
		this.request = request;
412
        this.session = request.getSession();
413
	}
414
 
415
	public String getErrorMsg() {
416
		return errorMsg;
417
	}
418
 
419
	public void setErrorMsg(String errorMsg) {
420
		this.errorMsg = errorMsg;
421
	}
422
 
423
	public Long getRowId() {
424
		return rowId;
425
	}
426
 
427
	public void setRowId(Long rowId) {
428
		this.rowId = rowId;
429
	}
430
 
431
	public File getOrderDataFile() {
432
		return orderDataFile;
433
	}
434
 
435
	public void setOrderDataFile(File orderDataFile) {
436
		this.orderDataFile = orderDataFile;
437
	}
438
 
439
}