Subversion Repositories SmartDukaan

Rev

Rev 8488 | Rev 8569 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
8488 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.VendorItemPricing;
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.SnapdealOrder;
32
import in.shop2020.model.v1.order.SourceDetail;
33
import in.shop2020.model.v1.order.Transaction;
34
import in.shop2020.model.v1.order.TransactionStatus;
35
import in.shop2020.model.v1.order.TransactionService.Client;
36
import in.shop2020.model.v1.user.Address;
37
import in.shop2020.model.v1.user.User;
38
import in.shop2020.payments.Attribute;
39
import in.shop2020.payments.PaymentException;
40
import in.shop2020.payments.PaymentStatus;
41
import in.shop2020.thrift.clients.CatalogClient;
42
import in.shop2020.thrift.clients.InventoryClient;
43
import in.shop2020.thrift.clients.LogisticsClient;
44
import in.shop2020.thrift.clients.PaymentClient;
45
import in.shop2020.thrift.clients.TransactionClient;
46
import in.shop2020.thrift.clients.UserClient;
47
import in.shop2020.support.utils.ReportsUtils;
48
 
49
import javax.servlet.http.HttpServletRequest;
50
import javax.servlet.http.HttpSession;
51
 
52
import org.apache.commons.io.FileUtils;
53
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
54
import org.apache.poi.ss.usermodel.Cell;
55
import org.apache.poi.ss.usermodel.Row;
56
import org.apache.poi.ss.usermodel.Sheet;
57
import org.apache.poi.ss.usermodel.Workbook;
58
import org.apache.struts2.convention.annotation.InterceptorRef;
59
import org.apache.struts2.convention.annotation.InterceptorRefs;
60
import org.apache.struts2.convention.annotation.Result;
61
import org.apache.struts2.convention.annotation.Results;
62
import org.apache.struts2.interceptor.ServletRequestAware;
63
import org.apache.thrift.TException;
64
import org.slf4j.Logger;
65
import org.slf4j.LoggerFactory;
66
 
67
import com.opensymphony.xwork2.ActionSupport;
68
 
69
@SuppressWarnings("serial")
70
@InterceptorRefs({
71
    @InterceptorRef("defaultStack"),
72
    @InterceptorRef("login")
73
})
74
@Results({
75
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
76
})
77
public class SnapdealOrderCreatorController extends ActionSupport implements ServletRequestAware {
78
 
79
	private static Logger logger = LoggerFactory.getLogger(SnapdealOrderCreatorController.class);
80
 
81
	private HttpServletRequest request;
82
    private HttpSession session;
83
 
84
    private static final int SNAPDEAL_SOURCE_ID = 7;
85
 
86
    private static final int COURIER_INDEX = 0;
87
    private static final int PRODUCT_NAME_INDEX = 1;
88
    private static final int REFERENCE_CODE_INDEX = 2;
89
    private static final int SUBORDER_ID_INDEX = 3;
90
    private static final int ITEMID_INDEX = 4;
91
    private static final int AWB_INDEX = 5;
92
    private static final int TRANSACTION_DATE_INDEX = 6;
93
    private static final int BUYER_NAME_INDEX = 8;
94
    private static final int CITY_INDEX = 9;
95
    private static final int STATE_INDEX = 10;
96
    private static final int PINCODE_INDEX = 11;
97
    private static final int AMOUNT_INDEX = 12;
98
    private static final int WAREHOUSE_ID_INDEX = 14;
99
    private static final int OVERRIDE_BILLING_PRICE_INDEX = 15;
100
 
101
 
102
    private static final int SNAPDEAL_GATEWAY_ID = 18;
103
 
104
    private static final String FIRSTFLIGHT = "First Flight";
105
    private static final String DELHIVERY = "DELHIVERY";
8508 amar.kumar 106
    private static final String BLUEDART = "Bluedart";
8488 amar.kumar 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_Snapdeal_"+(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 Snapdeal", 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 Snapdeal ", e);
135
            setErrorMsg(getErrorMsg() + "Error in opening File for Order creation");
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(SNAPDEAL_SOURCE_ID);
147
        } catch (Exception e) {
148
            logger.error("Unable to establish connection to the transaction service while getting Snapdeal Source Detail", e);
149
            setErrorMsg(getErrorMsg() + "Error in Order Service while getting Snapdeal Source Detail");
150
            addActionError("Error in connecting to Order Service");
151
		}
152
 
153
        if(checkForErrors())
154
            return "authsuccess";
155
 
