Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
7226 anupam.sin 1
package in.shop2020.serving.controllers;
2
 
7293 anupam.sin 3
import java.text.SimpleDateFormat;
7263 anupam.sin 4
import java.util.ArrayList;
7386 anupam.sin 5
import java.util.Arrays;
7263 anupam.sin 6
import java.util.Calendar;
7293 anupam.sin 7
import java.util.Date;
7263 anupam.sin 8
import java.util.List;
9
import java.util.Random;
10
 
7343 anupam.sin 11
import org.apache.struts2.convention.annotation.Result;
12
import org.apache.struts2.convention.annotation.Results;
7263 anupam.sin 13
import org.apache.thrift.TException;
14
import org.apache.thrift.transport.TTransportException;
15
 
7427 anupam.sin 16
import in.shop2020.logistics.DeliveryType;
17
import in.shop2020.logistics.LogisticsInfo;
7293 anupam.sin 18
import in.shop2020.logistics.PickUpType;
7427 anupam.sin 19
import in.shop2020.logistics.LogisticsService.Client;
7263 anupam.sin 20
import in.shop2020.model.v1.catalog.Item;
7427 anupam.sin 21
import in.shop2020.model.v1.catalog.ItemShippingInfo;
7323 anupam.sin 22
import in.shop2020.model.v1.catalog.StorePricing;
7386 anupam.sin 23
import in.shop2020.model.v1.order.HotspotStore;
7263 anupam.sin 24
import in.shop2020.model.v1.order.LineItem;
25
import in.shop2020.model.v1.order.Order;
7293 anupam.sin 26
import in.shop2020.model.v1.order.OrderSource;
7263 anupam.sin 27
import in.shop2020.model.v1.order.OrderStatus;
7293 anupam.sin 28
import in.shop2020.model.v1.order.OrderType;
7263 anupam.sin 29
import in.shop2020.model.v1.order.SourceDetail;
7386 anupam.sin 30
import in.shop2020.model.v1.order.StoreOrderDetail;
31
import in.shop2020.model.v1.order.StorePaymentStatus;
7263 anupam.sin 32
import in.shop2020.model.v1.order.Transaction;
33
import in.shop2020.model.v1.order.TransactionStatus;
34
import in.shop2020.model.v1.user.User;
35
import in.shop2020.model.v1.user.UserContextException;
7268 anupam.sin 36
import in.shop2020.payments.PaymentStatus;
7263 anupam.sin 37
import in.shop2020.thrift.clients.CatalogClient;
38
import in.shop2020.thrift.clients.HelperClient;
7427 anupam.sin 39
import in.shop2020.thrift.clients.LogisticsClient;
7268 anupam.sin 40
import in.shop2020.thrift.clients.PaymentClient;
7263 anupam.sin 41
import in.shop2020.thrift.clients.TransactionClient;
42
import in.shop2020.thrift.clients.UserClient;
43
import in.shop2020.utils.Mail;
44
 
45
import in.shop2020.serving.controllers.BaseController;
7293 anupam.sin 46
import in.shop2020.serving.utils.FormattingUtils;
7263 anupam.sin 47
 
7343 anupam.sin 48
@Results({
49
    @Result(name="order-success-redirect", type="redirectAction", params = {"actionName", "order-success", "paymentId", "${paymentId}", "userId", "${userId}"})
50
})
51
 
