Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
7410 amar.kumar 1
package in.shop2020.support.controllers;
2
 
3
import in.shop2020.model.v1.catalog.CatalogService;
4
import in.shop2020.model.v1.catalog.CatalogServiceException;
5
import in.shop2020.model.v1.catalog.Item;
6
import in.shop2020.model.v1.order.LineItem;
7
import in.shop2020.model.v1.order.Order;
8
import in.shop2020.model.v1.order.OrderSource;
9
import in.shop2020.model.v1.order.OrderStatus;
10
import in.shop2020.model.v1.order.OrderType;
11
import in.shop2020.model.v1.order.SourceDetail;
12
import in.shop2020.model.v1.order.Transaction;
13
import in.shop2020.model.v1.order.TransactionService.Client;
14
import in.shop2020.model.v1.order.TransactionServiceException;
15
import in.shop2020.model.v1.order.TransactionStatus;
16
import in.shop2020.model.v1.user.Address;
17
import in.shop2020.model.v1.user.User;
18
import in.shop2020.model.v1.user.UserContextException;
19
import in.shop2020.payments.Attribute;
20
import in.shop2020.payments.PaymentException;
21
import in.shop2020.payments.PaymentStatus;
22
import in.shop2020.support.utils.ReportsUtils;
23
import in.shop2020.thrift.clients.CatalogClient;
24
import in.shop2020.thrift.clients.PaymentClient;
25
import in.shop2020.thrift.clients.TransactionClient;
26
import in.shop2020.thrift.clients.UserClient;
27
 
28
import java.io.File;
29
import java.io.FileInputStream;
30
import java.io.FileNotFoundException;
31
import java.io.IOException;
32
import java.util.ArrayList;
33
import java.util.Collection;
34
import java.util.Collections;
35
import java.util.Date;
36
import java.util.List;
37
 
38
import javax.servlet.http.HttpServletRequest;
39
import javax.servlet.http.HttpSession;
40
 
41
import org.apache.commons.io.FileUtils;
42
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
43
import org.apache.poi.ss.usermodel.Row;
44
import org.apache.poi.ss.usermodel.Sheet;
45
import org.apache.poi.ss.usermodel.Workbook;
46
import org.apache.struts2.convention.annotation.InterceptorRef;
47
import org.apache.struts2.convention.annotation.InterceptorRefs;
48
import org.apache.struts2.convention.annotation.Result;
49
import org.apache.struts2.convention.annotation.Results;
50
import org.apache.struts2.interceptor.ServletRequestAware;
51
import org.apache.thrift.TException;
52
import org.apache.thrift.transport.TTransportException;
53
import org.slf4j.Logger;
54
import org.slf4j.LoggerFactory;
55
 
56
import com.opensymphony.xwork2.ActionSupport;
57
 
58
@SuppressWarnings("serial")
59
@InterceptorRefs({
60
    @InterceptorRef("defaultStack"),
61
    @InterceptorRef("login")
62
})
63
@Results({
64
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
65
})
66
public class SourceOrderCreationController extends ActionSupport implements ServletRequestAware {
67
 
68
    private static Logger logger = LoggerFactory.getLogger(SourceOrderCreationController.class);
69
 
70
    private static final int ITEM_ID_INDEX = 0;
71
    private static final int QUANTITY_INDEX = 1;
72
    private static final int BILLING_NAME_INDEX = 2;
73
    private static final int AMOUNT_PER_ORDER_INDEX = 3;
74
    private static final int CUST_EMAIL_INDEX = 4;
75
    private static final int CUST_MOBILE_INDEX = 5;
76
    private static final int CUST_ADDR1_INDEX = 6;
77
    private static final int CUST_ADDR2_INDEX = 7;
78
    private static final int CUST_CITY_INDEX = 8;
79
    private static final int CUST_STATE_INDEX = 9;
80
    private static final int CUST_PIN_INDEX = 10;
81
 
82
    private static final String PAY_METHOD  = "payMethod";
83
    private static final int RTGS_GATEWAY_ID = 6;
84
 
85
    private HttpServletRequest request;
86
    private HttpSession session;
87
 
88
    private File orderDataFile;
89
    private Long sourceId;
90
    private String orderDataFileName;
91
    private Long orderType;
92
    private Long pickUpType;
93
    private String transactionId;
94
    private Long amount;
95
    private String errorMsg = "";
96
    private Long rowId = 0L;
97
 
98
    public String index() {
99
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getServletPath()))
100
            return "authfail";
