Subversion Repositories SmartDukaan

Rev

Rev 8286 | Rev 8303 | 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;
8291 amar.kumar 23
import in.shop2020.model.v1.inventory.VendorItemPricing;
8182 amar.kumar 24
import in.shop2020.model.v1.inventory.Warehouse;
25
import in.shop2020.model.v1.order.EbayOrder;
26
import in.shop2020.model.v1.order.LineItem;
27
import in.shop2020.model.v1.order.Order;
28
import in.shop2020.model.v1.order.OrderSource;
29
import in.shop2020.model.v1.order.OrderStatus;
30
import in.shop2020.model.v1.order.OrderType;
31
import in.shop2020.model.v1.order.SourceDetail;
32
import in.shop2020.model.v1.order.Transaction;
33
import in.shop2020.model.v1.order.TransactionStatus;
34
import in.shop2020.model.v1.order.TransactionService.Client;
35
import in.shop2020.model.v1.user.Address;
36
import in.shop2020.model.v1.user.User;
37
import in.shop2020.payments.Attribute;
38
import in.shop2020.payments.PaymentException;
39
import in.shop2020.payments.PaymentStatus;
40
import in.shop2020.thrift.clients.CatalogClient;
41
import in.shop2020.thrift.clients.InventoryClient;
42
import in.shop2020.thrift.clients.LogisticsClient;
43
import in.shop2020.thrift.clients.PaymentClient;
44
import in.shop2020.thrift.clients.TransactionClient;
45
import in.shop2020.thrift.clients.UserClient;
46
import in.shop2020.support.utils.ReportsUtils;
47
 
48
import javax.servlet.http.HttpServletRequest;
49
import javax.servlet.http.HttpSession;
50
 
51
import org.apache.commons.io.FileUtils;
52
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
53
import org.apache.poi.ss.usermodel.Cell;
54
import org.apache.poi.ss.usermodel.Row;
55
import org.apache.poi.ss.usermodel.Sheet;
56
import org.apache.poi.ss.usermodel.Workbook;
57
import org.apache.struts2.convention.annotation.InterceptorRef;
58
import org.apache.struts2.convention.annotation.InterceptorRefs;
59
import org.apache.struts2.convention.annotation.Result;
60
import org.apache.struts2.convention.annotation.Results;
61
import org.apache.struts2.interceptor.ServletRequestAware;
62
import org.apache.thrift.TException;
63
import org.slf4j.Logger;
64
import org.slf4j.LoggerFactory;
65
 
66
import com.opensymphony.xwork2.ActionSupport;
67
 
