Subversion Repositories SmartDukaan

Rev

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