Subversion Repositories SmartDukaan

Rev

Rev 7268 | Rev 7323 | 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;
5
import java.util.Calendar;
7293 anupam.sin 6
import java.util.Date;
7263 anupam.sin 7
import java.util.List;
8
import java.util.Random;
9
 
10
import org.apache.thrift.TException;
11
import org.apache.thrift.transport.TTransportException;
12
 
7293 anupam.sin 13
import in.shop2020.logistics.PickUpType;
7263 anupam.sin 14
import in.shop2020.model.v1.catalog.Item;
15
import in.shop2020.model.v1.order.LineItem;
16
import in.shop2020.model.v1.order.Order;
7293 anupam.sin 17
import in.shop2020.model.v1.order.OrderSource;
7263 anupam.sin 18
import in.shop2020.model.v1.order.OrderStatus;
7293 anupam.sin 19
import in.shop2020.model.v1.order.OrderType;
7263 anupam.sin 20
import in.shop2020.model.v1.order.SourceDetail;
21
import in.shop2020.model.v1.order.Transaction;
22
import in.shop2020.model.v1.order.TransactionStatus;
23
import in.shop2020.model.v1.user.User;
24
import in.shop2020.model.v1.user.UserContextException;
7268 anupam.sin 25
import in.shop2020.payments.PaymentStatus;
7263 anupam.sin 26
import in.shop2020.thrift.clients.CatalogClient;
27
import in.shop2020.thrift.clients.HelperClient;
7268 anupam.sin 28
import in.shop2020.thrift.clients.PaymentClient;
7263 anupam.sin 29
import in.shop2020.thrift.clients.TransactionClient;
30
import in.shop2020.thrift.clients.UserClient;
31
import in.shop2020.utils.Mail;
32
 
33
import in.shop2020.serving.controllers.BaseController;
7293 anupam.sin 34
import in.shop2020.serving.utils.FormattingUtils;
7263 anupam.sin 35
 
