Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
1905 chandransh 1
package in.shop2020.serving.services;
2
 
3561 rajveer 3
import in.shop2020.model.v1.catalog.Item;
4
import in.shop2020.model.v1.catalog.InventoryService.Client;
1905 chandransh 5
import in.shop2020.model.v1.order.LineItem;
6
import in.shop2020.model.v1.order.Order;
7
import in.shop2020.model.v1.order.Transaction;
8
import in.shop2020.model.v1.order.TransactionServiceException;
9
import in.shop2020.model.v1.order.TransactionStatus;
10
import in.shop2020.model.v1.user.Cart;
11
import in.shop2020.model.v1.user.Line;
1981 varun.gupt 12
import in.shop2020.model.v1.user.PromotionException;
1905 chandransh 13
import in.shop2020.model.v1.user.ShoppingCartException;
2137 chandransh 14
import in.shop2020.payments.Payment;
1905 chandransh 15
import in.shop2020.payments.PaymentException;
3561 rajveer 16
import in.shop2020.thrift.clients.CatalogClient;
3126 rajveer 17
import in.shop2020.thrift.clients.PaymentClient;
18
import in.shop2020.thrift.clients.PromotionClient;
19
import in.shop2020.thrift.clients.TransactionClient;
20
import in.shop2020.thrift.clients.UserClient;
1905 chandransh 21
 
22
import java.util.HashMap;
23
import java.util.List;
24
import java.util.Map;
25
 
26
import org.apache.log4j.Logger;
27
import org.apache.thrift.TException;
28
 
29
/**
30
 * This class has methods to be used to process non-gateway-specific aspects of
31
 * payments and transactions.
32
 * 
33
 * @author Chandranshu
34
 * 
35
 */
