Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
1946 chandransh 1
package in.shop2020.payment.service.handler;
2
 
6050 anupam.sin 3
import in.shop2020.model.v1.order.RechargeOrder;
3578 mandeep.dh 4
import in.shop2020.payment.domain.Refund;
5
import in.shop2020.payment.handler.PaymentGatewayHandler;
6
import in.shop2020.payment.handler.PaymentHandler;
4008 mandeep.dh 7
import in.shop2020.payment.handler.PaymentRequiringExtraProcessingHandler;
3578 mandeep.dh 8
import in.shop2020.payment.handler.RefundHandler;
13352 amit.gupta 9
import in.shop2020.payment.service.handler.IPaymentHandler.Errors;
3578 mandeep.dh 10
import in.shop2020.payments.Attribute;
4008 mandeep.dh 11
import in.shop2020.payments.ExtraPaymentProcessingType;
3578 mandeep.dh 12
import in.shop2020.payments.Payment;
13
import in.shop2020.payments.PaymentException;
14
import in.shop2020.payments.PaymentGateway;
15
import in.shop2020.payments.PaymentService.Iface;
16
import in.shop2020.payments.PaymentStatus;
6050 anupam.sin 17
import in.shop2020.thrift.clients.TransactionClient;
3578 mandeep.dh 18
 
3010 chandransh 19
import java.text.SimpleDateFormat;
1946 chandransh 20
import java.util.ArrayList;
6448 rajveer 21
import java.util.Arrays;
1946 chandransh 22
import java.util.Date;
23
import java.util.HashMap;
24
import java.util.List;
25
import java.util.Map;
26
 
8618 rajveer 27
import org.apache.commons.logging.Log;
28
import org.apache.commons.logging.LogFactory;
1946 chandransh 29
import org.apache.thrift.TException;
30
import org.springframework.context.ApplicationContext;
31
import org.springframework.context.support.ClassPathXmlApplicationContext;
32
 
