Subversion Repositories SmartDukaan

Rev

Rev 8283 | Rev 8291 | 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 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
 
8196 amar.kumar 98
    private static final int EBAY_GATEWAY_ID = 16;
8182 amar.kumar 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);
8241 amar.kumar 189
    		double listingPrice = 0;
190
    		double overriddenPrice = 0;
191
    		double totalPrice = 0;
192
    		Cell overriddenPriceCell = row.getCell(LISTING_PRICE_INDEX);
193
        	if(overriddenPriceCell  != null && overriddenPriceCell .getCellType() != Cell.CELL_TYPE_BLANK) {
194
        		overriddenPrice = row.getCell(LISTING_PRICE_INDEX).getNumericCellValue();
195
        	}
196
 
8182 amar.kumar 197
    		long quantity = new Double(row.getCell(QUANTITY_INDEX).getNumericCellValue()).longValue();
198
    		String totalPriceString = row.getCell(AMOUNT_INDEX).getStringCellValue();
8241 amar.kumar 199
    		if(overriddenPrice>=1) {
200
    			totalPrice = overriddenPrice*quantity;
201
    			listingPrice = (Double.parseDouble(totalPriceString.substring(3).replace(",","")))/quantity;
202
    		} else {
203
    			totalPrice = Double.parseDouble(totalPriceString.substring(3).replace(",",""));
204
    			listingPrice = totalPrice/quantity;
205
    		}
8182 amar.kumar 206
 
207
        	LineItem lineItem = null;
208
        	try {
209
        		lineItem = createLineItem(ebayItem.getItemId(), quantity, totalPrice);
210
        	} catch (Exception tex) {
211
        		logger.error("Unable to create order for sales Rec Number " + row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue(), tex);
212
    	        addActionError("Unable to create order for sales Rec Number " + row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue());
213
    	        return "authsuccess";
214
        	}
215
            Order t_order = new Order();
216
            t_order.setCustomer_id(user.getUserId());
217
            t_order.setCustomer_email(sourceDetail.getEmail());
218
        	t_order.setCustomer_name("Ebay");
