Subversion Repositories SmartDukaan

Rev

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