156
	    try {   
157
	        in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
158
	        user = userClient.getUserByEmail(sourceDetail.getEmail());
159
	    } catch (Exception e) {
160
	        logger.error("Unable to establish connection to the User service", e);
161
	        setErrorMsg(getErrorMsg() + "Unable to get Default Email for Snapdeal ");
162
	        addActionError("Unable to get Default Email for Snapdeal ");
163
		}
164
 
165
        if(checkForErrors())
166
            return "authsuccess";
167
 
168
        Sheet sheet = wb.getSheetAt(0);
169
        Row firstRow = sheet.getRow(0);
170
        for (Row row : sheet) {
171
        	long orderCountForRow = 0;
172
        	rowId++;
173
            if(row.equals(firstRow))
174
                continue;
175
        	try {
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 Snapdeal ");
182
 
183
	            List<Order> orders = new ArrayList<Order>();
184
 
185
	            row.getCell(ITEMID_INDEX).setCellType(Cell.CELL_TYPE_STRING);
186
	            Long itemId = Long.parseLong(row.getCell(ITEMID_INDEX).getStringCellValue());
187
	    		double listingPrice = 0;
188
	    		double overriddenPrice = 0;
189
	    		double totalPrice = 0;
190
	    		Cell overriddenPriceCell = row.getCell(OVERRIDE_BILLING_PRICE_INDEX);
191
	        	if(overriddenPriceCell  != null && overriddenPriceCell .getCellType() != Cell.CELL_TYPE_BLANK) {
192
	        		overriddenPrice = row.getCell(OVERRIDE_BILLING_PRICE_INDEX).getNumericCellValue();
193
	        	}
194
 
195
	    		totalPrice = row.getCell(AMOUNT_INDEX).getNumericCellValue();
196
	    		listingPrice = totalPrice;
197
	    		if(overriddenPrice>=1) {
198
	    			totalPrice = overriddenPrice;
199
	    		}
200
	        	LineItem lineItem = null;
201
	        	try {
202
	        		lineItem = createLineItem(itemId, totalPrice);
203
	        	} catch (Exception tex) {
204
	        		logger.error("Unable to create order for RowId " + rowId, tex);
205
	        		setErrorMsg(getErrorMsg() + "<br>Unable to create lineitem using catalog info for RowId " + rowId);
206
	    	        continue;
207
	        	}
208
	            Order t_order = new Order();
209
	            t_order.setCustomer_id(user.getUserId());
210
	            t_order.setCustomer_email(sourceDetail.getEmail());
211
	            row.getCell(BUYER_NAME_INDEX).setCellType(Cell.CELL_TYPE_STRING);
212
	        	t_order.setCustomer_name(row.getCell(BUYER_NAME_INDEX).getStringCellValue());
213
	        	t_order.setCustomer_address1("");
214
	        	t_order.setCustomer_address2("");
215
	        	t_order.setCustomer_city(row.getCell(CITY_INDEX).getStringCellValue());
216
	        	t_order.setCustomer_state(row.getCell(STATE_INDEX).getStringCellValue());
217
	        	row.getCell(PINCODE_INDEX).setCellType(Cell.CELL_TYPE_STRING);
218
	        	t_order.setCustomer_pincode(row.getCell(PINCODE_INDEX).getStringCellValue());
219
	            t_order.setTotal_amount(lineItem.getTotal_price());            
220
	            t_order.setTotal_weight(lineItem.getTotal_weight());
221
	            t_order.setLineitems(Collections.singletonList(lineItem));            
222
	            t_order.setStatus(OrderStatus.SUBMITTED_FOR_PROCESSING);
223
	            t_order.setStatusDescription("In Process");
224
	            t_order.setCreated_timestamp(new Date().getTime());
225
	            t_order.setOrderType(OrderType.B2C);
226
	            t_order.setCod(false);
227
	            try {
228
	            	Calendar time = Calendar.getInstance();
229
	            	time.add(Calendar.DAY_OF_MONTH, 1);
230
	            	t_order.setPromised_shipping_time(time.getTimeInMillis());
231
	            	t_order.setExpected_shipping_time(time.getTimeInMillis());
232
	            	time.add(Calendar.DAY_OF_MONTH, 3);
233
	            	t_order.setPromised_delivery_time(time.getTimeInMillis());
234
	            	t_order.setExpected_delivery_time(time.getTimeInMillis());
235
	            } catch(Exception e) {
236
	            	addActionError("Error in updating Shipping or Delivery Time for row number " + rowId);
237
	            	logger.error("Error in updating Shipping or Delivery Time for row number " + rowId,e);
238
	            	continue;
239
	            }
240
 
241
	            InventoryService.Client inventoryClient = null;
242
	            Warehouse fulfillmentWarehouse= null; 
243
	            try {
244
	            	inventoryClient = new InventoryClient().getClient();
245
	            	Cell warehouseCell = row.getCell(WAREHOUSE_ID_INDEX);
246
	            	if(warehouseCell != null && warehouseCell.getCellType() != Cell.CELL_TYPE_BLANK) {
247
	            		fulfillmentWarehouse = inventoryClient.getWarehouse(new Double(row.getCell(WAREHOUSE_ID_INDEX).getNumericCellValue()).longValue());
248
	            	} else {
249
	            		List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(itemId, 1);
250
	            		fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
251
	            	}
252
	            	t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
253
	        		t_order.setWarehouse_id(fulfillmentWarehouse.getBillingWarehouseId());
254
 
255
	        		VendorItemPricing vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), fulfillmentWarehouse.getVendor().getId());
256
	        		t_order.getLineitems().get(0).setTransfer_price(vendorItemPricing.getTransferPrice());
257
	        		t_order.getLineitems().get(0).setNlc(vendorItemPricing.getNlc());
258
				} catch (InventoryServiceException e) {
259
					addActionError("Error in updating WarehouseId for row number " + rowId);
260
					setErrorMsg(getErrorMsg() + "<br>Error in updating WarehouseId for row number  " + rowId);
261
	            	logger.error("Error in updating WarehouseId for row number " + rowId,e);
262
	            	continue;
263
				}
