Subversion Repositories SmartDukaan

Rev

Rev 7410 | Details | Compare with Previous | 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
 
8182 amar.kumar 70
    private static final int AMAZON_SOURCE_ID = 3;
71
 
7410 amar.kumar 72
    private static final int ITEM_ID_INDEX = 0;
73
    private static final int QUANTITY_INDEX = 1;
74
    private static final int BILLING_NAME_INDEX = 2;
75
    private static final int AMOUNT_PER_ORDER_INDEX = 3;
76
    private static final int CUST_EMAIL_INDEX = 4;
77
    private static final int CUST_MOBILE_INDEX = 5;
78
    private static final int CUST_ADDR1_INDEX = 6;
79
    private static final int CUST_ADDR2_INDEX = 7;
80
    private static final int CUST_CITY_INDEX = 8;
81
    private static final int CUST_STATE_INDEX = 9;
82
    private static final int CUST_PIN_INDEX = 10;
8182 amar.kumar 83
    private static final int AMAZON_ORDER_ID = 11;
7410 amar.kumar 84
 
85
    private static final String PAY_METHOD  = "payMethod";
86
    private static final int RTGS_GATEWAY_ID = 6;
87
 
88
    private HttpServletRequest request;
89
    private HttpSession session;
90
 
91
    private File orderDataFile;
92
    private Long sourceId;
93
    private String orderDataFileName;
94
    private Long orderType;
95
    private Long pickUpType;
96
    private String transactionId;
97
    private Long amount;
98
    private String errorMsg = "";
99
    private Long rowId = 0L;
100
 
101
    public String index() {
102
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getServletPath()))
103
            return "authfail";
104
        checkForErrors();
105
        return "authsuccess";
106
    }
107
 
108
    public String create() throws TException {
109
        File fileToCreate = null;
110
        orderDataFileName = "OrderSheet_"+sourceId+"_"+(new Date().toString());
111
        try {
112
            fileToCreate = new File("/tmp/", this.orderDataFileName);
113
            FileUtils.copyFile(this.orderDataFile, fileToCreate);
114
        } catch (Exception e) {
115
           logger.error("Error while writing order data file to the local file system", e);
116
           addActionError("Error while writing order data file to the local file system");
117
        }
118
 
119
 
120
        if(checkForErrors())
121
            return "authsuccess";
122
 
123
        //Parse the file and submit the data for update to the transaction service
124
        Workbook wb = null;
125
        try {
126
            wb = new HSSFWorkbook(new FileInputStream(fileToCreate));
8182 amar.kumar 127
        } catch (Exception e) {
7410 amar.kumar 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);
8182 amar.kumar 140
        } catch (Exception e) {
7410 amar.kumar 141
            logger.error("Unable to establish connection to the transaction service", e);
142
            addActionError("Unable to establish connection to the transaction service");
143
		}
144
 
145
        if(checkForErrors())
146
            return "authsuccess";
147
 
148
	    try {   
149
	        in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
150
	        user = userClient.getUserByEmail(sourceDetail.getEmail());
8182 amar.kumar 151
	    } catch (Exception e) {
7410 amar.kumar 152
	        logger.error("Unable to establish connection to the User service", e);
153
	        addActionError("Unable to establish connection to the User service");
154
		}
155
 
156
        if (user == null) {
157
            addActionError("Could not find default user for SourceId: " + sourceId);
158
        }
159
 
160
        if(checkForErrors())
161
            return "authsuccess";
162
 
163
        Sheet sheet = wb.getSheetAt(0);
164
        Row firstRow = sheet.getRow(0);
165
        logger.info("Last row number is:" + sheet.getLastRowNum());
