Subversion Repositories SmartDukaan

Rev

Rev 7427 | Rev 7611 | 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
 
7435 anupam.sin 286
        order.setOrderType(OrderType.B2C);
287
 
7268 anupam.sin 288
        List<LineItem> lines = new ArrayList<LineItem>();
289
        lines.add(lineObj);
290
        order.setLineitems(lines);
7263 anupam.sin 291
        return order;
292
    }
293
 
294
    public LineItem createLineItem() {
295
        LineItem lineitem = new LineItem();
296
        Item item = null;
297
        try {
298
            CatalogClient ccl = new CatalogClient();
299
            item = ccl.getClient().getItem(product_id);
7323 anupam.sin 300
            sp = ccl.getClient().getStorePricing(product_id);
301
            lineitem.setDealText(sp.getBestDealText());
7427 anupam.sin 302
 
303
            ItemShippingInfo info = ccl.getClient().isActive(product_id);
304
            boolean isActive = info.isIsActive();
305
            boolean activeOnStore = ccl.getClient().getItem(product_id).isActiveOnStore();
306
 
307
            if(!isActive || !activeOnStore) {
308
                setErrorMsg("Unable to create order. Please try again.");
309
                return null;
310
            }
311
 
312
            if(price < sp.getAbsoluteMinPrice()) {
313
                setErrorMsg("You cannot sell below Rs." + sp.getAbsoluteMinPrice());
314
                return null;
315
            }
7263 anupam.sin 316
        } catch (Exception e) {
317
            log.error("Unable to get the item from catalog service, ItemId : " + product_id, e);
318
            setErrorMsg("Unable to create order. Please try again.");
319
            return null;
320
        }
321
        lineitem.setProductGroup(item.getProductGroup());
322
        lineitem.setBrand(item.getBrand());
323
        lineitem.setModel_number(item.getModelNumber());
324
        lineitem.setModel_name(item.getModelName());
325
        if(item.getColor() == null || item.getColor().isEmpty()) {
326
            lineitem.setColor("");
327
        } else {
328
            lineitem.setColor(item.getColor());
329
        }
330
        lineitem.setExtra_info(item.getFeatureDescription());
331
        lineitem.setItem_id(item.getId());
332
        lineitem.setQuantity(1.0);
333
        lineitem.setUnit_price(price);
334
        lineitem.setTotal_price(price);
335
        lineitem.setUnit_weight(item.getWeight());
336
        lineitem.setTotal_weight(item.getWeight());
7360 anupam.sin 337
        lineitem.setDealText(bestDealText);
7263 anupam.sin 338
 
339
        if(item.getWarrantyPeriod() > 0) {
340
            //Computing Manufacturer Warranty expiry date
341
            Calendar cal = Calendar.getInstance();
342
            cal.add(Calendar.MONTH, item.getWarrantyPeriod());
7268 anupam.sin 343
            cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
7263 anupam.sin 344
            lineitem.setWarrantry_expiry_timestamp(cal.getTimeInMillis());
345
        }
346
 
347
        return lineitem;
348
    }
349
 
350
    private static String generateNewPassword() {
351
        char[] buf = new char[LENGTH];
352
        for (int i = 0; i < buf.length; i++) {
353
            buf[i] = chars.charAt(random.nextInt(chars.length()));
354
        }
355
        return new String(buf);
356
    }
357
 
358
    private long createUserAndSendMail(String email) {
359
        User user = null;
360
        String password = null;
361
        try{
362
        UserClient ucl = new UserClient();
363
        user = ucl.getClient().getUserByEmail(email);
364
        if(user.getUserId() == -1) {
365
            user.setEmail(email);
366
            password = generateNewPassword();
367
            String encryptedPassword = password;
368
            user.setPassword(encryptedPassword);
369
            user.setCommunicationEmail(email);
370
            UserClient userContextServiceClient = new UserClient();
371
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
372
            user = userClient.createUser(user);
373
 
374
            List<String> toList = new ArrayList<String>();
375
            toList.add(email);
376
            HelperClient helperServiceClient = null;
377
            helperServiceClient = new HelperClient();
378
            in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
379
            Mail mail = new Mail();
380
            mail.setSubject("Saholic Registration successful");
381
            mail.setTo(toList);
382
            mail.setData("Your have successfully registered with Saholic.com. Your user name is: " + email + " and your password is: " +  password);
383
            client.sendMail(mail);
384
            }
385
        }catch (UserContextException ux){
386
            return -1;               
387
        } catch (TTransportException e) {
388
            return -1;
389
        } catch (TException e) {
390
            return -1;
391
        } catch (Exception e) {
392
            log.error("Unexpected error while mailing the new password");
393
            return -1;
394
        }
395
        return user.getUserId();
396
    }
7386 anupam.sin 397
 