264
 
265
				String provider = row.getCell(COURIER_INDEX).getStringCellValue();
266
				if(provider.equals(FIRSTFLIGHT)) {
267
					t_order.setLogistics_provider_id(12);
268
				} else if(provider.equals(DELHIVERY)) {
269
					t_order.setLogistics_provider_id(13);
8508 amar.kumar 270
				} else if(provider.equals(BLUEDART)) {
271
					t_order.setLogistics_provider_id(14);
8488 amar.kumar 272
				} else {
273
					addActionError("Unknown logistics provider found for row number " + rowId);
274
					setErrorMsg(getErrorMsg() + "<br>Unknown logistics provider found for row number " + rowId);
275
	            	logger.error("Unknown logistics provider found for row number " + rowId);
276
	            	continue;
277
				}
278
 
279
				row.getCell(AWB_INDEX).setCellType(Cell.CELL_TYPE_STRING);
280
				t_order.setAirwaybill_no(row.getCell(AWB_INDEX).getStringCellValue());
281
				t_order.setTracking_id(row.getCell(AWB_INDEX).getStringCellValue());
282
	            t_order.setTotal_amount(totalPrice);
283
	            t_order.setOrderType(OrderType.B2C);
284
	            t_order.setSource(SNAPDEAL_SOURCE_ID);
285
	            t_order.setOrderType(OrderType.B2C);
286
	            orders.add(t_order);
287
	            orderCountForRow++;
288
 
289
	            txn.setOrders(orders);
290
	            Client transaction_client = new TransactionClient().getClient();
291
	            try {
292
	            	long subOrderId = new Double(row.getCell(SUBORDER_ID_INDEX).getNumericCellValue()).longValue();
293
	            	String referenceCode = row.getCell(REFERENCE_CODE_INDEX).getStringCellValue();
294
	            	String productName = row.getCell(PRODUCT_NAME_INDEX).getStringCellValue();
295
	            	Date snapdealTxnDate = row.getCell(TRANSACTION_DATE_INDEX).getDateCellValue();
296
 
297
	            	if(transaction_client.snapdealOrderExists(subOrderId)) {
298
	            		setErrorMsg(getErrorMsg() + "<br>Duplicate order for subOrderId " + subOrderId + " for row number  " + rowId);
299
	            		logger.error("Duplicate order for subOrderId " + subOrderId + " for row number  " + rowId);
300
	            		continue;
301
	            	}
302
 
303
	            	transactionId =  String.valueOf(transaction_client.createTransaction(txn));
304
	            	createPayment(user, (new Long(subOrderId)).toString(), totalPrice);
305
 
306
	                logger.info("Successfully created transaction: " + transactionId + " for amount: " + totalPrice);
307
 
308
	                Transaction transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
309
	                Order order = transaction.getOrders().get(0);
310
 
311
	                inventoryClient.reserveItemInWarehouse(itemId, fulfillmentWarehouse.getId(), 1, 
312
	                		order.getId(), order.getCreated_timestamp(), order.getPromised_shipping_time(), order.getLineitems().get(0).getQuantity());
313
 
314
 
315
	                SnapdealOrder snapdealOrder = new SnapdealOrder();
316
	                snapdealOrder.setOrderId(order.getId());
317
	                snapdealOrder.setSubOrderId(subOrderId);
318
	                snapdealOrder.setReferenceCode(referenceCode);
319
	                snapdealOrder.setProductName(productName);
320
	                snapdealOrder.setSnapdealTxnDate(snapdealTxnDate.getTime());
321
	                snapdealOrder.setListingPrice(listingPrice);
322
	                transaction_client.createSnapdealOrder(snapdealOrder);
323
 
324
 
325
	            } catch (Exception e) {
326
	                logger.error("Error while creating order for rowId " + rowId, e);
327
	                addActionError("Error while creating order for rowId " + rowId);
328
	                setErrorMsg(getErrorMsg() + "<br>Error while creating order for row number " + rowId);
329
	                continue;
330
	    		}