33
public class PaymentServiceHandler implements Iface {
3010 chandransh 34
 
8618 rajveer 35
    private static final Log logger = LogFactory.getLog(PaymentServiceHandler.class);
36
 
3010 chandransh 37
 
38
    /**
39
     * Enum of all statuses that can be returned by the HDFC gateway
40
     * 
41
     * @author Chandranshu
42
     * 
43
     */
8907 rajveer 44
    public enum HdfcPaymentReturnStatus{
3010 chandransh 45
        APPROVED("APPROVED"),
46
        NOT_APPROVED("NOT APPROVED"),
47
        CAPTURED("CAPTURED"),
48
        NOT_CAPTURED ("NOT CAPTURED"),
49
        CANCELLED ("CANCELLED"),
50
        DENIED_BY_RISK("DENIED BY RISK"),
8907 rajveer 51
        HOST_TIMEOUT("HOST TIMEOUT"),
52
        SUCCESS("SUCCESS"),
53
        FAILURE("FAILURE");
3010 chandransh 54
        private String value;
55
        HdfcPaymentReturnStatus(String value) {
56
            this.value = value;
57
        }
58
        public String value(){
59
            return this.value;
60
        }
61
    }
62
 
2391 chandransh 63
	public static final long PAYMENT_NOT_CREATED = -1;
64
 
3010 chandransh 65
	private static final long HDFC_GATEWAY_ID = 1;
66
	private static final long EBS_GATEWAY_ID = 2;
13286 amit.gupta 67
	private static final long PAYU_GATEWAY_ID = 19;
8208 amar.kumar 68
	private static final long EBAY_GATEWAY_ID = 16;
8488 amar.kumar 69
	private static final long SNAPDEAL_GATEWAY_ID = 18;
7042 amar.kumar 70
	private static final List<Long> HDFC_EMI_GATEWAY_IDS = Arrays.asList(5L,10L,11L,12L,14L);
3010 chandransh 71
 
4651 rajveer 72
	ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
1946 chandransh 73
	PaymentHandler paymentHandler = (PaymentHandler) context.getBean("paymentHandler");
4008 mandeep.dh 74
    PaymentRequiringExtraProcessingHandler paymentRequiringExtraProcessingHandler =
75
        (PaymentRequiringExtraProcessingHandler) context.getBean("paymentRequiringExtraProcessingHandler");
76
 
77
    PaymentGatewayHandler paymentGatewayHandler = (PaymentGatewayHandler) context.getBean("paymentGatewayHandler");
2747 chandransh 78
	RefundHandler refundHandler = (RefundHandler) context.getBean("refundHandler");
1946 chandransh 79
 
4651 rajveer 80
	public void setDataSourceUrl(String dbHost){
81
		org.apache.commons.dbcp.BasicDataSource ds = (org.apache.commons.dbcp.BasicDataSource)context.getBean("dataSource");
82
		ds.setUrl(dbHost);
83
	}
84
 
85
	public String getDataSourceUrl(){
86
		org.apache.commons.dbcp.BasicDataSource ds = (org.apache.commons.dbcp.BasicDataSource)context.getBean("dataSource");
87
		return ds.getUrl();
88
	}
89
 
1946 chandransh 90
	@Override
6050 anupam.sin 91
	public long createPayment(long userId, double amount, long gatewayId, long txnId, boolean isDigital) throws PaymentException, TException {
3010 chandransh 92
	    logger.info("Creating payment corresponding to our txn id:" + txnId);
1946 chandransh 93
		in.shop2020.payment.domain.Payment payment = new in.shop2020.payment.domain.Payment();
94
		payment.setUserId(userId);
95
		payment.setAmount(amount);
96
		payment.setGatewayId(gatewayId);
97
		payment.setMerchantTxnId(txnId);
98
		payment.setStatus(PaymentStatus.INIT.getValue());
6050 anupam.sin 99
		payment.setDigital(isDigital);
1946 chandransh 100
 
101
		return paymentHandler.insertPayment(payment);
102
	}
103
 
104
	@Override
105
	public List<Payment> getPaymentsForUser(long userId, long fromTime, long toTime, PaymentStatus status, long gatewayId) throws PaymentException, TException {
3010 chandransh 106
	    logger.info("Getting payments from " + fromTime + " to " + toTime + " for user: " + userId);
2291 chandransh 107
		int statusValue = -1;
108
		if(status != null)
109
			statusValue = status.getValue();
110
		else
111
			statusValue = -1;
112
		return getThriftPayments(paymentHandler.getPaymentsForUser(userId, fromTime, toTime, statusValue, gatewayId));
1946 chandransh 113
	}
114
 
115
	@Override
116
	public List<Payment> getPayments(long fromTime, long toTime, PaymentStatus status, long gatewayId) throws PaymentException,	TException {
3010 chandransh 117
	    logger.info("Getting payments from " + fromTime + " to " + toTime);
2291 chandransh 118
		int statusValue = -1;
119
		if(status != null)
120
			statusValue = status.getValue();
121
		else
122
			statusValue = -1;
123
		return getThriftPayments(paymentHandler.getPayments(fromTime, toTime, statusValue, gatewayId));
1946 chandransh 124
	}
4141 chandransh 125
 
126
	@Override
127
	public List<Payment> getPaymentsByCapturedDate(long fromTime, long toTime, long gatewayId) throws PaymentException, TException {
128
		logger.info("Getting payments from " + fromTime + " to " + toTime + " for " + gatewayId);
129
		return getThriftPayments(paymentHandler.getPaymentsByCapturedDate(fromTime, toTime, gatewayId));
130
	}
1946 chandransh 131
 
132
	@Override
133
	public PaymentGateway getPaymentGateway(long id) throws PaymentException, TException {
3010 chandransh 134
	    logger.info("Getting payment gateway with id:" + id);
2291 chandransh 135
		return paymentGatewayHandler.getPaymentGateway(id).getThriftPaymentGateway();
1946 chandransh 136
	}
4600 varun.gupt 137
 
1946 chandransh 138
	@Override
4600 varun.gupt 139
	public List<PaymentGateway> getActivePaymentGateways() throws PaymentException, TException {
140
	    logger.info("Getting all active payment gateways");
141
	    return getThriftPaymentGateways(paymentGatewayHandler.getActivePaymentGateways());
142
	}
143
 
144
	@Override
1946 chandransh 145
	public Payment getPayment(long id) throws PaymentException, TException {
3010 chandransh 146
	    logger.info("Getting payment with id: " + id);
1946 chandransh 147
		return paymentHandler.getPayment(id).getThriftPayment();
148
	}
149
 
150
	@Override
151
	public List<Payment> getPaymentForTxnId(long txnId) throws PaymentException, TException {
3010 chandransh 152
	    logger.info("Getting payment for the txn id: " + txnId);
1946 chandransh 153
		return getThriftPayments(paymentHandler.getPaymentForTxn(txnId));
154
	}
4600 varun.gupt 155
 
156
	@Override
7049 anupam.sin 157
    public List<Payment> getPaymentForRechargeTxnId(long txnId) throws PaymentException, TException {
158
        logger.info("Getting payment for the txn id: " + txnId);
159
        return getThriftPayments(paymentHandler.getPaymentForRechargeTxn(txnId));
160
    }
161
 
162
	@Override
4600 varun.gupt 163
	public Payment getSuccessfulPaymentForTxnId(long txnId) throws PaymentException, TException {
164
 
165
		for (Payment payment: getPaymentForTxnId(txnId))	{
166
			if (payment.getStatus() == PaymentStatus.SUCCESS || payment.getStatus() == PaymentStatus.PARTIALLY_CAPTURED)	{
167
				return payment;
168
			}
169
		}
170
		return null;
171
	}
1946 chandransh 172
 
173
	@Override
174
	public boolean updatePaymentDetails(long id, String gatewayPaymentId,
175
			String sessionId, String gatewayTxnStatus, String description,
176
			String gatewayTxnId, String authCode, String referenceCode,
177
			String errorCode, PaymentStatus status, String gatewayTxnDate,
178
			List<Attribute> attributes) throws PaymentException, TException {
3010 chandransh 179
	    logger.info("Updating details of payment id: " + id);
1946 chandransh 180
		in.shop2020.payment.domain.Payment payment = paymentHandler.getPayment(id);
181
		payment.setGatewayPaymentId(gatewayPaymentId);
182
		payment.setSessionId(sessionId);
183
		payment.setGatewayTxnStatus(gatewayTxnStatus);
184
		payment.setDescription(description);
185
		payment.setGatewayTxnId(gatewayTxnId);
186
		payment.setAuthCode(authCode);
187
		payment.setReferenceCode(referenceCode);
188
		payment.setErrorCode(errorCode);
189
		if(status!=null){
190
			payment.setStatus(status.getValue());
191
			if(status.equals(PaymentStatus.SUCCESS))
192
				payment.setSuccessTimestamp(new Date());
3578 mandeep.dh 193
			else if(status.equals(PaymentStatus.FAILED)) {
194
			    payment.setErrorTimestamp(new Date());
4421 mandeep.dh 195
			    persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
3578 mandeep.dh 196
			}
4421 mandeep.dh 197
			else if (status.equals(PaymentStatus.PROVISIONALLY_CAPTURED)) {
198
			    // FIXME different column to note provisional capture timestamp
199
			    // FIXME Requires extra processing at Crm end for actual manual capture
200
			    payment.setProvisionalCaptureTimestamp(new Date());
201
			    persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.PENDING_CAPTURE);
202
			}
1946 chandransh 203
		}
204
 
205
		payment.setGatewayTxnDate(gatewayTxnDate);
206
 
207
		Map<String, String> attrMap = new HashMap<String, String>();
2272 rajveer 208
		if(attributes != null){
209
			for(Attribute attribute : attributes){
210
				attrMap.put(attribute.getName(), attribute.getValue());
211
			}
1946 chandransh 212
		}
213
 
214
		paymentHandler.updatePayment(payment, attrMap);
215
		return true;
216
	}
217
 
3649 mandeep.dh 218
	/**
4008 mandeep.dh 219
	 * Persists a given payment Id in another table for future processing by CRM etc.
220
	 * Failed payments generally require a follow-up to help customers through our
221
	 * CRM-Outbound team.
3649 mandeep.dh 222
	 *
223
	 * @param payment  the payment object that failed.
4421 mandeep.dh 224
	 * @param type TODO
3649 mandeep.dh 225
	 */
4421 mandeep.dh 226
	private void persistPaymentRequiringExtraProcessing(in.shop2020.payment.domain.Payment payment, ExtraPaymentProcessingType type) {
4008 mandeep.dh 227
	    try {
4421 mandeep.dh 228
            paymentRequiringExtraProcessingHandler.insert(payment.getId(), type);
4008 mandeep.dh 229
        } catch (Exception e) {
230
            logger.error("Could not persist payment: " + payment.getId(), e);
3578 mandeep.dh 231
        }
232
    }
233
 
234
    @Override
1946 chandransh 235
	public List<Double> getSuccessfulPaymentsAmountRange() throws TException {
3010 chandransh 236
	    logger.info("Getting the range of successful payments.");
1946 chandransh 237
		List<Double> minMaxAmounts = new ArrayList<Double>();
238
		Map<String, Float> minMax = paymentHandler.getMinMaxPaymentAmount();
239
		minMaxAmounts.add(Double.parseDouble(Float.toString(minMax.get("MIN"))));
240
		minMaxAmounts.add(Double.parseDouble(Float.toString(minMax.get("MAX"))));
241
		return minMaxAmounts;
242
	}