398
    public List<String> getAllEdcBanks() {
399
        List<String> banks = new ArrayList<String>(); 
400
        try {
401
            TransactionClient tcl = new TransactionClient();
402
            banks = tcl.getClient().getAllEdcBanks();
403
        } catch (Exception e) {
404
            log.error("Unable to get banks for EDC", e);
405
        }
406
        return banks;
407
    }
7263 anupam.sin 408
 
7226 anupam.sin 409
    public String getLine1() {
410
        return line1;
411
    }
412
 
413
    public void setLine1(String line1) {
414
        this.line1 = line1;
415
    }
416
 
417
    public String getLine2() {
418
        return line2;
419
    }
420
 
421
    public void setLine2(String line2) {
422
        this.line2 = line2;
423
    }
424
 
425
    public String getCity() {
426
        return city;
427
    }
428
 
429
    public void setCity(String city) {
430
        this.city = city;
431
    }
432
 
433
    public String getState() {
434
        return state;
435
    }
436
 
437
    public void setState(String state) {
438
        this.state = state;
439
    }
440
 
441
    public String getPincode() {
442
        return pincode;
443
    }
444
 
445
    public void setPincode(String pincode) {
446
        this.pincode = pincode;
447
    }
448
 
7248 anupam.sin 449
    public String getName() {
450
        return name;
451
    }
452
 
453
    public void setName(String name) {
454
        this.name = name;
455
    }
456
 
457
    public String getPhone() {
458
        return phone;
459
    }
460
 
461
    public void setPhone(String phone) {
462
        this.phone = phone;
463
    }
464
 
7263 anupam.sin 465
    public void setProduct_id(Long product_id) {
466
        this.product_id = product_id;
467
    }
468
 
469
    public Long getProduct_id() {
470
        return product_id;
471
    }
472
 
473
    public String getEmail() {
474
        return email;
475
    }
476
 
477
    public void setEmail(String email) {
478
        this.email = email;
479
    }
480
 
481
    public void setErrorMsg(String errorMsg) {
482
        this.errorMsg = errorMsg;
483
    }
484
 
485
    public String getErrorMsg() {
486
        return errorMsg;
487
    }
488
 
489
    public double getPrice() {
490
        return price;
491
    }
492
 
493
    public void setPrice(double price) {
494
        this.price = price;
495
    }
7293 anupam.sin 496
 
497
    public List<Order> getOrders() {
498
        return orders;
499
    }
500
 
501
    public void setOrders(List<Order> orders) {
502
        this.orders = orders;
503
    }
504
 
505
    public Double getAdvanceAmount() {
506
        return advanceAmount;
507
    }
508
 
509
    public void setAdvanceAmount(Double advanceAmount) {
510
        this.advanceAmount = advanceAmount;
511
    }
512
 
513
    public void setDeliveryDate(String deliveryDate) {
514
        this.deliveryDate = deliveryDate;
515
    }
516
 
517
    public String getDeliveryDate() {
518
        return deliveryDate;
519
    }
520
 
7323 anupam.sin 521
    public String getProductName() {
522
        return productName;
523
    }
524
 
525
    public void setProductName(String productName) {
526
        this.productName = productName;
527
    }
528
 
529
    public String getBestDealText() {
530
        return bestDealText;
531
    }
532
 
533
    public void setBestDealText(String bestDealText) {
534
        this.bestDealText = bestDealText;
535
    }
536
 
537
 
538
    public String getImageSource() {
539
        return "/storewebsite/images/website/" + getCatalogItemId() + "/default.jpg";
540
    }
541
 
542
    public String getCatalogItemId() {
543
        return CatalogItemId;
544
    }
545
 
546
    public void setCatalogItemId(String catalogItemId) {
547
        CatalogItemId = catalogItemId;
548
    }
7343 anupam.sin 549
 
550
    public long getPaymentId() {
551
        return paymentId;
552
    }
553
 
554
    public void setPaymentId(long paymentId) {
555
        this.paymentId = paymentId;
556
    }
557
 
558
    public long getUserId() {
559
        return userId;
560
    }
561
 
562
    public void setUserId(long userId) {
563
        this.userId = userId;
564
    }
7386 anupam.sin 565
 
566
    public double getCashAmount() {
567
        return cashAmount;
568
    }
569
 
570
    public void setCashAmount(double cashAmount) {
571
        this.cashAmount = cashAmount;
572
    }
573
 
574
    public double getCardAmount() {
575
        return cardAmount;
576
    }
577
 
578
    public void setCardAmount(double cardAmount) {
579
        this.cardAmount = cardAmount;
580
    }
7399 anupam.sin 581
 
582
    public String getEdc() {
583
        return edc;
584
    }
585
 
586
    public void setEdc(String edc) {
587
        this.edc = edc;
588
    }
7423 anupam.sin 589
 
590
    public String getApprovalCode() {
591
        return approvalCode;
592
    }
593
 
594
    public void setApprovalCode(String approvalCode) {
595
        this.approvalCode = approvalCode;
596
    }
7226 anupam.sin 597
}