331
        	} catch (Exception e) {
332
        		logger.error("Error while creating order for row number " + rowId);
333
        		setErrorMsg(getErrorMsg() + "<br>Error while creating order for row number " + rowId);
334
        		continue;
335
        	}
336
        }
337
 
338
        checkForErrors();
339
        return "authsuccess";
340
    }
341
 
342
    private Date interchangeDateAndMonth(Date date) {
343
		Date updatedDate = new Date(date.getTime());
344
		updatedDate.setDate(date.getMonth() + 1);
345
		updatedDate.setMonth(date.getDate() - 1);
346
		return updatedDate;
347
	}
348
 
349
	private LineItem createLineItem(long itemId, double amount) throws CatalogServiceException, TException {
350
    	LineItem lineItem = new LineItem();
351
    	CatalogService.Client catalogClient = new CatalogClient().getClient();
352
    	Item item = catalogClient.getItem(itemId);
353
 
354
    	lineItem.setProductGroup(item.getProductGroup());
355
        lineItem.setBrand(item.getBrand());
356
        lineItem.setModel_number(item.getModelNumber());
357
        lineItem.setModel_name(item.getModelName());
358
        lineItem.setExtra_info(item.getFeatureDescription());
359
        lineItem.setQuantity(1);
360
        lineItem.setItem_id(item.getId());
361
        lineItem.setUnit_weight(item.getWeight());
362
        lineItem.setTotal_weight(item.getWeight());
363
        lineItem.setUnit_price(amount);
364
        lineItem.setTotal_price(amount);
365
 
366
        if (item.getColor() == null || "NA".equals(item.getColor())) {
367
            lineItem.setColor("");
368
        } else {
369
            lineItem.setColor(item.getColor());
370
        }
371
    	return lineItem;
372
	}
373
 
374
    private void createPayment(User user, String subOrderId, double amount) throws NumberFormatException, PaymentException, TException {
375
        in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
376
        long paymentId = client.createPayment(user.getUserId(), amount, SNAPDEAL_GATEWAY_ID, Long.valueOf(transactionId), false);
377
        client.updatePaymentDetails(paymentId, null, null, null, null, null, null, subOrderId, null, PaymentStatus.AUTHORIZED, null, null);
378
    }   
379
 
380
	public String index() {
381
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), "/ebay-dashboard"))
382
            return "authfail";
383
        checkForErrors();
384
        return "authsuccess";
385
    }
386
 
387
	private boolean checkForErrors(){
388
        Collection<String> actionErrors = getActionErrors();
389
        if(actionErrors != null && !actionErrors.isEmpty()){
390
            for (String str : actionErrors) {
391
                errorMsg += "<BR/>" + str;
392
            }
393
            return true;
394
        }
395
        return false;
396
    }
397
 
398
	@Override
399
	public void setServletRequest(HttpServletRequest request) {
400
		this.request = request;
401
        this.session = request.getSession();
402
	}
403
 
404
	public String getErrorMsg() {
405
		return errorMsg;
406
	}
407
 
408
	public void setErrorMsg(String errorMsg) {
409
		this.errorMsg = errorMsg;
410
	}
411
 
412
	public Long getRowId() {
413
		return rowId;
414
	}
415
 
416
	public void setRowId(Long rowId) {
417
		this.rowId = rowId;
418
	}
419
 
420
	public File getOrderDataFile() {
421
		return orderDataFile;
422
	}
423
 
424
	public void setOrderDataFile(File orderDataFile) {
425
		this.orderDataFile = orderDataFile;
426
	}
427
 
428
}