243
 
6050 anupam.sin 244
    @Override
10269 amit.gupta 245
    public String initializeHdfcPayment(long merchantPaymentId, boolean isMobile) throws PaymentException, TException {
6050 anupam.sin 246
        logger.info("Initializing HDFC payment with id: " + merchantPaymentId);
247
        in.shop2020.payment.domain.Payment payment = paymentHandler.getPayment(merchantPaymentId);
248
        String redirectURL;
249
        try {
10269 amit.gupta 250
            redirectURL = HdfcPaymentHandler.initializeHdfcPayment(payment, this, isMobile);
6050 anupam.sin 251
        } catch (Exception e) {
252
            throw new PaymentException(102, "Error while initiliazing payment. Check service log for more details.");
253
        }
254
        return redirectURL;
255
    }
256
 
257
    @Override
10269 amit.gupta 258
	public String doHdfcPaymentForDigitalOrder(long merchantPaymentId, long rechargeOrderId, String phone, boolean isMobile) throws PaymentException, TException {
6050 anupam.sin 259
        logger.info("Initializing HDFC payment with id: " + merchantPaymentId);
10968 amit.gupta 260
        logger.info("doHdfcPaymentForDigitalOrder phone---- " + phone);
261
 
6050 anupam.sin 262
        in.shop2020.payment.domain.Payment payment = paymentHandler.getPayment(merchantPaymentId);
263
        TransactionClient tc = new TransactionClient();
264
        String redirectURL;
265
        RechargeOrder rechargeOrder;
266
        try {
267
            rechargeOrder = tc.getClient().getRechargeOrder(rechargeOrderId);
10269 amit.gupta 268
            redirectURL = HdfcPaymentHandler.initializeHdfcPayment(payment, rechargeOrder, phone, this, isMobile);
6050 anupam.sin 269
        } catch (Exception e) {
270
            throw new PaymentException(102, "Error while initiliazing payment. Check service log for more details.");
271
        }
272
 
273
        return redirectURL;
274
    }
2391 chandransh 275
 
276
	@Override
10269 amit.gupta 277
    public String initializeHdfcEmiPayment(long merchantPaymentId, boolean isMobile) throws PaymentException, TException {
3616 chandransh 278
        logger.info("Initializing HDFC payment with id: " + merchantPaymentId);
279
        in.shop2020.payment.domain.Payment payment = paymentHandler.getPayment(merchantPaymentId);
280
        String redirectURL;
281
        try {
10470 amit.gupta 282
            redirectURL = HdfcEmiPaymentHandler.initializeHdfcPayment(payment, this, isMobile);
3616 chandransh 283
        } catch (Exception e) {
284
            throw new PaymentException(102, "Error while initiliazing payment. Check service log for more details.");
285
        }
286
        return redirectURL;
287
    }
288
 
6486 rajveer 289
	@Override
290
	public synchronized boolean refundPayment(long merchantTxnId, double amount, boolean isDigital) throws PaymentException, TException {
6482 rajveer 291
        logger.info("Attempting to refund payment of amount " + amount + " corresponding to our transaction " + merchantTxnId);
8409 rajveer 292
        List<in.shop2020.payment.domain.Payment> payments;
293
        if(isDigital){
294
        	payments = paymentHandler.getPaymentForRechargeTxn(merchantTxnId);
295
        }else{
296
        	payments = paymentHandler.getPaymentForTxn(merchantTxnId);
297
        }
6482 rajveer 298
        if(payments ==null || payments.isEmpty())
299
            throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
300
 
6486 rajveer 301
        if(payments ==null || payments.isEmpty())
302
            throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
303
 
6482 rajveer 304
        in.shop2020.payment.domain.Payment payment = payments.get(0);
6486 rajveer 305
 
306
        if(payment.getAmount() < amount){
307
        	logger.warn("Refund amount is more than payment amount.");
308
            return false;
309
        }
310
 
6482 rajveer 311
        switch(PaymentStatus.findByValue(payment.getStatus())){
312
        case PENDING:
313
            logger.error("Attempt to refund a non-authorized payment");
314
            return false;
315
        case INIT:
316
            logger.warn("Attempt to refund a non-authorized payment");
317
            return false;
318
        case AUTHORIZED:
319
        	logger.warn("Attempt to refund a non-captured payment");
320
            return false;
321
        case CAPTURE_IN_PROCESS:
322
        	logger.warn("Attempt to refund a non-captured payment");
323
            return false;
324
        case PROVISIONALLY_CAPTURED:
325
        	logger.warn("Attempt to refund a non-captured payment");
326
            return false;
6486 rajveer 327
        case REFUNDED:
328
        	logger.warn("Attempt to refund a refunded payment");
329
            return false;
6482 rajveer 330
        case SUCCESS:
331
            break;
332
        case FAILED:
333
            logger.error("Attempting to capture a failed payment");
334
            return false;
335
        }
336
 
337
        long gatewayId = payment.getGatewayId();
338
 
339
        if(gatewayId == HDFC_GATEWAY_ID){
6491 rajveer 340
            //Refund the HDFC payment
6482 rajveer 341
            return refundHdfcPayment(payment, amount);
6491 rajveer 342
        }else if (gatewayId == EBS_GATEWAY_ID){
343
            //Refund the EBS payment
344
            return refundEbsPayment(payment, amount);
6482 rajveer 345
        } 
6491 rajveer 346
        else if (HDFC_EMI_GATEWAY_IDS.contains(gatewayId)){
347
             //Capture and update the HDFC EMI payment
348
            return refundHdfcEmiPayment(payment, amount);
349
        }
6482 rajveer 350
 
351
        logger.error("We have an captured payment from unknown gateway: " + gatewayId);
352
        return false;
353
    }
354
 
355
 
3616 chandransh 356
	@Override
2689 chandransh 357
    public long createRefund(long orderId, long merchantTxnId, double amount) throws PaymentException, TException{
6482 rajveer 358
		logger.info("Attempting to create a refund for order: " + orderId);
6488 rajveer 359
//		if(!refundPayment(merchantTxnId, amount, false)){
360
//			logger.warn("Not able to refund corresponding to the merchant txn " + merchantTxnId);
361
//		}
2689 chandransh 362
		List<in.shop2020.payment.domain.Payment> payments = paymentHandler.getPaymentForTxn(merchantTxnId);
363
		if(payments ==null || payments.isEmpty())
364
			throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
365
 
3010 chandransh 366
		in.shop2020.payment.domain.Payment payment = payments.get(0);
2689 chandransh 367
		if(payment.getStatus() != PaymentStatus.SUCCESS.getValue())
368
			throw new PaymentException(104, "No successful payments found corresponding to the merchant txn " + merchantTxnId);
369
 
2747 chandransh 370
		Refund refund = new Refund();
371
		refund.setOrderId(orderId);
372
		refund.setPaymentId(payment.getId());
373
		refund.setGatewayId(payment.getGatewayId());
374
		refund.setAmount(amount);
375
		refund.setAttempts(0);
376
		return refundHandler.createRefund(refund);
2689 chandransh 377
    }