166
        for (Row row : sheet) {
167
        	long orderCountForRow = 0;
168
            if(row.equals(firstRow))
169
                continue;
170
            rowId++;
171
            Transaction txn = new Transaction();
172
            txn.setShoppingCartid(user.getActiveCartId());
173
            txn.setCustomer_id(user.getUserId());
174
            txn.setCreatedOn(new Date().getTime());
175
            txn.setTransactionStatus(TransactionStatus.INIT);
176
            txn.setStatusDescription("Order for SourceId : " + sourceId);
177
 
178
            List<Order> orders = new ArrayList<Order>();
179
 
180
            // Extracting default address
181
            Address defaultAddress = null;
182
            for (Address address : user.getAddresses()) {
183
                if (address.getId() == user.getDefaultAddressId()) {
184
                    defaultAddress = address;
185
                    break;
186
                }
187
            }
188
 
189
            while(orderCountForRow <row.getCell(QUANTITY_INDEX).getNumericCellValue()) {
190
            	LineItem lineItem = null;
191
            	try {
192
            		lineItem = createLineItem(row.getCell(ITEM_ID_INDEX).getNumericCellValue());
193
            		lineItem.setTotal_price(row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue());
194
            		lineItem.setUnit_price(row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue());
8182 amar.kumar 195
            	} catch (Exception tex) {
7410 amar.kumar 196
            		logger.error("Unable to establish connection to the Catalog service", tex);
197
        	        addActionError("Unable to establish connection to the Catalog service");
198
        	        return "authsuccess";
199
            	}
200
                Order t_order = new Order();
201
                t_order.setCustomer_id(user.getUserId());
202
                t_order.setCustomer_email(sourceDetail.getEmail());
203
                if(row.getCell(BILLING_NAME_INDEX)!=null && row.getCell(BILLING_NAME_INDEX).getStringCellValue()!=null && 
204
                		!row.getCell(BILLING_NAME_INDEX).getStringCellValue().isEmpty()) {
205
                	t_order.setCustomer_name(row.getCell(BILLING_NAME_INDEX).getStringCellValue());
206
                } else {
207
                	t_order.setCustomer_name(sourceDetail.getName());
208
                }
209
                if(row.getCell(CUST_ADDR1_INDEX)!=null && row.getCell(CUST_CITY_INDEX)!=null && row.getCell(CUST_STATE_INDEX)!=null &&
210
                		row.getCell(CUST_PIN_INDEX)!=null) {
211
                	t_order.setCustomer_pincode(new Long(new Double(row.getCell(CUST_PIN_INDEX).getNumericCellValue()).longValue()).toString());
212
	                t_order.setCustomer_address1(row.getCell(CUST_ADDR1_INDEX).getStringCellValue());
213
	                if(row.getCell(CUST_ADDR2_INDEX)!=null) {
214
	                	t_order.setCustomer_address2(row.getCell(CUST_ADDR2_INDEX).getStringCellValue());
215
	                }
216
	                t_order.setCustomer_city(row.getCell(CUST_CITY_INDEX).getStringCellValue());
217
	                t_order.setCustomer_state(row.getCell(CUST_STATE_INDEX).getStringCellValue());
218
                } else {
219
                	if(pickUpType !=2 ) {
220
                		addActionError("Customer address is mandatory if pickupType is not selected as Self-Pickup");
221
                		return "authsuccess";
222
                	}
223
                	t_order.setCustomer_pincode(defaultAddress.getPin());
224
	                t_order.setCustomer_address1(defaultAddress.getLine1());
225
	                t_order.setCustomer_address2(defaultAddress.getLine2());
226
	                t_order.setCustomer_city(defaultAddress.getCity());
227
	                t_order.setCustomer_state(defaultAddress.getState());
228
                }
229
                try {
230
                	t_order.setCustomer_mobilenumber(new Double(row.getCell(CUST_MOBILE_INDEX).getNumericCellValue()).toString());
231
                } catch (Exception e) {
232
                	logger.error("Error in reading mobile Number for SourceId " + sourceId + "  and rowNumber " + row.getRowNum());
233
                }	
234
                //t_order.setTotal_amount(lineItem.getTotal_price());            
235
                t_order.setTotal_weight(lineItem.getTotal_weight());
236
                t_order.setLineitems(Collections.singletonList(lineItem));            
237
                t_order.setStatus(OrderStatus.PAYMENT_PENDING);
238
                t_order.setStatusDescription("Payment Pending");
239
                t_order.setCreated_timestamp(new Date().getTime());
240
                t_order.setTotal_amount(row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue());
241
                t_order.setSource(sourceId);
242
                orders.add(t_order);
243
                orderCountForRow++;
244
            }
245
            amount = new Double (row.getCell(1).getNumericCellValue() * row.getCell(AMOUNT_PER_ORDER_INDEX).getNumericCellValue()).longValue();
246
 
247
 
248
            txn.setOrders(orders);
249
            Client transaction_client = new TransactionClient().getClient();
250
            try {
251
            	transactionId =  String.valueOf(transaction_client.createTransaction(txn));
8182 amar.kumar 252
            	if(sourceDetail.getId()!= AMAZON_SOURCE_ID) {
253
	            	createPayment(user);
254
 
255
	            	in.shop2020.model.v1.order.Attribute orderAttribute = new in.shop2020.model.v1.order.Attribute();
256
	                orderAttribute.setName("tinNumber");
257
	                orderAttribute.setValue(sourceDetail.getTinNumber());
258
 
259
	                if(!sourceDetail.getTinNumber().equals("") && !(sourceDetail.getTinNumber() == null)) {
260
	                	transaction_client.setOrderAttributeForTransaction(Long.parseLong(transactionId), orderAttribute);
261
	                }
262
            	} else {
263
 
264
            	}
7410 amar.kumar 265
                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()));