7226 anupam.sin 52
public class PaymentDetailsController  extends BaseController {
53
 
7248 anupam.sin 54
    /**
55
     * 
56
     */
57
    private static final long serialVersionUID = 1L;
58
    private String name;
59
    private String phone;
7226 anupam.sin 60
    private String line1;
61
    private String line2;
62
    private String city;
63
    private String state;
64
    private String pincode;
7263 anupam.sin 65
    private Long product_id;
66
    private String email;
67
    private static int LENGTH = 10;
68
    private static final String chars = "abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
69
    private static final Random random = new Random();
70
    private String errorMsg = "";
71
    private double price;
7293 anupam.sin 72
    private List<Order> orders = new ArrayList<Order>();
73
    private Double advanceAmount;
74
    private String deliveryDate = "";
7323 anupam.sin 75
    private String productName = "";
76
    private String bestDealText = "";
77
    private String CatalogItemId = "";
7343 anupam.sin 78
    private long paymentId;
79
    private long userId;
7226 anupam.sin 80
 
7343 anupam.sin 81
 
7323 anupam.sin 82
    private StorePricing sp;
7386 anupam.sin 83
    private double cardAmount;
84
    private double cashAmount;
7399 anupam.sin 85
    private String edc;
7423 anupam.sin 86
    private String approvalCode;
7293 anupam.sin 87
 
7248 anupam.sin 88
    public String index() {
7386 anupam.sin 89
        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
90
        if(loginStatus == null || !loginStatus.equals("TRUE")){
91
            return "authfail";
92
        }
93
        storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));
94
        if(!hotspotStores.containsKey(storeId)){
95
            try{
96
                HotspotStore hotSpotStore = (new TransactionClient()).getClient().getHotspotStore(storeId, "");
97
                hotspotStores.put(storeId, hotSpotStore);
98
            } catch (Exception e) {
99
                log.error("Unable to get store", e);
100
            }
101
        }
102
 
7248 anupam.sin 103
        return INDEX;
104
    }
105
 
7226 anupam.sin 106
    public String create(){
107
        return index();
108
    }
7263 anupam.sin 109
 