378
 
3010 chandransh 379
    @Override
8618 rajveer 380
    public synchronized boolean capturePayment(long merchantTxnId, boolean isDigital) throws PaymentException, TException {
381
        logger.info("Attempting to capture payment corresponding to our transaction " + merchantTxnId + " and Is Digital is:" + isDigital);
382
        List<in.shop2020.payment.domain.Payment> payments;
383
        if(isDigital){
384
        	payments = paymentHandler.getPaymentForRechargeTxn(merchantTxnId);
385
        }else{
386
        	payments = paymentHandler.getPaymentForTxn(merchantTxnId);
387
        }
3010 chandransh 388
        if(payments ==null || payments.isEmpty())
389
            throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
390
 
391
        in.shop2020.payment.domain.Payment payment = payments.get(0);
392
        switch(PaymentStatus.findByValue(payment.getStatus())){
393
        case PENDING:
394
            logger.error("Attempt to capture a non-authorized payment");
395
            return false;
396
        case INIT:
397
            logger.warn("Attempt to capture a non-authorized payment");
398
            return false;
399
        case AUTHORIZED:
4421 mandeep.dh 400
        case CAPTURE_IN_PROCESS:
3010 chandransh 401
            //Actual work to be done in this case. Let the call proceed.
402
            break;
4421 mandeep.dh 403
        case PROVISIONALLY_CAPTURED:
404
            logger.info("Attempting to capture a payment that is provisonally captured but we can let the client proceed.");
405
            return true;
3010 chandransh 406
        case SUCCESS:
407
            logger.warn("Attempting to capture an already captured payment but we can let the client proceed.");
408
            return true;
409
        case FAILED:
410
            logger.error("Attempting to capture a failed payment");
411
            return false;
412
        }
413
 
414
        long gatewayId = payment.getGatewayId();
415
 
416
        if(gatewayId == HDFC_GATEWAY_ID){
417
            //Capture and update the HDFC payment
418
            return captureAndUpdateHdfcPayment(payment);
419
        } else if (gatewayId == EBS_GATEWAY_ID){
420
            //Capture and update the EBS payment
421
            return captureAndUpdateEbsPayment(payment);
6449 rajveer 422
        } else if (HDFC_EMI_GATEWAY_IDS.contains(gatewayId)){
3583 chandransh 423
            //Capture and update the HDFC EMI payment
424
            return captureAndUpdateHdfcEmiPayment(payment);
8488 amar.kumar 425
        } else if (gatewayId == EBAY_GATEWAY_ID || gatewayId == SNAPDEAL_GATEWAY_ID) {
8208 amar.kumar 426
        	return true;
13286 amit.gupta 427
        } else if (gatewayId == PAYU_GATEWAY_ID) {
13352 amit.gupta 428
        	return captureAndUpdatePayuPayment(payment);
3010 chandransh 429
        }
430
 
431
        logger.error("We have an authorized payment from unknown gateway: " + gatewayId);
432
        return false;
433
    }
434
 
13352 amit.gupta 435
    private boolean captureAndUpdatePayuPayment(in.shop2020.payment.domain.Payment payment)  throws PaymentException{
436
    	long merchantPaymentId = payment.getId();
437
 
438
        logger.info("Capturing Payu payment with id: " + merchantPaymentId);
439
        Map<String, String> attrMap = new HashMap<String, String>();
440
        Map<String, String> captureResult = PayuPaymentHandler.captureTransaction(merchantPaymentId + "", payment.getGatewayTxnId());
441
        if(captureResult.containsKey(IPaymentHandler.ERROR)){
442
            payment.setDescription(captureResult.get(IPaymentHandler.ERROR));
443
            payment.setErrorCode(captureResult.get(IPaymentHandler.ERR_CODE));
444
            payment.setErrorTimestamp(new Date());
445
        	if(captureResult.get(IPaymentHandler.ERR_CODE).equals(Errors.CAPTURE_FAILURE)) {
446
                payment.setStatus(PaymentStatus.FAILED.getValue());
447
                paymentHandler.updatePayment(payment, attrMap);
448
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
449
        	} else {
450
        		logger.error("Capture attempt failed for HDFC payment with id: " + merchantPaymentId);
451
        		payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());
452
        		paymentHandler.updatePayment(payment, attrMap);
453
        		throw new PaymentException(106, captureResult.get(IPaymentHandler.ERROR));
454
        	}
455
        	return false;
456
        } else {
457
        	logger.info("Capture attempt successful for HDFC payment with id: " + merchantPaymentId);
458
            payment.setDescription("Payment Captured");
459
            payment.setGatewayTxnStatus("captured");
460
            payment.setStatus(PaymentStatus.SUCCESS.getValue());
461
            payment.setSuccessTimestamp(new Date());           
462
            payment.setReferenceCode(captureResult.get(PayuPaymentHandler.REF_NO));
463
            attrMap.put(IPaymentHandler.CAPTURE_TXN_ID, captureResult.get(IPaymentHandler.CAPTURE_TXN_ID));
464
            attrMap.put(IPaymentHandler.CAPTURE_REF_ID, captureResult.get(IPaymentHandler.CAPTURE_REF_ID));
465
            attrMap.put(IPaymentHandler.CAPTURE_AUTH_ID, captureResult.get(IPaymentHandler.CAPTURE_AUTH_ID));
466
 
467
            SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
468
            attrMap.put(HdfcPaymentHandler.CAPTURE_TIME, captureTimeDateFormatter.format(new Date()));
469
 
470
            paymentHandler.updatePayment(payment, attrMap);
471
            return true;
472
        }
13286 amit.gupta 473
	}
474
 
475
	@Override