101
        checkForErrors();
102
        return "authsuccess";
103
    }
104
 
105
    public String create() throws TException {
106
        File fileToCreate = null;
107
        orderDataFileName = "OrderSheet_"+sourceId+"_"+(new Date().toString());
108
        try {
109
            fileToCreate = new File("/tmp/", this.orderDataFileName);
110
            FileUtils.copyFile(this.orderDataFile, fileToCreate);
111
        } catch (Exception e) {
112
           logger.error("Error while writing order data file to the local file system", e);
113
           addActionError("Error while writing order data file to the local file system");
114
        }
115
 
116
 
117
        if(checkForErrors())
118
            return "authsuccess";
119
 
120
        //Parse the file and submit the data for update to the transaction service
121
        Workbook wb = null;
122
        try {
123
            wb = new HSSFWorkbook(new FileInputStream(fileToCreate));
124
        } catch (FileNotFoundException e) {
125
            logger.error("Unable to open the File for Order Creation for SourceId " + sourceId, e);
126
            addActionError("Unable to open the File for Order creation");
127
        } catch (IOException e) {
128
        	logger.error("Unable to open the File for Order Creation for SourceId " + sourceId, e);
129
        	addActionError("Unable to open the File for Order creation");
130
        }
131
        if(checkForErrors())
132
            return "authsuccess";
133
 
134
        SourceDetail sourceDetail = null;
135
        User user = null;
136
        TransactionClient tsc = null;
137
        try {
138
            tsc = new TransactionClient();
139
			sourceDetail = tsc.getClient().getSourceDetail(sourceId);
140
        } catch (TTransportException e) {
141
            logger.error("Unable to establish connection to the transaction service", e);
142
            addActionError("Unable to establish connection to the transaction service");
143
        } catch (TException e) {
144
            logger.error("Unable to establish connection to the transaction service", e);
145
            addActionError("Unable to establish connection to the transaction service");
146
		}
147
 
148
        if(checkForErrors())
149
            return "authsuccess";
150
 
151
	    try {   
152
	        in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
153
	        user = userClient.getUserByEmail(sourceDetail.getEmail());
154
	    } catch (TTransportException e) {
155
	        logger.error("Unable to establish connection to the User service", e);
156
	        addActionError("Unable to establish connection to the User service");
157
	    } catch (TException e) {
158
	        logger.error("Unable to establish connection to the User service", e);
159
	        addActionError("Unable to establish connection to the User service");
160
		} catch (UserContextException e) {
161
			logger.error("Unable to establish connection to the User service", e);
162
			addActionError("Unable to establish connection to the User service");
163
		}
164
 
165
        if (user == null) {
166
            addActionError("Could not find default user for SourceId: " + sourceId);
167
        }
168
 
169
        if(checkForErrors())
170
            return "authsuccess";
171
 
172
        Sheet sheet = wb.getSheetAt(0);
173
        Row firstRow = sheet.getRow(0);
174
        logger.info("Last row number is:" + sheet.getLastRowNum());
175
        for (Row row : sheet) {
176
        	long orderCountForRow = 0;
177
            if(row.equals(firstRow))
178
                continue;
179
            rowId++;
180
            Transaction txn = new Transaction();
181
            txn.setShoppingCartid(user.getActiveCartId());
182
            txn.setCustomer_id(user.getUserId());
183
            txn.setCreatedOn(new Date().getTime());
184
            txn.setTransactionStatus(TransactionStatus.INIT);
185
            txn.setStatusDescription("Order for SourceId : " + sourceId);
186
 
187
            List<Order> orders = new ArrayList<Order>();
188
 
189
            // Extracting default address
190
            Address defaultAddress = null;
191
            for (Address address : user.getAddresses()) {
192
                if (address.getId() == user.getDefaultAddressId()) {
193
                    defaultAddress = address;
194
                    break;
195
                }
196
            }
197
 
198
            while(orderCountForRow <row.getCell(QUANTITY_INDEX).getNumericCellValue()) {
199
            	LineItem lineItem = null;
200
            	try {
201
            		lineItem = createLineItem(row.getCell(ITEM_ID_INDEX).getNumericCellValue());
202
            		lineItem.setTotal_price(row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue());
203
            		lineItem.setUnit_price(row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue());
204
            	} catch (TException tex) {
205
            		logger.error("Unable to establish connection to the Catalog service", tex);
206
        	        addActionError("Unable to establish connection to the Catalog service");
207
        	        return "authsuccess";
208
            	} catch (CatalogServiceException csex) {
209
            		logger.error("Unable to establish connection to the Catalog service", csex);
210
        	        addActionError("Unable to establish connection to the Catalog service");
211
        	        return "authsuccess";
212
            	}
213
                Order t_order = new Order();
214
                t_order.setCustomer_id(user.getUserId());
215
                t_order.setCustomer_email(sourceDetail.getEmail());
216
                if(row.getCell(BILLING_NAME_INDEX)!=null && row.getCell(BILLING_NAME_INDEX).getStringCellValue()!=null && 
217
                		!row.getCell(BILLING_NAME_INDEX).getStringCellValue().isEmpty()) {
218
                	t_order.setCustomer_name(row.getCell(BILLING_NAME_INDEX).getStringCellValue());
219
                } else {
220
                	t_order.setCustomer_name(sourceDetail.getName());
221
                }
222
                if(row.getCell(CUST_ADDR1_INDEX)!=null && row.getCell(CUST_CITY_INDEX)!=null && row.getCell(CUST_STATE_INDEX)!=null &&
223
                		row.getCell(CUST_PIN_INDEX)!=null) {
224
                	t_order.setCustomer_pincode(new Long(new Double(row.getCell(CUST_PIN_INDEX).getNumericCellValue()).longValue()).toString());
225
	                t_order.setCustomer_address1(row.getCell(CUST_ADDR1_INDEX).getStringCellValue());
226
	                if(row.getCell(CUST_ADDR2_INDEX)!=null) {
227
	                	t_order.setCustomer_address2(row.getCell(CUST_ADDR2_INDEX).getStringCellValue());
228
	                }
229
	                t_order.setCustomer_city(row.getCell(CUST_CITY_INDEX).getStringCellValue());
230
	                t_order.setCustomer_state(row.getCell(CUST_STATE_INDEX).getStringCellValue());
231
                } else {
232
                	if(pickUpType !=2 ) {
233
                		addActionError("Customer address is mandatory if pickupType is not selected as Self-Pickup");
234
                		return "authsuccess";
235
                	}
236
                	t_order.setCustomer_pincode(defaultAddress.getPin());
237
	                t_order.setCustomer_address1(defaultAddress.getLine1());
238
	                t_order.setCustomer_address2(defaultAddress.getLine2());
239
	                t_order.setCustomer_city(defaultAddress.getCity());
240
	                t_order.setCustomer_state(defaultAddress.getState());
241
                }
242
                try {
243
                	t_order.setCustomer_mobilenumber(new Double(row.getCell(CUST_MOBILE_INDEX).getNumericCellValue()).toString());
244
                } catch (Exception e) {
245
                	logger.error("Error in reading mobile Number for SourceId " + sourceId + "  and rowNumber " + row.getRowNum());
246
                }	
247
                //t_order.setTotal_amount(lineItem.getTotal_price());            
248
                t_order.setTotal_weight(lineItem.getTotal_weight());
249
                t_order.setLineitems(Collections.singletonList(lineItem));            
250
                t_order.setStatus(OrderStatus.PAYMENT_PENDING);
251
                t_order.setStatusDescription("Payment Pending");
252
                t_order.setCreated_timestamp(new Date().getTime());
253
                t_order.setTotal_amount(row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue());
254
                t_order.setSource(sourceId);
255
                orders.add(t_order);
256
                orderCountForRow++;
257
            }
258
            amount = new Double (row.getCell(1).getNumericCellValue() * row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue()).longValue();
259
 
260
 
261
            txn.setOrders(orders);
262
            Client transaction_client = new TransactionClient().getClient();
263
            try {
264
            	transactionId =  String.valueOf(transaction_client.createTransaction(txn));
265
            	createPayment(user);
266
 
267
            	in.shop2020.model.v1.order.Attribute orderAttribute = new in.shop2020.model.v1.order.Attribute();
268
                orderAttribute.setName("tinNumber");
269
                orderAttribute.setValue(sourceDetail.getTinNumber());
270
 
271
                if(!sourceDetail.getTinNumber().equals("") && !(sourceDetail.getTinNumber() == null)) {
272
                	transaction_client.setOrderAttributeForTransaction(Long.parseLong(transactionId), orderAttribute);
273
                }
274
                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()));
275
                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()));