266
                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()));
267
                logger.info("Successfully created transaction: " + transactionId + " for amount: " + amount);
268
 
8182 amar.kumar 269
            } catch (Exception e) {
7410 amar.kumar 270
                logger.error("Unable to establish connection to the transaction service", e);
271
                addActionError("Unable to establish connection to the transaction service");
272
                return "authsuccess";
273
    		}
274
        }
275
 
276
        checkForErrors();
277
        return "authsuccess";
278
    }
279
 
280
    private LineItem createLineItem(Double itemId) throws CatalogServiceException, TException {
281
    	LineItem lineItem = new LineItem();
282
    	CatalogService.Client catalogClient = new CatalogClient().getClient();
283
    	Item item = catalogClient.getItem(itemId.longValue());
284
 
285
    	lineItem.setProductGroup(item.getProductGroup());
286
        lineItem.setBrand(item.getBrand());
287
        lineItem.setModel_number(item.getModelNumber());
288
        lineItem.setModel_name(item.getModelName());
289
        lineItem.setExtra_info(item.getFeatureDescription());
290
        lineItem.setItem_id(item.getId());
291
        lineItem.setUnit_weight(item.getWeight());
292
        lineItem.setTotal_weight(item.getWeight());
293
        //lineItem.setDealText(item.getBestDealText());
294
        //lineItem.setTotal_price(lineItem.getUnit_price());
295
 
296
        if (item.getColor() == null || "NA".equals(item.getColor())) {
297
            lineItem.setColor("");
298
        } else {
299
            lineItem.setColor(item.getColor());
300
        }
301
    	return lineItem;
302
	}
303
 
304
    private void createPayment(User user) throws NumberFormatException, PaymentException, TException {
305
        List<Attribute> paymentAttributes = new ArrayList<Attribute>();
306
        paymentAttributes.add(new Attribute(PAY_METHOD, "4000"));
307
        paymentAttributes.add(new Attribute("sourceId", sourceId.toString()));
308
 
309
        in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
310
        long paymentId = client.createPayment(user.getUserId(), Double.valueOf(amount), RTGS_GATEWAY_ID, Long.valueOf(transactionId), false);
311
        client.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null, PaymentStatus.SUCCESS, null, paymentAttributes);
312
    }
313
 
314
	@Override
315
    public void setServletRequest(HttpServletRequest request) {
316
        this.request = request;
317
        this.session = request.getSession();
318
    }
319
 
320
    public String getErrorMsg(){
321
        return this.errorMsg;
322
    }
323
 
324
    private boolean checkForErrors(){
325
        Collection<String> actionErrors = getActionErrors();
326
        if(actionErrors != null && !actionErrors.isEmpty()){
327
            for (String str : actionErrors) {
328
                errorMsg += "<BR/>" + str;
329
            }
330
            if(rowId>1) {
331
            	errorMsg += "<BR/>" + "Error while processing rowNumber : " + rowId;
332
            }
333
            return true;
334
        }
335
        return false;
336
    }
337
 
338
	public File getOrderDataFile() {
339
		return orderDataFile;
340
	}
341
 
342
	public void setOrderDataFile(File orderDataFile) {
343
		this.orderDataFile = orderDataFile;
344
	}
345
 
346
	public String getOrderDataFileName() {
347
		return orderDataFileName;
348
	}
349
 
350
	public void setOrderDataFileName(String orderDataFileName) {
351
		this.orderDataFileName = orderDataFileName;
352
	}
353
 
354
	public Long getSourceId() {
355
		return sourceId;
356
	}
357
 
358
	public void setSourceId(Long sourceId) {
359
		this.sourceId = sourceId;
360
	}
361
 
362
	public Long getOrderType() {
363
		return orderType;
364
	}
365
 
366
	public void setOrderType(Long orderType) {
367
		this.orderType = orderType;
368
	}
369
 
370
	public Long getPickUpType() {
371
		return pickUpType;
372
	}
373
 
374
	public void setPickUpType(Long pickUpType) {
375
		this.pickUpType = pickUpType;
376
	}
377
 
378
}