3956 chandransh 476
    public boolean partiallyCapturePayment(long merchantTxnId, double amount, String xferBy, String xferTxnId, long xferDate) throws PaymentException, TException {
477
        logger.info("Attempting to partially capture payment corresponding to our transaction " + merchantTxnId);
478
        List<in.shop2020.payment.domain.Payment> payments = paymentHandler.getPaymentForTxn(merchantTxnId);
479
        if(payments ==null || payments.isEmpty())
480
            throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
481
 
482
        in.shop2020.payment.domain.Payment payment = payments.get(0);
483
        switch(PaymentStatus.findByValue(payment.getStatus())){
484
        case PENDING:
485
            // COD payments lie in this state before settlement.
486
        case INIT:
487
        case PARTIALLY_CAPTURED:
488
        case AUTHORIZED:
489
            // COD payments would not be in this state but we are processing
490
            // payments in this state as well for forward compatibility since
491
            // someday we'd want to be able to capture authorized CC payments
492
            // partially.
493
            break;
494
        case SUCCESS:
495
            logger.warn("Attempting to capture an already captured payment but we can let the client proceed.");
496
            return true;
497
        case FAILED:
498
            logger.error("Attempting to capture a failed payment");
499
            return false;
500
        }
501
        SimpleDateFormat mysqlDateFormatter = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
502
        String xferDateStr = mysqlDateFormatter.format(new Date(xferDate));
503
 
504
        return settleAndUpdateCodPayment(payment, amount, xferBy, xferTxnId, xferDateStr);
505
    }
506
 
3010 chandransh 507
    /**
508
     * Capture the HDFC payment represented by the given payment object. If the
509
     * capture attempt is not successful, we mark this payment as failed. We
510
     * don't retry or anything. We'll add the support of multiple attempts later
511
     * on.
512
     * 
513
     * @param payment The payment which has to be captured.
514
     * @return True if the payment attempt is successful, false if not.
4421 mandeep.dh 515
     * @throws PaymentException 
3010 chandransh 516
     */
4421 mandeep.dh 517
    private boolean captureAndUpdateHdfcPayment(in.shop2020.payment.domain.Payment payment) throws PaymentException {
3010 chandransh 518
        long merchantPaymentId = payment.getId();
519
        logger.info("Capturing HDFC payment with id: " + merchantPaymentId);
520
        Map<String, String> captureResult = HdfcPaymentHandler.capturePayment(payment);
521
        String captureStatus = captureResult.get(IPaymentHandler.STATUS);
522
        String gatewayStatus = captureResult.get(IPaymentHandler.GATEWAY_STATUS);
523
 
524
        Map<String, String> attrMap = new HashMap<String, String>();
525
        if (!captureStatus.trim().equals("0") 
526
                || !HdfcPaymentReturnStatus.CAPTURED.value().equals(gatewayStatus)) {
527
            // Failure
3616 chandransh 528
            logger.error("Capture attempt failed for HDFC payment with id: " + merchantPaymentId);
3010 chandransh 529
            String description = captureResult.get(IPaymentHandler.ERROR);
530
            String errorCode = captureResult.get(IPaymentHandler.ERR_CODE);
531
 
532
            payment.setDescription(description);
533
            payment.setErrorCode(errorCode);
534
            payment.setErrorTimestamp(new Date());
4421 mandeep.dh 535
 
536
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
537
                payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());
538
                paymentHandler.updatePayment(payment, attrMap);
539
                throw new PaymentException(106, "Could not capture due to connection issue");
540
            }
541
            else {
542
                payment.setStatus(PaymentStatus.FAILED.getValue());
543
                paymentHandler.updatePayment(payment, attrMap);
544
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
545
            }
546
 
3010 chandransh 547
            return false;
548
        } else {
549
            // Success
3616 chandransh 550
            logger.info("Capture attempt successful for HDFC payment with id: " + merchantPaymentId);
3010 chandransh 551
            payment.setDescription("Payment Captured");
552
            payment.setGatewayTxnStatus(gatewayStatus);
553
            payment.setStatus(PaymentStatus.SUCCESS.getValue());
554
            payment.setSuccessTimestamp(new Date());           
555
 
556
            attrMap.put(IPaymentHandler.CAPTURE_TXN_ID, captureResult.get(IPaymentHandler.CAPTURE_TXN_ID));
557
            attrMap.put(IPaymentHandler.CAPTURE_REF_ID, captureResult.get(IPaymentHandler.CAPTURE_REF_ID));
558
            attrMap.put(IPaymentHandler.CAPTURE_AUTH_ID, captureResult.get(IPaymentHandler.CAPTURE_AUTH_ID));
559
 
560
            SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
561
            attrMap.put(HdfcPaymentHandler.CAPTURE_TIME, captureTimeDateFormatter.format(new Date()));
562
 
563
            paymentHandler.updatePayment(payment, attrMap);
564
            return true;
565
          }
566
    }
567
 
568
    /**
3583 chandransh 569
     * Capture the HDFC EMI payment represented by the given payment object. If
570
     * the capture attempt is not successful, we mark this payment as failed. We
571
     * don't retry or anything. We'll add the support of multiple attempts later
572
     * on.
573
     * 
574
     * @param payment
575
     *            The payment which has to be captured.
576
     * @return True if the payment attempt is successful, false if not.
4421 mandeep.dh 577
     * @throws PaymentException 
3583 chandransh 578
     */
4421 mandeep.dh 579
    private boolean captureAndUpdateHdfcEmiPayment(in.shop2020.payment.domain.Payment payment) throws PaymentException{
3583 chandransh 580
        long merchantPaymentId = payment.getId();
581
        logger.info("Capturing HDFC payment with id: " + merchantPaymentId);
582
        Map<String, String> captureResult = HdfcEmiPaymentHandler.capturePayment(payment);
583
        String captureStatus = captureResult.get(IPaymentHandler.STATUS);
584
        String gatewayStatus = captureResult.get(IPaymentHandler.GATEWAY_STATUS);
585
 
586
        Map<String, String> attrMap = new HashMap<String, String>();
587
        if (!captureStatus.trim().equals("0") 
588
                || !HdfcPaymentReturnStatus.CAPTURED.value().equals(gatewayStatus)) {
589
            // Failure
3616 chandransh 590
            logger.error("Capture attempt failed for HDFC payment with id: " + merchantPaymentId);
3583 chandransh 591
            String description = captureResult.get(IPaymentHandler.ERROR);
592
            String errorCode = captureResult.get(IPaymentHandler.ERR_CODE);
593
 
594
            payment.setDescription(description);
595
            payment.setErrorCode(errorCode);
4421 mandeep.dh 596
            payment.setErrorTimestamp(new Date());                
597
 
598
            // Not marking payments as failed in case of connection issues
599
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
600
                payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());
601
                paymentHandler.updatePayment(payment, attrMap);
602
                throw new PaymentException(106, "Could not capture due to connection issue");
603
            }
604
            else {
605
                payment.setStatus(PaymentStatus.FAILED.getValue());
606
                paymentHandler.updatePayment(payment, attrMap);
607
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
608
            }
609
 
3583 chandransh 610
            return false;