276
                logger.info("Successfully created transaction: " + transactionId + " for amount: " + amount);
277
 
278
            } catch (TTransportException e) {
279
                logger.error("Unable to establish connection to the transaction service", e);
280
                addActionError("Unable to establish connection to the transaction service");
281
                return "authsuccess";
282
            } catch (TException e) {
283
                logger.error("Unable to establish connection to the transaction service", e);
284
                addActionError("Unable to establish connection to the transaction service");
285
                return "authsuccess";
286
    		} catch (TransactionServiceException e) {
287
                logger.error("Unable to establish connection to the transaction service", e);
288
                addActionError("Unable to establish connection to the transaction service");
289
                return "authsuccess";
290
    		} catch (PaymentException e) {
291
                logger.error("Unable to establish connection to the transaction service", e);
292
                addActionError("Unable to establish connection to the transaction service");
293
                return "authsuccess";
294
    		}
295
        }
296
 
297
        checkForErrors();
298
        return "authsuccess";
299
    }
300
 
301
    private LineItem createLineItem(Double itemId) throws CatalogServiceException, TException {
302
    	LineItem lineItem = new LineItem();
303
    	CatalogService.Client catalogClient = new CatalogClient().getClient();
304
    	Item item = catalogClient.getItem(itemId.longValue());
305
 
306
    	lineItem.setProductGroup(item.getProductGroup());
307
        lineItem.setBrand(item.getBrand());
308
        lineItem.setModel_number(item.getModelNumber());
309
        lineItem.setModel_name(item.getModelName());
310
        lineItem.setExtra_info(item.getFeatureDescription());
311
        lineItem.setItem_id(item.getId());
312
        lineItem.setUnit_weight(item.getWeight());
313
        lineItem.setTotal_weight(item.getWeight());
314
        //lineItem.setDealText(item.getBestDealText());
315
        //lineItem.setTotal_price(lineItem.getUnit_price());
316
 
317
        if (item.getColor() == null || "NA".equals(item.getColor())) {
318
            lineItem.setColor("");
319
        } else {
320
            lineItem.setColor(item.getColor());
321
        }
322
    	return lineItem;
323
	}