68
@SuppressWarnings("serial")
69
@InterceptorRefs({
70
    @InterceptorRef("defaultStack"),
71
    @InterceptorRef("login")
72
})
73
@Results({
74
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
75
})
76
public class EbayPsOrderCreatorController extends ActionSupport implements ServletRequestAware {
77
 
78
	private static Logger logger = LoggerFactory.getLogger(EbayPsOrderCreatorController.class);
79
 
80
	private HttpServletRequest request;
81
    private HttpSession session;
82
 
83
    private static final int EBAY_SOURCE_ID = 6;
84
 
85
    private static final int SALES_RECORD_NUM_INDEX = 0;
86
    private static final int QUANTITY_INDEX = 2;
87
    private static final int AMOUNT_INDEX = 3;
88
    private static final int TRANSACTION_DATE_INDEX = 4;
89
    private static final int SHIP_DATE_INDEX = 5;
90
    private static final int PAISAPAY_ID_INDEX = 7;
91
    private static final int COURIER_INDEX = 8;
92
    private static final int CUST_MOBILE_INDEX = 13;
93
    private static final int EBAY_LISTINGID_INDEX = 14;
94
    private static final int AWB_INDEX = 15;
95
    private static final int WAREHOUSE_ID_INDEX = 17;
96
    private static final int LISTING_PRICE_INDEX = 18;
97
 
98
 
8196 amar.kumar 99
    private static final int EBAY_GATEWAY_ID = 16;
8182 amar.kumar 100
 
101
    private static final String bluedart = "BLUE DART";
102
    private static final String aramex = "ARAMEX";
103
    private static final String dtdc = "DTDC";
104
    private static final String fedex = "FEDEX";
105
 
106
    private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
107
 
108
    private File orderDataFile;
109
    private String orderDataFileName;
110
    private String transactionId;
111
    private String errorMsg = "";
112
    private Long rowId = 0L;
113
 
114
    public String create() throws TException {
115
        File fileToCreate = null;
116
        orderDataFileName = "OrderSheet_"+EBAY_SOURCE_ID+"_"+(new Date().toString());
117
        try {
118
            fileToCreate = new File("/tmp/", this.orderDataFileName);
119
            FileUtils.copyFile(this.orderDataFile, fileToCreate);
120
        } catch (Exception e) {
121
           logger.error("Error while writing order data file to the local file system for Ebay", e);
122
           addActionError("Error while writing order data file to the local file system");
123
        }
124
 
125
 
126
        if(checkForErrors())
127
            return "authsuccess";
128
 
129
        //Parse the file and submit the data for update to the transaction service
130
        Workbook wb = null;
131
        try {
132
            wb = new HSSFWorkbook(new FileInputStream(fileToCreate));
133
        } catch (Exception e) {
134
            logger.error("Unable to open the File for Order Creation for Ebay ", e);
135
            addActionError("Unable to open the File for Order creation");
136
        }
137
        if(checkForErrors())
138
            return "authsuccess";
139
 
140
        SourceDetail sourceDetail = null;
141
        User user = null;
142
        TransactionClient tsc = null;
143
        try {
144
            tsc = new TransactionClient();
145
			sourceDetail = tsc.getClient().getSourceDetail(EBAY_SOURCE_ID);
146
        } catch (Exception e) {
147
            logger.error("Unable to establish connection to the transaction service", e);
148
            addActionError("Unable to establish connection to the transaction service");
149
		}
150
 
151
        if(checkForErrors())
152
            return "authsuccess";
153
 
154
	    try {   
155
	        in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
156
	        user = userClient.getUserByEmail(sourceDetail.getEmail());
157
	    } catch (Exception e) {
158
	        logger.error("Unable to establish connection to the User service", e);
159
	        addActionError("Unable to establish connection to the User service");
160
		}
161
 
162
        if (user == null) {
163
            addActionError("Could not find default user for Ebay: ");
164
        }
165
 
166
        if(checkForErrors())
167
            return "authsuccess";
168
 
169
        Sheet sheet = wb.getSheetAt(0);
170
        Row firstRow = sheet.getRow(0);
171
        logger.info("Last row number is:" + sheet.getLastRowNum());
172
        for (Row row : sheet) {
173
        	long orderCountForRow = 0;
174
            if(row.equals(firstRow))
175
                continue;
176
            rowId++;
177
            Transaction txn = new Transaction();
178
            txn.setShoppingCartid(user.getActiveCartId());
179
            txn.setCustomer_id(user.getUserId());
180
            txn.setCreatedOn(new Date().getTime());
181
            txn.setTransactionStatus(TransactionStatus.INIT);
182
            txn.setStatusDescription("Order for Ebay ");
183
 
184
            List<Order> orders = new ArrayList<Order>();
185
 
186
            row.getCell(EBAY_LISTINGID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
187
            String ebayListingId = row.getCell(EBAY_LISTINGID_INDEX).getStringCellValue();
188
    		CatalogService.Client catalogClient = new CatalogClient().getClient();
189
    		EbayItem ebayItem = catalogClient.getEbayItem(ebayListingId);
8241 amar.kumar 190
    		double listingPrice = 0;
191
    		double overriddenPrice = 0;
192
    		double totalPrice = 0;
193
    		Cell overriddenPriceCell = row.getCell(LISTING_PRICE_INDEX);
194
        	if(overriddenPriceCell  != null && overriddenPriceCell .getCellType() != Cell.CELL_TYPE_BLANK) {
195
        		overriddenPrice = row.getCell(LISTING_PRICE_INDEX).getNumericCellValue();
196
        	}
197
 
8182 amar.kumar 198
    		long quantity = new Double(row.getCell(QUANTITY_INDEX).getNumericCellValue()).longValue();
199
    		String totalPriceString = row.getCell(AMOUNT_INDEX).getStringCellValue();
8241 amar.kumar 200
    		if(overriddenPrice>=1) {
201
    			totalPrice = overriddenPrice*quantity;
202
    			listingPrice = (Double.parseDouble(totalPriceString.substring(3).replace(",","")))/quantity;
203
    		} else {
204
    			totalPrice = Double.parseDouble(totalPriceString.substring(3).replace(",",""));
205
    			listingPrice = totalPrice/quantity;
206
    		}
8182 amar.kumar 207
 
208
        	LineItem lineItem = null;
209
        	try {
210
        		lineItem = createLineItem(ebayItem.getItemId(), quantity, totalPrice);
211
        	} catch (Exception tex) {
212
        		logger.error("Unable to create order for sales Rec Number " + row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue(), tex);
213
    	        addActionError("Unable to create order for sales Rec Number " + row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue());
214
    	        return "authsuccess";
215
        	}
216
            Order t_order = new Order();
217
            t_order.setCustomer_id(user.getUserId());
218
            t_order.setCustomer_email(sourceDetail.getEmail());
219
        	t_order.setCustomer_name("Ebay");
220
            try {
221
            	row.getCell(CUST_MOBILE_INDEX).setCellType(Cell.CELL_TYPE_STRING);
222
            	t_order.setCustomer_mobilenumber(row.getCell(CUST_MOBILE_INDEX).getStringCellValue());
223
            } catch (Exception e) {
224
            	addActionError("Error in reading mobile Number for rowNumber " + row.getRowNum());
225
            	logger.error("Error in reading mobile Number for rowNumber " + row.getRowNum());
226
            }	
227
            //t_order.setTotal_amount(lineItem.getTotal_price());            
228
            t_order.setTotal_weight(lineItem.getTotal_weight());
229
            t_order.setLineitems(Collections.singletonList(lineItem));            
230
            t_order.setStatus(OrderStatus.PAYMENT_PENDING);
231
            t_order.setStatusDescription("Payment Pending");
232
            t_order.setCreated_timestamp(new Date().getTime());
233
            try {
8281 amar.kumar 234
            	Date shippingDate = interchangeDateAndMonth(row.getCell(SHIP_DATE_INDEX).getDateCellValue());
235
            	t_order.setPromised_shipping_time(shippingDate.getTime());
236
            	t_order.setExpected_shipping_time(shippingDate.getTime());
8252 amar.kumar 237
            	/*t_order.setPromised_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());
238
            	t_order.setExpected_shipping_time(sdf.parse(row.getCell(SHIP_DATE_INDEX).getStringCellValue()).getTime());*/
8182 amar.kumar 239
            	Calendar time = Calendar.getInstance();
240
            	time.setTimeInMillis(t_order.getExpected_shipping_time());
241
            	time.add(Calendar.DAY_OF_MONTH, 3);
242
            	t_order.setPromised_delivery_time(time.getTimeInMillis());
243
            	t_order.setExpected_delivery_time(time.getTimeInMillis());
244
            } catch(Exception e) {
245
            	addActionError("Error in updating Shipping Time for row number " + (rowId + 1));
246
            	logger.error("Error in updating Shipping Time for row number " + (rowId + 1),e);
247
            }
248
 
249
            //TODO Delivery time
250
            InventoryService.Client inventoryClient = null;
251
            Warehouse fulfillmentWarehouse= null; 
252
            try {
253
            	inventoryClient = new InventoryClient().getClient();
254
            	Cell warehouseCell = row.getCell(WAREHOUSE_ID_INDEX);
255
            	if(warehouseCell != null && warehouseCell.getCellType() != Cell.CELL_TYPE_BLANK) { 
256
            		fulfillmentWarehouse = inventoryClient.getWarehouse(new Double(row.getCell(WAREHOUSE_ID_INDEX).getNumericCellValue()).longValue());
257
 
258
            	} else if (ebayItem.getDefaultWarehouseId()!=0 ){
259
            		fulfillmentWarehouse = inventoryClient.getWarehouse(ebayItem.getDefaultWarehouseId());
260
            	} else {
261
            		List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(ebayItem.getItemId(), 1);
262
            		fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
263
            	}
264
            	t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
265
        		t_order.setWarehouse_id(fulfillmentWarehouse.getBillingWarehouseId());
8291 amar.kumar 266
 
267
        		VendorItemPricing vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), fulfillmentWarehouse.getVendor().getId());
268
        		t_order.getLineitems().get(0).setTransfer_price(vendorItemPricing.getTransferPrice());
269
        		t_order.getLineitems().get(0).setNlc(vendorItemPricing.getNlc());
8182 amar.kumar 270
			} catch (InventoryServiceException e) {
271
				addActionError("Error in updating WarehouseId for row number " + (rowId + 1));
272
            	logger.error("Error in updating WarehouseId for row number " + (rowId + 1),e);
273
            	return "authsuccess";
274
			}
275
 
276
			String provider = row.getCell(COURIER_INDEX).getStringCellValue();
277
			if(provider.equals(bluedart)) {
278
				t_order.setLogistics_provider_id(8);
279
			} else if(provider.equals(aramex)) {
280
				t_order.setLogistics_provider_id(9);
281
			} else if(provider.equals(dtdc)) {
282
				t_order.setLogistics_provider_id(10);
283
			} else if(provider.equals(fedex)) {
284
				t_order.setLogistics_provider_id(11);
285
			} else {
286
				//TODO Continue and proceed with next row
287
			}
288
 
289
			row.getCell(AWB_INDEX).setCellType(Cell.CELL_TYPE_STRING);
290
			t_order.setAirwaybill_no(row.getCell(AWB_INDEX).getStringCellValue());
291
			t_order.setTracking_id(row.getCell(AWB_INDEX).getStringCellValue());
292
            t_order.setTotal_amount(totalPrice);
293
            t_order.setOrderType(OrderType.B2C);
294
            t_order.setSource(EBAY_SOURCE_ID);
295
            orders.add(t_order);
296
            orderCountForRow++;
297
 
298
            txn.setOrders(orders);
299
            Client transaction_client = new TransactionClient().getClient();
300
            try {
301
            	long salesRecNumber = new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue();
302
            	if(transaction_client.ebayOrderExists(salesRecNumber, ebayItem.getEbayListingId())) {
303
            		throw new Exception("Duplicate order for salesRecNumber " + salesRecNumber + " and listingId " + ebayItem.getEbayListingId());
304
            	}
305
 
306
            	transactionId =  String.valueOf(transaction_client.createTransaction(txn));
307
            	row.getCell(PAISAPAY_ID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
308
            	String paisaPayId = row.getCell(PAISAPAY_ID_INDEX).getStringCellValue();
309
            	createPayment(user, paisaPayId, totalPrice);
310
 
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
                //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()));
319
                //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()));
320
                logger.info("Successfully created transaction: " + transactionId + " for amount: " + totalPrice);
321
 
322
                Transaction transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
323
                Order order = transaction.getOrders().get(0);
324
 
325
                inventoryClient.reserveItemInWarehouse(ebayItem.getItemId(), fulfillmentWarehouse.getId(), 1, 
326
                		order.getId(), order.getCreated_timestamp(), order.getPromised_shipping_time(), order.getLineitems().get(0).getQuantity());
327
 
328
                EbayOrder ebayOrder = new EbayOrder();
329
                ebayOrder.setEbayListingId(ebayItem.getEbayListingId());
330
                ebayOrder.setSalesRecordNumber(new Double(row.getCell(SALES_RECORD_NUM_INDEX).getNumericCellValue()).longValue());
331
                try {
8252 amar.kumar 332
//                	ebayOrder.setEbayTxnDate(sdf.parse(row.getCell(TRANSACTION_DATE_INDEX).getStringCellValue()).getTime());
8281 amar.kumar 333
                	Date ebayTransactionDate = interchangeDateAndMonth(row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue());
334
                	ebayOrder.setEbayTxnDate(ebayTransactionDate.getTime());
8182 amar.kumar 335
                } catch (Exception e) {
336
                	logger.error("Error in setting transaction date for Ebay Order with OrderId : " + order.getId());
337
                }
338
                ebayOrder.setOrderId(order.getId());
339
                ebayOrder.setPaisaPayId(paisaPayId);
340
                ebayOrder.setListingName(ebayItem.getListingName());
341
                ebayOrder.setSubsidyAmount(ebayItem.getSubsidy()*quantity);
8241 amar.kumar 342
                ebayOrder.setListingPrice(listingPrice);
8182 amar.kumar 343
                transaction_client.createEbayOrder(ebayOrder);
344
            } catch (Exception e) {
345
                logger.error("Unable to create order for rowId " + (rowId + 1), e);
346
                addActionError("Unable to create order for rowId " + (rowId + 1));
347
                return "authsuccess";
348
    		}
349
        }
350
 
351
        checkForErrors();
352
        return "authsuccess";
353
    }
354
 
8281 amar.kumar 355
    private Date interchangeDateAndMonth(Date date) {
356
		Date updatedDate = new Date(date.getTime());
8286 amar.kumar 357
		updatedDate.setDate(date.getMonth() + 1);
358
		updatedDate.setMonth(date.getDate() - 1);
8281 amar.kumar 359
		return updatedDate;
360
	}
361
 
362
	private LineItem createLineItem(long itemId, long quantity, double amount) throws CatalogServiceException, TException {
8182 amar.kumar 363
    	LineItem lineItem = new LineItem();
364
    	CatalogService.Client catalogClient = new CatalogClient().getClient();
365
    	Item item = catalogClient.getItem(itemId);
366
 
367
    	lineItem.setProductGroup(item.getProductGroup());
368
        lineItem.setBrand(item.getBrand());
369
        lineItem.setModel_number(item.getModelNumber());
370
        lineItem.setModel_name(item.getModelName());
371
        lineItem.setExtra_info(item.getFeatureDescription());
372
        lineItem.setQuantity(quantity);
373
        lineItem.setItem_id(item.getId());
8241 amar.kumar 374
        lineItem.setUnit_weight(item.getWeight());
375
        lineItem.setTotal_weight(item.getWeight()*quantity);
8182 amar.kumar 376
        lineItem.setUnit_price(amount/quantity);
377
        lineItem.setTotal_price(amount);
378
 
379
        if (item.getColor() == null || "NA".equals(item.getColor())) {
380
            lineItem.setColor("");
381
        } else {
382
            lineItem.setColor(item.getColor());
383
        }
384
    	return lineItem;
385
	}
386
 
387
    private void createPayment(User user, String paisaPayId, double amount) throws NumberFormatException, PaymentException, TException {
388
        in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
389
        long paymentId = client.createPayment(user.getUserId(), amount, EBAY_GATEWAY_ID, Long.valueOf(transactionId), false);
390
        client.updatePaymentDetails(paymentId, null, null, null, null, null, null, paisaPayId, null, PaymentStatus.PENDING, null, null);
391
    }   
392
 
393
	public String index() {
394
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), "/ebay-dashboard"))
395
            return "authfail";