611
        } else {
612
            // Success
3616 chandransh 613
            logger.info("Capture attempt successful for HDFC payment with id: " + merchantPaymentId);
3583 chandransh 614
            payment.setDescription("Payment Captured");
615
            payment.setGatewayTxnStatus(gatewayStatus);
616
            payment.setStatus(PaymentStatus.SUCCESS.getValue());
4421 mandeep.dh 617
            payment.setSuccessTimestamp(new Date());
3583 chandransh 618
 
619
            attrMap.put(IPaymentHandler.CAPTURE_TXN_ID, captureResult.get(IPaymentHandler.CAPTURE_TXN_ID));
620
            attrMap.put(IPaymentHandler.CAPTURE_REF_ID, captureResult.get(IPaymentHandler.CAPTURE_REF_ID));
621
            attrMap.put(IPaymentHandler.CAPTURE_AUTH_ID, captureResult.get(IPaymentHandler.CAPTURE_AUTH_ID));
622
 
623
            SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
624
            attrMap.put(HdfcPaymentHandler.CAPTURE_TIME, captureTimeDateFormatter.format(new Date()));
625
 
626
            paymentHandler.updatePayment(payment, attrMap);
627
            return true;
628
          }
629
    }
630
 
631
    /**
3010 chandransh 632
     * Capture the EBS payment represented by the given payment object. If the
633
     * capture attempt is not successful, we mark this payment as failed. We
634
     * don't retry or anything. We'll add the support of multiple attempts later
635
     * on.
636
     * 
637
     * @param payment The payment which has to be captured.
638
     * @return True if the payment attempt is successful, false if not.
4421 mandeep.dh 639
     * @throws PaymentException 
3010 chandransh 640
     */
4421 mandeep.dh 641
    private boolean captureAndUpdateEbsPayment(in.shop2020.payment.domain.Payment payment) throws PaymentException{
3010 chandransh 642
        Map<String, String> captureResult = EbsPaymentHandler.capturePayment(payment);
643
        String captureStatus = captureResult.get(EbsPaymentHandler.STATUS);
8650 anupam.sin 644
        for(String key : captureResult.keySet()) {
645
            logger.info("key : " + key + " value : " + captureResult.get(key));
646
        }
3010 chandransh 647
 
8650 anupam.sin 648
        logger.info("capture status : " + captureStatus);
649
 
3010 chandransh 650
        Map<String, String> attrMap = new HashMap<String, String>();
651
        if("".equals(captureStatus)){
652
            //Failure
3616 chandransh 653
            logger.error("Capture attempt failed for EBS payment with id: " + payment.getId());
3010 chandransh 654
            String description = captureResult.get(EbsPaymentHandler.ERROR);
655
            String errorCode = captureResult.get(EbsPaymentHandler.ERR_CODE);
4421 mandeep.dh 656
 
3010 chandransh 657
            payment.setDescription(description);
658
            payment.setErrorCode(errorCode);
659
            payment.setErrorTimestamp(new Date());
4421 mandeep.dh 660
 
661
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
662
                payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());            
663
                paymentHandler.updatePayment(payment, attrMap);
664
                throw new PaymentException(106, "Could not capture due to connection issue");
665
            }
666
            else {
667
                payment.setStatus(PaymentStatus.FAILED.getValue());            
668
                paymentHandler.updatePayment(payment, attrMap);
669
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
670
            }
671
 
3010 chandransh 672
            return false;
673
        }else{
674
            //Success
3616 chandransh 675
            logger.info("Capture attempt successful for EBS payment with id: " + payment.getId());
3010 chandransh 676
            payment.setGatewayTxnStatus(captureStatus);
677
            payment.setStatus(PaymentStatus.SUCCESS.getValue());
678
            payment.setSuccessTimestamp(new Date());
679
 
680
            attrMap.put(IPaymentHandler.CAPTURE_TXN_ID, captureResult.get(IPaymentHandler.CAPTURE_TXN_ID));
681
            attrMap.put(IPaymentHandler.CAPTURE_TIME, captureResult.get(IPaymentHandler.CAPTURE_TIME));
682
            paymentHandler.updatePayment(payment, attrMap);
683
            return true;
684
        }
685
    }
686
 
6482 rajveer 687
 
3010 chandransh 688
    /**
6482 rajveer 689
     * Refund the HDFC payment represented by the given payment object. If the
690
     * refund attempt is not successful, will not any action.
691
     * 
692
     * @param payment The payment which has to be captured.
693
     * @amount amount to be refunded
694
     * @return True if the payment attempt is successful, false if not.
695
     * @throws PaymentException 
696
     */
697
    private boolean refundHdfcPayment(in.shop2020.payment.domain.Payment payment, double amount) throws PaymentException {
698
        long merchantPaymentId = payment.getId();
699
        logger.info("Refunding HDFC payment with id: " + merchantPaymentId);
700
        Map<String, String> refundResult = HdfcPaymentHandler.refundPayment(payment, amount);
6486 rajveer 701
        String refundStatus = refundResult.get(IPaymentHandler.STATUS);
6482 rajveer 702
        String gatewayStatus = refundResult.get(IPaymentHandler.GATEWAY_STATUS);
703
 
704
        Map<String, String> attrMap = new HashMap<String, String>();
6486 rajveer 705
        if (!refundStatus.trim().equals("0") 
6482 rajveer 706
                || !HdfcPaymentReturnStatus.CAPTURED.value().equals(gatewayStatus)) {
6486 rajveer 707
 
708
        	logger.error("Refund attempt failed for HDFC payment with id: " + merchantPaymentId);
709
            String description = refundResult.get(IPaymentHandler.ERROR);
710
            String errorCode = refundResult.get(IPaymentHandler.ERR_CODE);
711
 
712
            payment.setDescription(description);
713
            payment.setErrorCode(errorCode);
714
            payment.setErrorTimestamp(new Date());
715
 
716
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
717
                //payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());
718
                //paymentHandler.updatePayment(payment, attrMap);
719
                throw new PaymentException(106, "Could not capture due to connection issue. Try Later");
720
            }
721
            else {
6491 rajveer 722
//                payment.setStatus(PaymentStatus.FAILED.getValue());
723
//                paymentHandler.updatePayment(payment, attrMap);
6486 rajveer 724
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
725
            }
726
 
6482 rajveer 727
            return false;
728
        } else {
729
            // Success
730
            logger.info("Refund attempt successful for HDFC payment with id: " + merchantPaymentId);
731
            payment.setDescription("Payment Refunded");
732
            payment.setGatewayTxnStatus(gatewayStatus);
6503 rajveer 733
            payment.setStatus(PaymentStatus.REFUNDED.getValue());    
734
            payment.setRefundAmount(amount);
6482 rajveer 735
 
6486 rajveer 736
            attrMap.put(IPaymentHandler.REFUND_TXN_ID, refundResult.get(IPaymentHandler.REFUND_TXN_ID));
737
            attrMap.put(IPaymentHandler.REFUND_REF_ID, refundResult.get(IPaymentHandler.REFUND_REF_ID));
738
            attrMap.put(IPaymentHandler.REFUND_AUTH_ID, refundResult.get(IPaymentHandler.REFUND_AUTH_ID));
6503 rajveer 739
            attrMap.put(IPaymentHandler.REFUND_AMNT, refundResult.get(IPaymentHandler.REFUND_AMNT));
740
 
6482 rajveer 741
            SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
6486 rajveer 742
            attrMap.put(HdfcPaymentHandler.REFUND_TIME, captureTimeDateFormatter.format(new Date()));
6482 rajveer 743
 
744
            paymentHandler.updatePayment(payment, attrMap);
745
            return true;
746
          }