7226 anupam.sin 36
public class PaymentDetailsController  extends BaseController {
37
 
7248 anupam.sin 38
    /**
39
     * 
40
     */
41
    private static final long serialVersionUID = 1L;
42
    private String name;
43
    private String phone;
7226 anupam.sin 44
    private String line1;
45
    private String line2;
46
    private String city;
47
    private String state;
48
    private String pincode;
7263 anupam.sin 49
    private Long product_id;
50
    private String email;
51
    private static int LENGTH = 10;
52
    private static final String chars = "abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
53
    private static final Random random = new Random();
54
    private String errorMsg = "";
55
    private double price;
7293 anupam.sin 56
    private List<Order> orders = new ArrayList<Order>();
57
    private Double advanceAmount;
58
    private String deliveryDate = "";
7226 anupam.sin 59
 
7293 anupam.sin 60
    private FormattingUtils formattingUtils = new FormattingUtils();
61
 
7248 anupam.sin 62
    public String index() {
63
        return INDEX;
64
    }
65
 
7226 anupam.sin 66
    public String create(){
67
        return index();
68
    }
7263 anupam.sin 69
 
70
    public String persistTransaction() {
71
 
72
        /**
73
         * 0.Create user
74
         * 1.Make a transaction object comprised of Order which in turn contains lineitem.
75
         * 2.Call create_transaction
76
         * 3.retrieve that order
77
         */
78
 
79
        Transaction txnObj = new Transaction();
80
 
81
        long tempUserId = -1;
7293 anupam.sin 82
        Long merchantPaymentId = 0l;
7226 anupam.sin 83
 
7263 anupam.sin 84
        if(email != null && !email.isEmpty()) {
85
            tempUserId = createUserAndSendMail(email);
86
        } else {
87
            try {
88
                TransactionClient tcl = new TransactionClient();
89
                //Source Id for store website is 2 and our normal website is 1
90
                SourceDetail detail = tcl.getClient().getSourceDetail(2);
91
 
92
                tempUserId = createUserAndSendMail(detail.getEmail());
93
            } catch(Exception e) {
94
                log.error("Unable to get default source", e);
95
            }
96
        }
97
 
98
        if(tempUserId == -1) {
99
            log.error("Unable to get a user, terminating the transaction");
100
            setErrorMsg("Unable to create a user for this order. Please try again.");
101
            return "error-result";
102
        }
103
 
104
        txnObj.setShoppingCartid(0);
105
        txnObj.setCustomer_id(tempUserId);
106
        txnObj.setCreatedOn(Calendar.getInstance().getTimeInMillis());
107
        txnObj.setTransactionStatus(TransactionStatus.INIT);
108
        txnObj.setStatusDescription("New Store Order");
109
        txnObj.setCoupon_code("");
110
        txnObj.setEmiSchemeId(0);
111
 
112
        if(createOrder(tempUserId) ==  null) {
113
            log.error("Unable to create transaction");
114
            setErrorMsg("Unable to create order. Please try again.");
115
            return "error-result";
116
        }
117
 
118
        orders.add(createOrder(tempUserId));
119
        txnObj.setOrders(orders);
120
        TransactionClient tcl;
7268 anupam.sin 121
        long txnId = 0;
7263 anupam.sin 122
        try {
123
            tcl = new TransactionClient();
7268 anupam.sin 124
            txnId = tcl.getClient().createTransaction(txnObj);
7263 anupam.sin 125
        } catch (Exception e) {
126
            log.error("Unable to create transaction", e);
127
            setErrorMsg("Unable to create order. Please try again.");
128
            return "error-result";
129
        }
7268 anupam.sin 130
 
7293 anupam.sin 131
        PaymentClient pcl;
7268 anupam.sin 132
        try {
7293 anupam.sin 133
            pcl = new PaymentClient();
134
            merchantPaymentId = pcl.getClient().createPayment(tempUserId, price, 10, txnId, true);
135
            //Update payment status as authorized
136
            pcl.getClient().updatePaymentDetails(merchantPaymentId, "", "", "0", "", "", "", "", "", PaymentStatus.SUCCESS, "", null);
137
            txnId = pcl.getClient().getPayment(merchantPaymentId).getMerchantTxnId();
7268 anupam.sin 138
        } catch(Exception e) {
139
            log.error("Unable to create payment for this order");
140
            setErrorMsg("Unable to create order. Please try again.");
141
            return "error-result";
142
        }
7293 anupam.sin 143
 
144
        try {
145
            tcl = new TransactionClient();
146
            boolean status = tcl.getClient().changeTransactionStatus(txnId, TransactionStatus.COD_IN_PROCESS, "Payment authorized", PickUpType.COURIER.getValue(), OrderType.B2C, OrderSource.STORE);
147
            if(!status) {
148
                log.error("Unable to update transaction");
149
                setErrorMsg("Unable to create order. Please try again.");
150
                return "error-result";
151
            }
152
        } catch (Exception e) {
153
            log.error("Unable to create transaction", e);
154
            setErrorMsg("Unable to create order. Please try again.");
155
            return "error-result";
156
        }
157
 
158
 
159
        try {
160
            pcl = new PaymentClient();
161
 
162
            orders = tcl.getClient().getOrdersForTransaction(txnId, tempUserId);
163
        } catch (Exception e) {
164
            log.error("Unable to retrieve orders");
165
            setErrorMsg("Order was created but due to some error we could not display it. Please try again.");
166
        }
167
 
168
        return "order-success";
7263 anupam.sin 169
    }
170
 
171
    public Order createOrder(long userId) {
172
        LineItem lineObj = createLineItem();
173
        if (lineObj == null) {
174
            return null;
175
        }
176
        Order order = new Order();
177
        User user = new User();
178
        try {
179
            UserClient ucl = new UserClient();
180
            user = ucl.getClient().getUserById(userId);
181
        } catch (Exception e) {
182
            log.error("Unable to get user for id " + userId, e);
183
            return null;
184
        }
185
        order.setCustomer_id(user.getUserId());
186
        order.setCustomer_email(user.getEmail());
187
        order.setCustomer_name(name);
188
        order.setCustomer_address1(line1);
189
        order.setCustomer_address2(line2);
190
        order.setCustomer_city(city);
191
        order.setCustomer_state(state);
192
        order.setCustomer_pincode(pincode);
193
        order.setCustomer_mobilenumber(phone);
194
 
195
        order.setTotal_amount(price);
196
        order.setStatus(OrderStatus.SUBMITTED_FOR_PROCESSING);
197
        order.setStatusDescription("In process");
198
        order.setCreated_timestamp(Calendar.getInstance().getTimeInMillis());
7268 anupam.sin 199
        order.setTotal_weight(lineObj.getTotal_weight());
7263 anupam.sin 200
 
7293 anupam.sin 201
        order.setSource(2);
202
        order.setStoreId(1);
203
        order.setAdvanceAmount(advanceAmount);
204
 
7268 anupam.sin 205
        List<LineItem> lines = new ArrayList<LineItem>();
206
        lines.add(lineObj);
207
        order.setLineitems(lines);
7263 anupam.sin 208
        return order;
209
    }
210
 
211
    public LineItem createLineItem() {
212
        LineItem lineitem = new LineItem();
213
        Item item = null;
214
        try {
215
            CatalogClient ccl = new CatalogClient();
216
            item = ccl.getClient().getItem(product_id);
217
        } catch (Exception e) {
218
            log.error("Unable to get the item from catalog service, ItemId : " + product_id, e);
219
            setErrorMsg("Unable to create order. Please try again.");
220
            return null;
221
        }
222
        lineitem.setProductGroup(item.getProductGroup());
223
        lineitem.setBrand(item.getBrand());
224
        lineitem.setModel_number(item.getModelNumber());
225
        lineitem.setModel_name(item.getModelName());
226
        if(item.getColor() == null || item.getColor().isEmpty()) {
227
            lineitem.setColor("");
228
        } else {
229
            lineitem.setColor(item.getColor());
230
        }
231
        lineitem.setExtra_info(item.getFeatureDescription());
232
        lineitem.setItem_id(item.getId());
233
        lineitem.setQuantity(1.0);
234
        lineitem.setUnit_price(price);
235
        lineitem.setTotal_price(price);
236
        lineitem.setUnit_weight(item.getWeight());
237
        lineitem.setTotal_weight(item.getWeight());
238
        lineitem.setDealText(item.getBestDealText());
239
 
240
        if(item.getWarrantyPeriod() > 0) {
241
            //Computing Manufacturer Warranty expiry date
242
            Calendar cal = Calendar.getInstance();
243
            cal.add(Calendar.MONTH, item.getWarrantyPeriod());
7268 anupam.sin 244
            cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
7263 anupam.sin 245
            lineitem.setWarrantry_expiry_timestamp(cal.getTimeInMillis());
246
        }
247
 
248
        return lineitem;
249
    }
250
 
251
    private static String generateNewPassword() {
252
        char[] buf = new char[LENGTH];
253
        for (int i = 0; i < buf.length; i++) {
254
            buf[i] = chars.charAt(random.nextInt(chars.length()));
255
        }
256
        return new String(buf);
257
    }
258
 
259
    private long createUserAndSendMail(String email) {
260
        User user = null;
261
        String password = null;
262
        try{
263
        UserClient ucl = new UserClient();
264
        user = ucl.getClient().getUserByEmail(email);
265
        if(user.getUserId() == -1) {
266
            user.setEmail(email);
267
            password = generateNewPassword();
268
            String encryptedPassword = password;
269
            user.setPassword(encryptedPassword);
270
            user.setCommunicationEmail(email);
271
            UserClient userContextServiceClient = new UserClient();
272
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
273
            user = userClient.createUser(user);
274
 
275
            List<String> toList = new ArrayList<String>();
276
            toList.add(email);
277
            HelperClient helperServiceClient = null;
278
            helperServiceClient = new HelperClient();
279
            in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
280
            Mail mail = new Mail();
281
            mail.setSubject("Saholic Registration successful");
282
            mail.setTo(toList);
283
            mail.setData("Your have successfully registered with Saholic.com. Your user name is: " + email + " and your password is: " +  password);
284
            client.sendMail(mail);
285
            }
286
        }catch (UserContextException ux){
287
            return -1;               
288
        } catch (TTransportException e) {
289
            return -1;
290
        } catch (TException e) {
291
            return -1;
292
        } catch (Exception e) {
293
            log.error("Unexpected error while mailing the new password");
294
            return -1;
295
        }
296
        return user.getUserId();
297
    }
298
 
7226 anupam.sin 299
    public String getLine1() {
300
        return line1;
301
    }
302
 
303
    public void setLine1(String line1) {
304
        this.line1 = line1;
305
    }
306
 
307
    public String getLine2() {
308
        return line2;
309
    }
310
 
311
    public void setLine2(String line2) {
312
        this.line2 = line2;
313
    }
314
 
315
    public String getCity() {
316
        return city;
317
    }
318
 
319
    public void setCity(String city) {
320
        this.city = city;
321
    }
322
 
323
    public String getState() {
324
        return state;
325
    }
326
 
327
    public void setState(String state) {
328
        this.state = state;
329
    }
330
 
331
    public String getPincode() {
332
        return pincode;
333
    }
334
 
335
    public void setPincode(String pincode) {
336
        this.pincode = pincode;
337
    }
338
 
7248 anupam.sin 339
    public String getName() {
340
        return name;
341
    }
342
 
343
    public void setName(String name) {
344
        this.name = name;
345
    }
346
 
347
    public String getPhone() {
348
        return phone;
349
    }
350
 
351
    public void setPhone(String phone) {
352
        this.phone = phone;
353
    }
354
 
7263 anupam.sin 355
    public void setProduct_id(Long product_id) {
356
        this.product_id = product_id;
357
    }
358
 
359
    public Long getProduct_id() {
360
        return product_id;
361
    }
362
 
363
    public String getEmail() {
364
        return email;
365
    }
366
 
367
    public void setEmail(String email) {
368
        this.email = email;
369
    }
370
 
371
    public void setErrorMsg(String errorMsg) {
372
        this.errorMsg = errorMsg;
373
    }
374
 
375
    public String getErrorMsg() {
376
        return errorMsg;
377
    }
378
 
379
    public double getPrice() {
380
        return price;
381
    }
382
 
383
    public void setPrice(double price) {
384
        this.price = price;
385
    }
7293 anupam.sin 386
 
387
    public List<Order> getOrders() {
388
        return orders;
389
    }
390
 
391
    public void setOrders(List<Order> orders) {
392
        this.orders = orders;
393
    }
394
 
395
    public Double getAdvanceAmount() {
396
        return advanceAmount;
397
    }
398
 
399
    public void setAdvanceAmount(Double advanceAmount) {
400
        this.advanceAmount = advanceAmount;
401
    }
402
 
403
    public void setDeliveryDate(String deliveryDate) {
404
        this.deliveryDate = deliveryDate;
405
    }
406
 
407
    public String getDeliveryDate() {
408
        return deliveryDate;
409
    }
410
 
411
    public String formatPrice(double price)    {
412
        return formattingUtils.formatPrice(price);
413
    }
414
 
415
    public static String formatDate(long timestamp){
416
        SimpleDateFormat dateformat = new SimpleDateFormat("h:m a, dd MMMM yyyy");
417
        return dateformat.format(new Date(timestamp));  
418
    }
7226 anupam.sin 419
}