Subversion Repositories SmartDukaan

Rev

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