747
    }
748
 
749
 
6491 rajveer 750
    /**
751
     * Refund the HDFC EMI payment represented by the given payment object. If
752
     * the capture attempt is not successful, we will not do anything.
753
     * 
754
     * @param payment
755
     *            The payment which has to be captured.
756
     * @return True if the payment attempt is successful, false if not.
757
     * @throws PaymentException 
758
     */
759
    private boolean refundHdfcEmiPayment(in.shop2020.payment.domain.Payment payment, double amount) throws PaymentException{
760
        long merchantPaymentId = payment.getId();
761
        logger.info("Refunding HDFC payment with id: " + merchantPaymentId);
762
        Map<String, String> refundResult = HdfcEmiPaymentHandler.refundPayment(payment, amount);
763
        String refundStatus = refundResult.get(IPaymentHandler.STATUS);
764
        String gatewayStatus = refundResult.get(IPaymentHandler.GATEWAY_STATUS);
765
 
766
        Map<String, String> attrMap = new HashMap<String, String>();
767
        if (!refundStatus.trim().equals("0") 
768
                || !HdfcPaymentReturnStatus.CAPTURED.value().equals(gatewayStatus)) {
769
            // Failure
770
            logger.error("Refund attempt failed for HDFC payment with id: " + merchantPaymentId);
771
            String description = refundResult.get(IPaymentHandler.ERROR);
772
            String errorCode = refundResult.get(IPaymentHandler.ERR_CODE);
773
 
774
            payment.setDescription(description);
775
            payment.setErrorCode(errorCode);
776
            payment.setErrorTimestamp(new Date());                
777
 
778
            // Not marking payments as failed in case of connection issues
779
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
780
             //   payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());
781
             //   paymentHandler.updatePayment(payment, attrMap);
782
                throw new PaymentException(106, "Could not capture due to connection issue");
783
            }
784
            else {
785
              //  payment.setStatus(PaymentStatus.FAILED.getValue());
786
              //  paymentHandler.updatePayment(payment, attrMap);
787
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
788
            }
789
 
790
            return false;
791
        } else {
792
            // Success
793
            logger.info("Refund attempt successful for HDFC payment with id: " + merchantPaymentId);
794
            payment.setDescription("Payment Refunded");
795
            payment.setGatewayTxnStatus(gatewayStatus);
796
            payment.setStatus(PaymentStatus.REFUNDED.getValue());           
6503 rajveer 797
            payment.setRefundAmount(amount);
6491 rajveer 798
 
799
            attrMap.put(IPaymentHandler.REFUND_TXN_ID, refundResult.get(IPaymentHandler.REFUND_TXN_ID));
800
            attrMap.put(IPaymentHandler.REFUND_REF_ID, refundResult.get(IPaymentHandler.REFUND_REF_ID));
801
            attrMap.put(IPaymentHandler.REFUND_AUTH_ID, refundResult.get(IPaymentHandler.REFUND_AUTH_ID));
6503 rajveer 802
            attrMap.put(IPaymentHandler.REFUND_AMNT, refundResult.get(IPaymentHandler.REFUND_AMNT));
803
 
6491 rajveer 804
            SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
805
            attrMap.put(HdfcPaymentHandler.REFUND_TIME, captureTimeDateFormatter.format(new Date()));
806
 
807
            paymentHandler.updatePayment(payment, attrMap);
808
            return true;
809
          }
810
    }
6482 rajveer 811
 
812
    /**
6491 rajveer 813
     * Refund the EBS payment represented by the given payment object. If the
814
     * capture attempt is not successful, we will ignore. We don't retry or anything. 
815
     * We'll add the support of multiple attempts later on.
816
     * 
817
     * @param payment The payment which has to be captured.
818
     * @amount Amount to be refunded
819
     * @return True if the payment attempt is successful, false if not.
820
     * @throws PaymentException 
821
     */
822
    private boolean refundEbsPayment(in.shop2020.payment.domain.Payment payment, double amount) throws PaymentException{
823
        Map<String, String> refundResult = EbsPaymentHandler.refundPayment(payment, amount);
824
        String refundStatus = refundResult.get(EbsPaymentHandler.STATUS);
825
 
826
        Map<String, String> attrMap = new HashMap<String, String>();
827
        if("".equals(refundStatus)){
828
            //Failure
829
            logger.error("Refund attempt failed for EBS payment with id: " + payment.getId());
830
            String description = refundResult.get(EbsPaymentHandler.ERROR);
831
            String errorCode = refundResult.get(EbsPaymentHandler.ERR_CODE);
832
 
833
            payment.setDescription(description);
834
            payment.setErrorCode(errorCode);
835
            payment.setErrorTimestamp(new Date());
836
 
837
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
838
//                payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());            
839
//                paymentHandler.updatePayment(payment, attrMap);
840
                throw new PaymentException(106, "Could not capture due to connection issue");
841
            }
842
            else {
843
//                payment.setStatus(PaymentStatus.FAILED.getValue());            
844
//                paymentHandler.updatePayment(payment, attrMap);
845
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
846
            }
847
 
848
            return false;
849
        }else{
850
            //Success
851
            logger.info("Refund attempt successful for EBS payment with id: " + payment.getId());
852
            payment.setGatewayTxnStatus(refundStatus);
853
            payment.setStatus(PaymentStatus.REFUNDED.getValue());
6503 rajveer 854
            payment.setRefundAmount(amount);
6491 rajveer 855
 
856
            attrMap.put(IPaymentHandler.REFUND_TXN_ID, refundResult.get(IPaymentHandler.REFUND_TXN_ID));
857
            attrMap.put(IPaymentHandler.REFUND_TIME, refundResult.get(IPaymentHandler.REFUND_TIME));
858
            paymentHandler.updatePayment(payment, attrMap);
859
            return true;
860
        }
861
    }
862
 
863
 