396
        checkForErrors();
397
        return "authsuccess";
398
    }
399
 
400
	private boolean checkForErrors(){
401
        Collection<String> actionErrors = getActionErrors();
402
        if(actionErrors != null && !actionErrors.isEmpty()){
403
            for (String str : actionErrors) {
404
                errorMsg += "<BR/>" + str;
405
            }
406
            if(rowId>1) {
407
            	errorMsg += "<BR/>" + "Error while processing rowNumber : " + rowId;
408
            }
409
            return true;
410
        }
411
        return false;
412
    }
413
 
414
	@Override
415
	public void setServletRequest(HttpServletRequest request) {
416
		this.request = request;
417
        this.session = request.getSession();
418
	}
419
 
420
	public String getErrorMsg() {
421
		return errorMsg;
422
	}
423
 
424
	public void setErrorMsg(String errorMsg) {
425
		this.errorMsg = errorMsg;
426
	}
427
 
428
	public Long getRowId() {
429
		return rowId;
430
	}
431
 
432
	public void setRowId(Long rowId) {
433
		this.rowId = rowId;
434
	}
435
 
436
	public File getOrderDataFile() {
437
		return orderDataFile;
438
	}
439
 
440
	public void setOrderDataFile(File orderDataFile) {
441
		this.orderDataFile = orderDataFile;
442
	}
443
 
444
 
445
}