36
public class CommonPaymentService {
37
 
38
	private static final boolean PAYMENT_NOT_CREATED = false;
39
 
40
	private static Logger log = Logger.getLogger(Class.class);
41
 
42
	private long paymentId;
43
	private double amount;
44
 
45
	public long getPaymentId() {
46
		return paymentId;
47
	}
48
 
49
	public double getAmount() {
50
		return amount;
51
	}
52
 
53
	/**
54
	 * Creates a payment for the given cart of the given user for the given
55
	 * transaction. Stores the id of the newly created payment and the amount
56
	 * for which this payment was created. They can be retrieved later on using
57
	 * {@link #getPaymentId()}getPaymentId() and {@link #getAmount()}getAmount()
58
	 * methods respectively later on.
59
	 * 
60
	 * @param currentCartId
61
	 *            The cart for which the payment object has to be created.
62
	 * @param userId
63
	 *            The user for whom the payment has to be created.
64
	 * @param txnId
65
	 *            The transaction against which the payment has to be created.
66
	 * @param gatewayId
67
	 * @return True if the payment object is successfully created, False
68
	 *         otherwise.
69
	 */
3561 rajveer 70
	public boolean createPayment(long currentCartId, long userId, long txnId, int gatewayId, long sourceId){
3126 rajveer 71
		PaymentClient paymentServiceClient = null;
1905 chandransh 72
		try {
3126 rajveer 73
			paymentServiceClient = new PaymentClient();
1905 chandransh 74
		} catch (Exception e) {
2199 chandransh 75
			log.error("Error while getting payment client", e);
1905 chandransh 76
			return PAYMENT_NOT_CREATED;
77
		}
78
 
79
		try {
3561 rajveer 80
			amount = calculatePaymentAmount(currentCartId, sourceId);
1905 chandransh 81
		} catch (ShoppingCartException e1) {
2199 chandransh 82
			log.error("Unable to fetch payment amount from cart id.", e1);
1905 chandransh 83
			return PAYMENT_NOT_CREATED;
84
		} catch (TException e1) {
2199 chandransh 85
			log.error("Unable to fetch payment amount.", e1);
1905 chandransh 86
			return PAYMENT_NOT_CREATED;
87
		}
88
 
89
		try {
2137 chandransh 90
			paymentId = paymentServiceClient.getClient().createPayment(userId, amount, gatewayId, txnId);
91
			// This is being done to ensure that the amount which we pass on to
92
			// the PGs is same as what we have in the database.
93
			Payment payment = paymentServiceClient.getClient().getPayment(paymentId);
94
			amount = payment.getAmount();
1905 chandransh 95
		} catch (PaymentException e1) {
2199 chandransh 96
			log.error("Unable to create payment object.", e1);
1905 chandransh 97
			return PAYMENT_NOT_CREATED;
98
		} catch (TException e) {
2199 chandransh 99
			log.error("Not able to create payment object.", e);
1905 chandransh 100
			return PAYMENT_NOT_CREATED;
101
		}
102
 
103
		return true;
104
	}
105
 
2199 chandransh 106
	// TODO: The service client parameters in the processSuccessfulTxn et al are
107
	// unnecessary but initializing them again when the caller has the necessary
108
	// references has a performance overhead. Need to think more about this.
109
 
1905 chandransh 110
	/**
2199 chandransh 111
	 * Processes a successful transaction by:
112
	 * <ol>
3063 chandransh 113
	 * <li>Marking the given transaction as 'authorized'.</li>
2199 chandransh 114
	 * <li>Removing the items in the cart for which the given transaction was
115
	 * processed.</li>
116
	 * <li>Marking the coupon associated with this transaction, if any, as used
117
	 * for this user.</li>
118
	 * <li>Queuing the transaction successful email, containing transaction
119
	 * info, to be sent later by a batch job.</li>
120
	 * </ol>
121
	 * <br>
1905 chandransh 122
	 * Please note that it's possible that a user has added items to the cart
2199 chandransh 123
	 * and so it's not possible to simply wipe out their cart. Therefore, it's
124
	 * important to ensure that we remove only as much quantity of items as for
125
	 * which the order was processed.
1905 chandransh 126
	 * 
2199 chandransh 127
	 * @param txnId
128
	 *            The transaction which should be marked as successful.
129
	 * @param userServiceClient
130
	 *            A user context service client to use.
131
	 * @param transactionServiceClient
132
	 *            A transaction service client to use.
4246 rajveer 133
	 * @param isFlagged
134
	 * 			  If payment is flagged it will be true else false 
1905 chandransh 135
	 */
4246 rajveer 136
	public static void processSuccessfulTxn(long txnId, UserClient userServiceClient, TransactionClient transactionServiceClient, boolean isFlagged) {
1905 chandransh 137
		Transaction transaction = null;
4246 rajveer 138
		TransactionStatus tStatus = TransactionStatus.AUTHORIZED;
139
        String description = "Payment authorized for the order";
140
		// if flag is set, status to be changed to flagged
141
		if(isFlagged){
142
			tStatus = TransactionStatus.FLAGGED;
143
			description = "Payment flagged for the order";
144
		}
1905 chandransh 145
		try {
146
			in.shop2020.model.v1.order.TransactionService.Client transactionClient = transactionServiceClient.getClient();
4246 rajveer 147
			transactionClient.changeTransactionStatus(txnId, tStatus, description);
1905 chandransh 148
			transaction = transactionClient.getTransaction(txnId);
2199 chandransh 149
			transactionClient.enqueueTransactionInfoEmail(txnId);
1905 chandransh 150
		} catch (TException e1) {
2199 chandransh 151
			log.error("Unable to update status of transaction. Thrift Exception:", e1);
1905 chandransh 152
		} catch (TransactionServiceException e) {
2199 chandransh 153
			log.error("Unable to update status of transaction. Thrift Exception: ", e);
1905 chandransh 154
		}
2219 varun.gupt 155
		trackCouponUsage(transaction);
2199 chandransh 156
        resetCart(transaction, userServiceClient);
1905 chandransh 157
	}
158
 
159
	/**
160
	 * Marks a transaction as well as all its orders as failed.
161
	 * 
162
	 * @param txnId
163
	 *            The id of the transaction which has to be marked as failed.
164
	 * @param transactionServiceClient
165
	 */
3126 rajveer 166
	public static void processFailedTxn(long txnId, TransactionClient transactionServiceClient) {
1905 chandransh 167
		try {
168
			in.shop2020.model.v1.order.TransactionService.Client transactionClient = transactionServiceClient.getClient();
169
			transactionClient.changeTransactionStatus(txnId, TransactionStatus.FAILED, "Payment failed for the transaction.");
170
		} catch(TException e){
2199 chandransh 171
			log.error("Thrift exception while getting information from transaction service.", e);
1905 chandransh 172
		} catch (TransactionServiceException e) {
2199 chandransh 173
			log.error("Error while updating status information in transaction database.", e);
1905 chandransh 174
		}
175
	}
176
 
3063 chandransh 177
    /**
178
     * Processes a COD transaction by:
179
     * <ol>
180
     * <li>Setting the COD flag of all the orders and moving them to the INIT
181
     * state.
182
     * <li>Marking the given transaction to be in COD_IN_PROCESS state
183
     * <li>Marking the coupon associated with this transaction, if any, as used
184
     * for this user.</li>
185
     * <li>Queuing the transaction successful email, containing transaction
186
     * info, to be sent later by a batch job.</li>
187
     * </ol>
188
     * <br>
189
     * Please note that it's possible that a user has added items to the cart
190
     * and so it's not possible to simply wipe out their cart. Therefore, it's
191
     * important to ensure that we remove only as much quantity of items as for
192
     * which the order was processed.
193
     * 
194
     * @param txnId
195
     *            The COD transaction which should be marked as verification
196
     *            pending.
197
     */
198
	public static void processCodTxn(long txnId){
199
        try {            
3126 rajveer 200
            TransactionClient transactionServiceClient = new TransactionClient();
3063 chandransh 201
            in.shop2020.model.v1.order.TransactionService.Client transactionClient = transactionServiceClient.getClient();
202
            transactionClient.changeTransactionStatus(txnId, TransactionStatus.COD_IN_PROCESS, "COD payment awaited");
203
            Transaction transaction = transactionClient.getTransaction(txnId);
204
            transactionClient.enqueueTransactionInfoEmail(txnId);
205
 
3126 rajveer 206
            UserClient userServiceClient = new UserClient();
3063 chandransh 207
            trackCouponUsage(transaction);
208
            resetCart(transaction, userServiceClient);
209
        } catch (TException e1) {
210
            log.error("Unable to update status of transaction. Thrift Exception:", e1);
211
        } catch (TransactionServiceException e) {
212
            log.error("Unable to update status of transaction. Thrift Exception: ", e);
213
        } catch (Exception e) {
214
            log.error("Unable to update status of transaction. Thrift Exception: ", e);
215
        }
216
	}
217
 
1905 chandransh 218
	/**
219
	 * Calculates the amount for the payment required for the given cart.
220
	 * 
221
	 * @param cartId
222
	 *            Id of the cart for which this payment amount has to be
223
	 *            calculated.
224
	 * @return The total amount for which a payment should be created.
225
	 * @throws ShoppingCartException
226
	 *             If no cart can be found for the given id.
227
	 * @throws TException
228
	 */
3561 rajveer 229
	private double calculatePaymentAmount(long cartId, long sourceId) throws ShoppingCartException, TException{
1905 chandransh 230
		double totalAmount = 0;
231
		Cart cart;
3126 rajveer 232
		UserClient userContextServiceClient = null;
1905 chandransh 233
		try {
3126 rajveer 234
			userContextServiceClient = new UserClient();
1905 chandransh 235
		} catch (Exception e) {
2942 chandransh 236
			log.error("Unable to initialize user context service client", e);
237
			throw new ShoppingCartException(100, "Unable to initialize the user service client");
1905 chandransh 238
		}
239
		in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
240
		cart = userClient.getCart(cartId);
1981 varun.gupt 241
 
2199 chandransh 242
		if(cart.getCouponCode() == null)  {
1981 varun.gupt 243
		    List<Line> lineItems = cart.getLines(); 
244
 
245
	        for (Line line : lineItems) {
246
	            long productId = line.getItemId();
247
	            // FIXME: It's expensive to get the price of each item from the
248
	            // catalog service. We maintain the pricing info in the line items
249
	            // themselves now.
3561 rajveer 250
	            totalAmount =  totalAmount + line.getQuantity() * getItemPrice(productId, sourceId);
1981 varun.gupt 251
	        }
2199 chandransh 252
		} else {
1981 varun.gupt 253
		    totalAmount = cart.getDiscountedPrice();
1905 chandransh 254
		}
1981 varun.gupt 255
 
1905 chandransh 256
		return totalAmount;
257
	}
258
 
3561 rajveer 259
 
260
	private double getItemPrice(long itemId, long sourceId){
261
		CatalogClient catalogClient = null;
262
		Client client = null;
263
		Double itemPrice = 0.0;
264
		try {
265
			catalogClient = new CatalogClient();
266
			client = catalogClient.getClient();
267
			Item item = client.getItemForSource(itemId, sourceId);
268
			itemPrice = item.getSellingPrice();
269
 
270
		} catch(Exception e){
271
			log.error("Unable to get the item price because of:", e);
272
		}
273
		return itemPrice;
274
	}
275
 
276
 
2199 chandransh 277
	/**
278
	 * Removes the items processed through the given transaction from the
279
	 * shopping cart.
280
	 * 
281
	 * @param transaction
282
	 *            The transaction whose items have to be removed from the
283
	 *            shopping cart.
284
	 * @param userServiceClient
285
	 */
3126 rajveer 286
	private static void resetCart(Transaction transaction, UserClient userServiceClient) {
2199 chandransh 287
		Map<Long, Double> items = new HashMap<Long, Double>();
288
		for(Order order: transaction.getOrders()){
289
			for(LineItem lineitem: order.getLineitems()){
290
				Long itemId = lineitem.getItem_id();
291
				Double quantity = items.get(itemId);
292
				if(quantity==null){
293
					quantity = lineitem.getQuantity();
294
				} else {
295
					quantity= quantity + lineitem.getQuantity();
296
				}
297
				items.put(itemId, quantity);
298
			}
299
		}
300
 
3063 chandransh 301
		log.debug("Items to reset in cart are: " + items);
2199 chandransh 302
 
303
		try {
304
			//TODO Optimize the function to send less data over the wire
305
            userServiceClient.getClient().resetCart(transaction.getShoppingCartid(), items);
306
		}catch (TException e) {
307
			log.error("Error while updating information in payment database.", e);
308
		} catch (ShoppingCartException e) {
309
			log.error("Error while reseting the cart in cart database.", e);
310
		}catch (Exception e) {
311
			log.error("Unexpected exception", e);
312
        }
313
	}
314
 
315
	/**
316
	 * Mark the coupon associated with the given transaction as used.
317
	 * 
318
	 * @param transaction
319
	 *            The transaction to track coupon for.
320
	 * 
321
	 * @param userServiceClient
322
	 *            The user service client instance to use.
323
	 */
2219 varun.gupt 324
	private static void trackCouponUsage(Transaction transaction) {
2199 chandransh 325
        try {
2219 varun.gupt 326
            String couponCode = transaction.getCoupon_code();
327
 
2199 chandransh 328
            if (couponCode != null && !couponCode.isEmpty()) {
3126 rajveer 329
            	PromotionClient promotionServiceClient = new PromotionClient();
2199 chandransh 330
                promotionServiceClient.getClient().trackCouponUsage(couponCode, transaction.getId(), transaction.getCustomer_id());
331
            }
332
        } catch (PromotionException e) {
333
            log.error("Promotion Exception: " + e);
334
        } catch (TException e)  {
335
            log.error("Transport from Promotion Service failed:", e);
336
        } catch (Exception e) {
337
            log.error("Unexpected exception:", e);
338
        }
339
	}
1905 chandransh 340
}