864
    /**
3956 chandransh 865
     * Updates the settlement details of COD payments. Sets payment status as
866
     * either PARTIALLY CAPTURED or SUCCESS depending on whether the complete
867
     * amount has been captured. Other parameters are set as attributes.
868
     * 
869
     * @param payment
870
     *            The payment which needs to be updated.
871
     * @param amount
872
     *            Amount that has been captured.
873
     * @param xferBy
874
     *            Entity which transferred the money.
875
     * @param xferTxnId
876
     *            Transaction Id of the transfer.
877
     * @param xferDateStr
878
     *            Date on which the transfer took place.
879
     * @return true if the payment details were updated successfully.
880
     * @throws PaymentException
881
     *             if the captured amount will become more than the actual
882
     *             amount after this update.
883
     */
884
    private boolean settleAndUpdateCodPayment(in.shop2020.payment.domain.Payment payment, double amount, String xferBy, String xferTxnId, String xferDateStr) throws PaymentException{
885
        Map<String, String> attrMap = payment.getAttributeMap();
886
 
887
        double captureAmount = 0;
888
        String captureAmntStr = attrMap.get(IPaymentHandler.CAPTURE_AMNT);
889
        if(captureAmntStr != null)
890
            captureAmount = Double.parseDouble(captureAmntStr);
891
        captureAmount += amount;
5051 rajveer 892
        // If capture amount higher than payment amount by more than 50 paisa,
893
        // there is some issue and we should raise exception.
894
        if(captureAmount - payment.getAmount() > 0.5){
895
        	throw new PaymentException(105, "We've got a settlement request for an amount which is more than the transaction value.");
896
        }
3956 chandransh 897
 
5051 rajveer 898
        // If capture amount differs from payment amount by less than 50 paisa, lets mark the payment as successful. 
899
        // Else we can safely assume there will be some more orders for the payment, leading to make the payment as partially captured.
900
        if(Math.abs(captureAmount - payment.getAmount()) < 0.5){
901
        	payment.setStatus(PaymentStatus.SUCCESS.getValue());
902
        }else {
903
        	payment.setStatus(PaymentStatus.PARTIALLY_CAPTURED.getValue());   
3956 chandransh 904
        }
905
        payment.setSuccessTimestamp(new Date());
906
        attrMap.put(IPaymentHandler.CAPTURE_AMNT, captureAmount + "");
907
        attrMap.put(IPaymentHandler.XFER_TXN_ID, xferTxnId);
908
        attrMap.put(IPaymentHandler.XFER_TXN_DATE, xferDateStr);
909
        attrMap.put(IPaymentHandler.XFER_BY, xferBy);
910
        paymentHandler.updatePayment(payment, attrMap);
911
        return true;
912
    }
913
 
914
    /**
3010 chandransh 915
     * Creates a list of thrift payment objects corresponding to a list of
916
     * payment data objects.
917
     * 
918
     * @param daoPayments
919
     *            A list of payment DAO.
920
     * @return A list of Thrift payment objects.
921
     */
922
    private List<Payment> getThriftPayments(List<in.shop2020.payment.domain.Payment> daoPayments){
923
 
924
        List<Payment> payments = new ArrayList<Payment>();
925
        for(in.shop2020.payment.domain.Payment payment : daoPayments){
926
            payments.add(payment.getThriftPayment());
927
        }
928
        return payments;
929
    }
3375 rajveer 930
 
4600 varun.gupt 931
    /**
932
     * Creates a list of thrift payment gateway objects corresponding to a list of
933
     * payment gateway data objects.
934
     * 
935
     * @param daoPaymentGateways
936
     *            A list of payment gateway DAO.
937
     * @return A list of Thrift payment gateway objects.
938
     */
939
    private List<PaymentGateway> getThriftPaymentGateways(List<in.shop2020.payment.domain.PaymentGateway> daoPaymentGateways){
940
 
941
        List<PaymentGateway> paymentGateways = new ArrayList<PaymentGateway>();
942
        for(in.shop2020.payment.domain.PaymentGateway paymentGateway : daoPaymentGateways){
943
            paymentGateways.add(paymentGateway.getThriftPaymentGateway());
944
        }
945
        return paymentGateways;
946
    }
4619 mandeep.dh 947
 
3375 rajveer 948
	@Override
4619 mandeep.dh 949
	public boolean isAlive() {
950
	    try {
951
            return !paymentGatewayHandler.getActivePaymentGateways().isEmpty();
952
        } catch (Exception e) {
953
            logger.error("Could not fetch payment gateways", e);
954
        }
955
 
956
        return false;
3375 rajveer 957
	}
3956 chandransh 958
 
959
 
960
    @Override
961
    public void closeSession() throws TException {
962
        // TODO Auto-generated method stub      
963
    }
4008 mandeep.dh 964
 
965
    @Override
966
    public List<Long> getPaymentsRequiringExtraProcessing (
967
            ExtraPaymentProcessingType category) throws TException {
968
        return paymentRequiringExtraProcessingHandler.getPaymentIds(category);
969
    }
970
 
971
    @Override
972
    public void markPaymentAsProcessed(long paymentId,
973
            ExtraPaymentProcessingType category) throws TException {
974
        paymentRequiringExtraProcessingHandler.delete(paymentId, category);
975
    }
4141 chandransh 976
 
8907 rajveer 977
	@Override
8914 rajveer 978
	public PaymentStatus getPaymentStatusAtGateway(long merchantTxnId, double amount, boolean isDigital) throws PaymentException, TException {
8907 rajveer 979
	        logger.info("Attempting to get status of payment of amount " + amount + " corresponding to our transaction " + merchantTxnId);
980
	        List<in.shop2020.payment.domain.Payment> payments;
981
	        if(isDigital){
982
	        	payments = paymentHandler.getPaymentForRechargeTxn(merchantTxnId);
983
	        }else{
984
	        	payments = paymentHandler.getPaymentForTxn(merchantTxnId);
985
	        }
986
	        if(payments ==null || payments.isEmpty())
987
	            throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
988
 
989
	        if(payments ==null || payments.isEmpty())
990
	            throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
991
 
992
	        in.shop2020.payment.domain.Payment payment = payments.get(0);
993
	        long gatewayId = payment.getGatewayId();
994
 
995
	        if(gatewayId == HDFC_GATEWAY_ID){
996
	            return HdfcPaymentHandler.validateHdfcPayment(payment, amount);
997
	        }else if (gatewayId == EBS_GATEWAY_ID){
998
	            //return validateEbsPayment(payment, amount);
999
	        } 
1000
	        else if (HDFC_EMI_GATEWAY_IDS.contains(gatewayId)){
1001
	            //return validateHdfcEmiPayment(payment, amount);
1002
	        }
1003
 
1004
	        logger.error("We have an payment from unknown gateway: " + gatewayId);
8914 rajveer 1005
	        return PaymentStatus.INIT;
8907 rajveer 1006
	    }
1007
 
1008
 
1946 chandransh 1009
}