324
 
325
    private void createPayment(User user) throws NumberFormatException, PaymentException, TException {
326
        List<Attribute> paymentAttributes = new ArrayList<Attribute>();
327
        paymentAttributes.add(new Attribute(PAY_METHOD, "4000"));
328
        paymentAttributes.add(new Attribute("sourceId", sourceId.toString()));
329
 
330
        in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
331
        long paymentId = client.createPayment(user.getUserId(), Double.valueOf(amount), RTGS_GATEWAY_ID, Long.valueOf(transactionId), false);
332
        client.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null, PaymentStatus.SUCCESS, null, paymentAttributes);
333
    }
334
 
335
	@Override
336
    public void setServletRequest(HttpServletRequest request) {
337
        this.request = request;
338
        this.session = request.getSession();
339
    }
340
 
341
    public String getErrorMsg(){
342
        return this.errorMsg;
343
    }
344
 
345
    private boolean checkForErrors(){
346
        Collection<String> actionErrors = getActionErrors();
347
        if(actionErrors != null && !actionErrors.isEmpty()){
348
            for (String str : actionErrors) {
349
                errorMsg += "<BR/>" + str;
350
            }
351
            if(rowId>1) {
352
            	errorMsg += "<BR/>" + "Error while processing rowNumber : " + rowId;
353
            }
354
            return true;
355
        }
356
        return false;
357
    }
358
 
359
	public File getOrderDataFile() {
360
		return orderDataFile;
361
	}
362
 
363
	public void setOrderDataFile(File orderDataFile) {
364
		this.orderDataFile = orderDataFile;
365
	}
366
 
367
	public String getOrderDataFileName() {
368
		return orderDataFileName;
369
	}
370
 
371
	public void setOrderDataFileName(String orderDataFileName) {
372
		this.orderDataFileName = orderDataFileName;
373
	}
374
 
375
	public Long getSourceId() {
376
		return sourceId;
377
	}
378
 
379
	public void setSourceId(Long sourceId) {
380
		this.sourceId = sourceId;
381
	}
382
 
383
	public Long getOrderType() {
384
		return orderType;
385
	}
386
 
387
	public void setOrderType(Long orderType) {
388
		this.orderType = orderType;
389
	}
390
 
391
	public Long getPickUpType() {
392
		return pickUpType;
393
	}
394
 
395
	public void setPickUpType(Long pickUpType) {
396
		this.pickUpType = pickUpType;
397
	}
398
 
399
}