Subversion Repositories SmartDukaan

Rev

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