219
            try {
220
            	row.getCell(CUST_MOBILE_INDEX).setCellType(Cell.CELL_TYPE_STRING);
221
            	t_order.setCustomer_mobilenumber(row.getCell(CUST_MOBILE_INDEX).getStringCellValue());
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
            //t_order.setTotal_amount(lineItem.getTotal_price());            
227
            t_order.setTotal_weight(lineItem.getTotal_weight());
228
            t_order.setLineitems(Collections.singletonList(lineItem));            
229
            t_order.setStatus(OrderStatus.PAYMENT_PENDING);
230
            t_order.setStatusDescription("Payment Pending");
231
            t_order.setCreated_timestamp(new Date().getTime());
232
            try {
8281 amar.kumar 233
            	Date shippingDate = interchangeDateAndMonth(row.getCell(SHIP_DATE_INDEX).getDateCellValue());
234
            	t_order.setPromised_shipping_time(shippingDate.getTime());
235
            	t_order.setExpected_shipping_time(shippingDate.getTime());
8252 amar.kumar 236
            	/*t_order.setPromised_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());
237
            	t_order.setExpected_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());*/
8182 amar.kumar 238
            	Calendar time = Calendar.getInstance();
239
            	time.setTimeInMillis(t_order.getExpected_shipping_time());
240
            	time.add(Calendar.DAY_OF_MONTH, 3);
241
            	t_order.setPromised_delivery_time(time.getTimeInMillis());
242
            	t_order.setExpected_delivery_time(time.getTimeInMillis());
243
            } catch(Exception e) {
244
            	addActionError("Error in updating Shipping Time for row number " + (rowId + 1));
245
            	logger.error("Error in updating Shipping Time for row number " + (rowId + 1),e);
246
            }
247
 
248
            //TODO Delivery time
249
            InventoryService.Client inventoryClient = null;
250
            Warehouse fulfillmentWarehouse= null; 
251
            try {
252
            	inventoryClient = new InventoryClient().getClient();
253
            	Cell warehouseCell = row.getCell(WAREHOUSE_ID_INDEX);
254
            	if(warehouseCell != null && warehouseCell.getCellType() != Cell.CELL_TYPE_BLANK) { 
255
            		fulfillmentWarehouse = inventoryClient.getWarehouse(new Double(row.getCell(WAREHOUSE_ID_INDEX).getNumericCellValue()).longValue());
256
 
257
            	} else if (ebayItem.getDefaultWarehouseId()!=0 ){
258
            		fulfillmentWarehouse = inventoryClient.getWarehouse(ebayItem.getDefaultWarehouseId());
259
            	} else {
260
            		List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(ebayItem.getItemId(), 1);
261
            		fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
262
            	}
263
            	t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
264
        		t_order.setWarehouse_id(fulfillmentWarehouse.getBillingWarehouseId());
265
			} catch (InventoryServiceException e) {
266
				addActionError("Error in updating WarehouseId for row number " + (rowId + 1));
267
            	logger.error("Error in updating WarehouseId for row number " + (rowId + 1),e);
268
            	return "authsuccess";
269
			}
270
 
271
			String provider = row.getCell(COURIER_INDEX).getStringCellValue();
272
			if(provider.equals(bluedart)) {
273
				t_order.setLogistics_provider_id(8);
274
			} else if(provider.equals(aramex)) {
275
				t_order.setLogistics_provider_id(9);
276
			} else if(provider.equals(dtdc)) {
277
				t_order.setLogistics_provider_id(10);
278
			} else if(provider.equals(fedex)) {
279
				t_order.setLogistics_provider_id(11);
280
			} else {
281
				//TODO Continue and proceed with next row
282
			}
283
 
284
			row.getCell(AWB_INDEX).setCellType(Cell.CELL_TYPE_STRING);
285
			t_order.setAirwaybill_no(row.getCell(AWB_INDEX).getStringCellValue());
286
			t_order.setTracking_id(row.getCell(AWB_INDEX).getStringCellValue());
287
            t_order.setTotal_amount(totalPrice);
288
            t_order.setOrderType(OrderType.B2C);
289
            t_order.setSource(EBAY_SOURCE_ID);
290
            orders.add(t_order);
291
            orderCountForRow++;
292
 
293
            txn.setOrders(orders);
294
            Client transaction_client = new TransactionClient().getClient();
295
            try {
296
            	long salesRecNumber = new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue();
297
            	if(transaction_client.ebayOrderExists(salesRecNumber, ebayItem.getEbayListingId())) {
298
            		throw new Exception("Duplicate order for salesRecNumber " + salesRecNumber + " and listingId " + ebayItem.getEbayListingId());
299
            	}
300
 
301
            	transactionId =  String.valueOf(transaction_client.createTransaction(txn));
302
            	row.getCell(PAISAPAY_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
303
            	String paisaPayId = row.getCell(PAISAPAY_ID_INDEX).getStringCellValue();
304
            	createPayment(user, paisaPayId, totalPrice);
305
 
306
            	/*in.shop2020.model.v1.order.Attribute orderAttribute = new in.shop2020.model.v1.order.Attribute();
307
                orderAttribute.setName("tinNumber");
308
                orderAttribute.setValue(sourceDetail.getTinNumber());
309
 
310
                if(!sourceDetail.getTinNumber().equals("") && !(sourceDetail.getTinNumber() == null)) {
311
                	transaction_client.setOrderAttributeForTransaction(Long.parseLong(transactionId), orderAttribute);
312
                }*/
313
                //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()));
314
                //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()));
315
                logger.info("Successfully created transaction: " + transactionId + " for amount: " + totalPrice);
316
 
317
                Transaction transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
318
                Order order = transaction.getOrders().get(0);
319
 
320
                inventoryClient.reserveItemInWarehouse(ebayItem.getItemId(), fulfillmentWarehouse.getId(), 1, 
321
                		order.getId(), order.getCreated_timestamp(), order.getPromised_shipping_time(), order.getLineitems().get(0).getQuantity());
322
 
323
                EbayOrder ebayOrder = new EbayOrder();
324
                ebayOrder.setEbayListingId(ebayItem.getEbayListingId());
325
                ebayOrder.setSalesRecordNumber(new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue());
326
                try {
8252 amar.kumar 327
//                	ebayOrder.setEbayTxnDate(sdf.parse(row.getCell(TRANSACTION_DATE_INDEX).getStringCellValue()).getTime());
8281 amar.kumar 328
                	Date ebayTransactionDate = interchangeDateAndMonth(row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue());
329
                	ebayOrder.setEbayTxnDate(ebayTransactionDate.getTime());
8182 amar.kumar 330
                } catch (Exception e) {
331
                	logger.error("Error in setting transaction date for Ebay Order with OrderId : " + order.getId());
332
                }
333
                ebayOrder.setOrderId(order.getId());
334
                ebayOrder.setPaisaPayId(paisaPayId);
335
                ebayOrder.setListingName(ebayItem.getListingName());
336
                ebayOrder.setSubsidyAmount(ebayItem.getSubsidy()*quantity);
8241 amar.kumar 337
                ebayOrder.setListingPrice(listingPrice);
8182 amar.kumar 338
                transaction_client.createEbayOrder(ebayOrder);
339
            } catch (Exception e) {
340
                logger.error("Unable to create order for rowId " + (rowId + 1), e);
341
                addActionError("Unable to create order for rowId " + (rowId + 1));
342
                return "authsuccess";
343
    		}
344
        }
345
 
346
        checkForErrors();
347
        return "authsuccess";
348
    }
349
 
8281 amar.kumar 350
    private Date interchangeDateAndMonth(Date date) {
351
		Date updatedDate = new Date(date.getTime());
8286 amar.kumar 352
		updatedDate.setDate(date.getMonth() + 1);
353
		updatedDate.setMonth(date.getDate() - 1);
8281 amar.kumar 354
		return updatedDate;
355
	}
356
 
357
	private LineItem createLineItem(long itemId, long quantity, double amount) throws CatalogServiceException, TException {
8182 amar.kumar 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());
8241 amar.kumar 369
        lineItem.setUnit_weight(item.getWeight());
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.PENDING, 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
 
440
}