110
    public String persistTransaction() {
7427 anupam.sin 111
        if(advanceAmount > price) {
112
            setErrorMsg("Advance amount was greater than Total Price.");
113
            return "error-result";
114
        }
115
 
116
        if(cashAmount + cardAmount != advanceAmount) {
117
            setErrorMsg("Sum of cash and card amounts was not equal to total Price.");
118
            return "error-result";
119
        }
120
 
121
        if(cardAmount > 0 && approvalCode.equals("")) {
122
            setErrorMsg("Approval code cannot be empty.");
123
            return "error-result";
124
        }
125
 
126
        validateAddress();
127
 
7263 anupam.sin 128
        Transaction txnObj = new Transaction();
7386 anupam.sin 129
        StoreOrderDetail storeOrderDetail = new StoreOrderDetail();
7263 anupam.sin 130
 
131
        if(email != null && !email.isEmpty()) {
7343 anupam.sin 132
            userId = createUserAndSendMail(email);
7263 anupam.sin 133
        } else {
7427 anupam.sin 134
            log.error("Email is null, terminating the transaction");
135
            setErrorMsg("Invalid email Id. Please try again.");
136
            return "error-result";
7263 anupam.sin 137
        }
138
 
7427 anupam.sin 139
        if(userId == -1 || userId == 0) {
7263 anupam.sin 140
            log.error("Unable to get a user, terminating the transaction");
141
            setErrorMsg("Unable to create a user for this order. Please try again.");
142
            return "error-result";
143
        }
144
 
145
        txnObj.setShoppingCartid(0);
7343 anupam.sin 146
        txnObj.setCustomer_id(userId);
7263 anupam.sin 147
        txnObj.setCreatedOn(Calendar.getInstance().getTimeInMillis());
148
        txnObj.setTransactionStatus(TransactionStatus.INIT);
149
        txnObj.setStatusDescription("New Store Order");
150
        txnObj.setCoupon_code("");
151
        txnObj.setEmiSchemeId(0);
152
 
7343 anupam.sin 153
        Order order = createOrder(userId);
7323 anupam.sin 154
 
155
        if(order ==  null) {
7263 anupam.sin 156
            log.error("Unable to create transaction");
157
            setErrorMsg("Unable to create order. Please try again.");
158
            return "error-result";
159
        }
160
 
7323 anupam.sin 161
        orders.add(order);
7263 anupam.sin 162
        txnObj.setOrders(orders);
7386 anupam.sin 163
 
7263 anupam.sin 164
        TransactionClient tcl;
7268 anupam.sin 165
        long txnId = 0;
7263 anupam.sin 166
        try {
167
            tcl = new TransactionClient();
7268 anupam.sin 168
            txnId = tcl.getClient().createTransaction(txnObj);
7386 anupam.sin 169
 
170
            storeOrderDetail.setAdvanceAmount(advanceAmount);
171
            storeOrderDetail.setCardAmount(cardAmount);
172
            storeOrderDetail.setCashAmount(cashAmount);
173
            storeOrderDetail.setOrderId(txnId);
7399 anupam.sin 174
            storeOrderDetail.setStoreId(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")));
7386 anupam.sin 175
            if(advanceAmount == price) {
176
                storeOrderDetail.setPayStatus(StorePaymentStatus.FULL_PAY_RECEIVED);
177
            } else {
178
                storeOrderDetail.setPayStatus(StorePaymentStatus.ADV_RECEIVED);
179
            }
7399 anupam.sin 180
            if(cardAmount > 0) {
181
                storeOrderDetail.setEdcBank(edc);
182
            }
183
            storeOrderDetail.setCardRefundAmount(0);
184
            storeOrderDetail.setCashRefundAmount(0);
7423 anupam.sin 185
            storeOrderDetail.setApprovalCode(approvalCode);
7386 anupam.sin 186
 
187
            boolean saveSuccess = tcl.getClient().saveStoreOrderDetail(storeOrderDetail);
188
            if(!saveSuccess) {
189
                setErrorMsg("Unable to create order. Please try again.");
190
                return "error-result";
191
            }
192
 
7263 anupam.sin 193
        } catch (Exception e) {
194
            log.error("Unable to create transaction", e);
195
            setErrorMsg("Unable to create order. Please try again.");
196
            return "error-result";
197
        }
7268 anupam.sin 198
 
7293 anupam.sin 199
        PaymentClient pcl;
7268 anupam.sin 200
        try {
7293 anupam.sin 201
            pcl = new PaymentClient();
7343 anupam.sin 202
            paymentId = pcl.getClient().createPayment(userId, price, 10, txnId, true);
7293 anupam.sin 203
            //Update payment status as authorized
7343 anupam.sin 204
            pcl.getClient().updatePaymentDetails(paymentId, "", "", "0", "", "", "", "", "", PaymentStatus.SUCCESS, "", null);
205
            txnId = pcl.getClient().getPayment(paymentId).getMerchantTxnId();
7268 anupam.sin 206
        } catch(Exception e) {
207
            log.error("Unable to create payment for this order");
208
            setErrorMsg("Unable to create order. Please try again.");
209
            return "error-result";
210
        }
7293 anupam.sin 211
 
212
        try {
7323 anupam.sin 213
            TransactionStatus txnStatus = TransactionStatus.COD_IN_PROCESS;
214
            if(advanceAmount >= price) {
215
                txnStatus = TransactionStatus.AUTHORIZED;
216
            }
217
 
7293 anupam.sin 218
            tcl = new TransactionClient();
7323 anupam.sin 219
            boolean status = tcl.getClient().changeTransactionStatus(txnId, txnStatus, "Payment authorized", PickUpType.COURIER.getValue(), OrderType.B2C, OrderSource.STORE);
7293 anupam.sin 220
            if(!status) {
221
                log.error("Unable to update transaction");
222
                setErrorMsg("Unable to create order. Please try again.");
223
                return "error-result";
224
            }
225
        } catch (Exception e) {
226
            log.error("Unable to create transaction", e);
227
            setErrorMsg("Unable to create order. Please try again.");
228
            return "error-result";
229
        }
230
 
7426 anupam.sin 231
        try {
232
 
233
            tcl = new TransactionClient();
234
            tcl.getClient().enqueueTransactionInfoEmail(txnId);
235
        } catch (Exception e) {
236
            log.error("Unable to send email", e);
237
        }
238
 
7343 anupam.sin 239
        return "order-success-redirect";
7263 anupam.sin 240
    }
241
 
7427 anupam.sin 242
    String validateAddress() {
243
        if(name.equals("") || line1.equals("") || city.equals("") || state.equals("") || pincode.equals("") || phone.equals("")) {
244
            setErrorMsg("Address was invalid");
245
            return "error-result";
246
        }
247
        return "";
248
    }
249
 
7263 anupam.sin 250
    public Order createOrder(long userId) {
251
        LineItem lineObj = createLineItem();
252
        if (lineObj == null) {
253
            return null;
254
        }
255
        Order order = new Order();
256
        User user = new User();
257
        try {
258
            UserClient ucl = new UserClient();
259
            user = ucl.getClient().getUserById(userId);
260
        } catch (Exception e) {
261
            log.error("Unable to get user for id " + userId, e);
262
            return null;
263
        }
264
        order.setCustomer_id(user.getUserId());
265
        order.setCustomer_email(user.getEmail());
266
        order.setCustomer_name(name);
267
        order.setCustomer_address1(line1);
268
        order.setCustomer_address2(line2);
269
        order.setCustomer_city(city);
270
        order.setCustomer_state(state);
271
        order.setCustomer_pincode(pincode);
272
        order.setCustomer_mobilenumber(phone);
273
 
274
        order.setTotal_amount(price);
7427 anupam.sin 275
        order.setStatus(OrderStatus.PAYMENT_PENDING);
276
        order.setStatusDescription("Order Incomplete");
7263 anupam.sin 277
        order.setCreated_timestamp(Calendar.getInstance().getTimeInMillis());
7268 anupam.sin 278
        order.setTotal_weight(lineObj.getTotal_weight());
7263 anupam.sin 279
 
7293 anupam.sin 280
        order.setSource(2);
7423 anupam.sin 281
        order.setStoreId(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")));
7323 anupam.sin 282
 
7293 anupam.sin 283
        order.setAdvanceAmount(advanceAmount);
7323 anupam.sin 284
        order.setFreebieItemId(sp.getFreebieItemId());
7293 anupam.sin 285
 
7268 anupam.sin 286
        List<LineItem> lines = new ArrayList<LineItem>();
287
        lines.add(lineObj);
288
        order.setLineitems(lines);
7263 anupam.sin 289
        return order;
290
    }
291
 
292
    public LineItem createLineItem() {
293
        LineItem lineitem = new LineItem();
294
        Item item = null;
295
        try {
296
            CatalogClient ccl = new CatalogClient();
297
            item = ccl.getClient().getItem(product_id);
7323 anupam.sin 298
            sp = ccl.getClient().getStorePricing(product_id);
299
            lineitem.setDealText(sp.getBestDealText());
7427 anupam.sin 300
 
301
            ItemShippingInfo info = ccl.getClient().isActive(product_id);
302
            boolean isActive = info.isIsActive();
303
            boolean activeOnStore = ccl.getClient().getItem(product_id).isActiveOnStore();
304
 
305
            if(!isActive || !activeOnStore) {
306
                setErrorMsg("Unable to create order. Please try again.");
307
                return null;
308
            }
309
 
310
            if(price < sp.getAbsoluteMinPrice()) {
311
                setErrorMsg("You cannot sell below Rs." + sp.getAbsoluteMinPrice());
312
                return null;
313
            }
7263 anupam.sin 314
        } catch (Exception e) {
315
            log.error("Unable to get the item from catalog service, ItemId : " + product_id, e);
316
            setErrorMsg("Unable to create order. Please try again.");
317
            return null;
318
        }
319
        lineitem.setProductGroup(item.getProductGroup());
320
        lineitem.setBrand(item.getBrand());
321
        lineitem.setModel_number(item.getModelNumber());
322
        lineitem.setModel_name(item.getModelName());
323
        if(item.getColor() == null || item.getColor().isEmpty()) {
324
            lineitem.setColor("");
325
        } else {
326
            lineitem.setColor(item.getColor());
327
        }
328
        lineitem.setExtra_info(item.getFeatureDescription());
329
        lineitem.setItem_id(item.getId());
330
        lineitem.setQuantity(1.0);
331
        lineitem.setUnit_price(price);
332
        lineitem.setTotal_price(price);
333
        lineitem.setUnit_weight(item.getWeight());
334
        lineitem.setTotal_weight(item.getWeight());
7360 anupam.sin 335
        lineitem.setDealText(bestDealText);
7263 anupam.sin 336
 
337
        if(item.getWarrantyPeriod() > 0) {
338
            //Computing Manufacturer Warranty expiry date
339
            Calendar cal = Calendar.getInstance();
340
            cal.add(Calendar.MONTH, item.getWarrantyPeriod());
7268 anupam.sin 341
            cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
7263 anupam.sin 342
            lineitem.setWarrantry_expiry_timestamp(cal.getTimeInMillis());
343
        }
344
 
345
        return lineitem;
346
    }
347
 
348
    private static String generateNewPassword() {
349
        char[] buf = new char[LENGTH];
350
        for (int i = 0; i < buf.length; i++) {
351
            buf[i] = chars.charAt(random.nextInt(chars.length()));
352
        }
353
        return new String(buf);
354
    }
355
 
356
    private long createUserAndSendMail(String email) {
357
        User user = null;
358
        String password = null;
359
        try{
360
        UserClient ucl = new UserClient();
361
        user = ucl.getClient().getUserByEmail(email);
362
        if(user.getUserId() == -1) {
363
            user.setEmail(email);
364
            password = generateNewPassword();
365
            String encryptedPassword = password;
366
            user.setPassword(encryptedPassword);
367
            user.setCommunicationEmail(email);
368
            UserClient userContextServiceClient = new UserClient();
369
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
370
            user = userClient.createUser(user);
371
 
372
            List<String> toList = new ArrayList<String>();
373
            toList.add(email);
374
            HelperClient helperServiceClient = null;
375
            helperServiceClient = new HelperClient();
376
            in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
377
            Mail mail = new Mail();
378
            mail.setSubject("Saholic Registration successful");
379
            mail.setTo(toList);
380
            mail.setData("Your have successfully registered with Saholic.com. Your user name is: " + email + " and your password is: " +  password);
381
            client.sendMail(mail);
382
            }
383
        }catch (UserContextException ux){
384
            return -1;               
385
        } catch (TTransportException e) {
386
            return -1;
387
        } catch (TException e) {
388
            return -1;
389
        } catch (Exception e) {
390
            log.error("Unexpected error while mailing the new password");
391
            return -1;
392
        }
393
        return user.getUserId();
394
    }
7386 anupam.sin 395
 
396
    public List<String> getAllEdcBanks() {
397
        List<String> banks = new ArrayList<String>(); 
398
        try {
399
            TransactionClient tcl = new TransactionClient();
400
            banks = tcl.getClient().getAllEdcBanks();
401
        } catch (Exception e) {
402
            log.error("Unable to get banks for EDC", e);
403
        }
404
        return banks;
405
    }
7263 anupam.sin 406
 
7226 anupam.sin 407
    public String getLine1() {
408
        return line1;
409
    }
410
 
411
    public void setLine1(String line1) {
412
        this.line1 = line1;
413
    }
414
 
415
    public String getLine2() {
416
        return line2;
417
    }
418
 
419
    public void setLine2(String line2) {
420
        this.line2 = line2;
421
    }
422
 
423
    public String getCity() {
424
        return city;
425
    }
426
 
427
    public void setCity(String city) {
428
        this.city = city;
429
    }
430
 
431
    public String getState() {
432
        return state;
433
    }
434
 
435
    public void setState(String state) {
436
        this.state = state;
437
    }
438
 
439
    public String getPincode() {
440
        return pincode;
441
    }
442
 
443
    public void setPincode(String pincode) {
444
        this.pincode = pincode;
445
    }
446
 
7248 anupam.sin 447
    public String getName() {
448
        return name;
449
    }
450
 
451
    public void setName(String name) {
452
        this.name = name;
453
    }
454
 
455
    public String getPhone() {
456
        return phone;
457
    }
458
 
459
    public void setPhone(String phone) {
460
        this.phone = phone;
461
    }
462
 
7263 anupam.sin 463
    public void setProduct_id(Long product_id) {
464
        this.product_id = product_id;
465
    }
466
 
467
    public Long getProduct_id() {
468
        return product_id;
469
    }
470
 
471
    public String getEmail() {
472
        return email;
473
    }
474
 
475
    public void setEmail(String email) {
476
        this.email = email;
477
    }
478
 
479
    public void setErrorMsg(String errorMsg) {
480
        this.errorMsg = errorMsg;
481
    }
482
 
483
    public String getErrorMsg() {
484
        return errorMsg;
485
    }
486
 
487
    public double getPrice() {
488
        return price;
489
    }
490
 
491
    public void setPrice(double price) {
492
        this.price = price;
493
    }
7293 anupam.sin 494
 
495
    public List<Order> getOrders() {
496
        return orders;
497
    }
498
 
499
    public void setOrders(List<Order> orders) {
500
        this.orders = orders;
501
    }
502
 
503
    public Double getAdvanceAmount() {
504
        return advanceAmount;
505
    }
506
 
507
    public void setAdvanceAmount(Double advanceAmount) {
508
        this.advanceAmount = advanceAmount;
509
    }
510
 
511
    public void setDeliveryDate(String deliveryDate) {
512
        this.deliveryDate = deliveryDate;
513
    }
514
 
515
    public String getDeliveryDate() {
516
        return deliveryDate;
517
    }
518
 
7323 anupam.sin 519
    public String getProductName() {
520
        return productName;
521
    }
522
 
523
    public void setProductName(String productName) {
524
        this.productName = productName;
525
    }
526
 
527
    public String getBestDealText() {
528
        return bestDealText;
529
    }
530
 
531
    public void setBestDealText(String bestDealText) {
532
        this.bestDealText = bestDealText;
533
    }
534
 
535
 
536
    public String getImageSource() {
537
        return "/storewebsite/images/website/" + getCatalogItemId() + "/default.jpg";
538
    }
539
 
540
    public String getCatalogItemId() {
541
        return CatalogItemId;
542
    }
543
 
544
    public void setCatalogItemId(String catalogItemId) {
545
        CatalogItemId = catalogItemId;
546
    }
7343 anupam.sin 547
 
548
    public long getPaymentId() {
549
        return paymentId;
550
    }
551
 
552
    public void setPaymentId(long paymentId) {
553
        this.paymentId = paymentId;
554
    }
555
 
556
    public long getUserId() {
557
        return userId;
558
    }
559
 
560
    public void setUserId(long userId) {
561
        this.userId = userId;
562
    }
7386 anupam.sin 563
 
564
    public double getCashAmount() {
565
        return cashAmount;
566
    }
567
 
568
    public void setCashAmount(double cashAmount) {
569
        this.cashAmount = cashAmount;
570
    }
571
 
572
    public double getCardAmount() {
573
        return cardAmount;
574
    }
575
 
576
    public void setCardAmount(double cardAmount) {
577
        this.cardAmount = cardAmount;
578
    }
7399 anupam.sin 579
 
580
    public String getEdc() {
581
        return edc;
582
    }
583
 
584
    public void setEdc(String edc) {
585
        this.edc = edc;
586
    }
7423 anupam.sin 587
 
588
    public String getApprovalCode() {
589
        return approvalCode;
590
    }
591
 
592
    public void setApprovalCode(String approvalCode) {
593
        this.approvalCode = approvalCode;
594
    }
7226 anupam.sin 595
}