Subversion Repositories SmartDukaan

Rev

Rev 13352 | Rev 13545 | 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);
13518 amit.gupta 349
        }else if (gatewayId == PAYU_GATEWAY_ID) {
350
        	//Refund PayU
351
        	return refundPayUPayment(payment, amount);
352
 
6491 rajveer 353
        }
6482 rajveer 354
 
355
        logger.error("We have an captured payment from unknown gateway: " + gatewayId);
356
        return false;
357
    }
358
 
359
 
13518 amit.gupta 360
	private boolean refundPayUPayment (
361
			in.shop2020.payment.domain.Payment payment, double amount) throws PaymentException{
362
		Map<String, String> captureResult = PayuPaymentHandler.refundPayment(payment, amount);
363
		if(captureResult.containsKey(IPaymentHandler.ERROR)){
364
            payment.setDescription(captureResult.get(IPaymentHandler.ERROR));
365
            payment.setErrorCode(captureResult.get(IPaymentHandler.ERR_CODE));
366
            payment.setErrorTimestamp(new Date());
367
        	if(captureResult.get(IPaymentHandler.ERR_CODE).equals(Errors.CAPTURE_FAILURE)) {
368
                payment.setStatus(PaymentStatus.FAILED.getValue());
369
                paymentHandler.updatePayment(payment, captureResult);
370
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
371
        	} else {
372
        		logger.error("Capture attempt failed for Payu payment with id: " + payment.getId());
373
        		payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());
374
        		paymentHandler.updatePayment(payment, captureResult);
375
        		throw new PaymentException(106, captureResult.get(IPaymentHandler.ERROR));
376
        	}
377
        	return false;
378
        } else {
379
 
380
        	payment.setGatewayTxnStatus("Refund initiated");
381
            payment.setStatus(PaymentStatus.REFUNDED.getValue());
382
            payment.setRefundAmount(amount);
383
 
384
            SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
385
            captureResult.put(IPaymentHandler.REFUND_TXN_ID, captureResult.get(IPaymentHandler.REFUND_TXN_ID));
386
            captureResult.put(IPaymentHandler.REFUND_TIME, captureTimeDateFormatter.format(new Date()));
387
            paymentHandler.updatePayment(payment, captureResult);
388
            return true;
389
        }
390
	}
391
 
3616 chandransh 392
	@Override
2689 chandransh 393
    public long createRefund(long orderId, long merchantTxnId, double amount) throws PaymentException, TException{
6482 rajveer 394
		logger.info("Attempting to create a refund for order: " + orderId);
6488 rajveer 395
//		if(!refundPayment(merchantTxnId, amount, false)){
396
//			logger.warn("Not able to refund corresponding to the merchant txn " + merchantTxnId);
397
//		}
2689 chandransh 398
		List<in.shop2020.payment.domain.Payment> payments = paymentHandler.getPaymentForTxn(merchantTxnId);
399
		if(payments ==null || payments.isEmpty())
400
			throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
401
 
3010 chandransh 402
		in.shop2020.payment.domain.Payment payment = payments.get(0);
2689 chandransh 403
		if(payment.getStatus() != PaymentStatus.SUCCESS.getValue())
404
			throw new PaymentException(104, "No successful payments found corresponding to the merchant txn " + merchantTxnId);
405
 
2747 chandransh 406
		Refund refund = new Refund();
407
		refund.setOrderId(orderId);
408
		refund.setPaymentId(payment.getId());
409
		refund.setGatewayId(payment.getGatewayId());
410
		refund.setAmount(amount);
411
		refund.setAttempts(0);
412
		return refundHandler.createRefund(refund);
2689 chandransh 413
    }
414
 
3010 chandransh 415
    @Override
8618 rajveer 416
    public synchronized boolean capturePayment(long merchantTxnId, boolean isDigital) throws PaymentException, TException {
417
        logger.info("Attempting to capture payment corresponding to our transaction " + merchantTxnId + " and Is Digital is:" + isDigital);
418
        List<in.shop2020.payment.domain.Payment> payments;
419
        if(isDigital){
420
        	payments = paymentHandler.getPaymentForRechargeTxn(merchantTxnId);
421
        }else{
422
        	payments = paymentHandler.getPaymentForTxn(merchantTxnId);
423
        }
3010 chandransh 424
        if(payments ==null || payments.isEmpty())
425
            throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
426
 
427
        in.shop2020.payment.domain.Payment payment = payments.get(0);
428
        switch(PaymentStatus.findByValue(payment.getStatus())){
429
        case PENDING:
430
            logger.error("Attempt to capture a non-authorized payment");
431
            return false;
432
        case INIT:
433
            logger.warn("Attempt to capture a non-authorized payment");
434
            return false;
435
        case AUTHORIZED:
4421 mandeep.dh 436
        case CAPTURE_IN_PROCESS:
3010 chandransh 437
            //Actual work to be done in this case. Let the call proceed.
438
            break;
4421 mandeep.dh 439
        case PROVISIONALLY_CAPTURED:
440
            logger.info("Attempting to capture a payment that is provisonally captured but we can let the client proceed.");
441
            return true;
3010 chandransh 442
        case SUCCESS:
443
            logger.warn("Attempting to capture an already captured payment but we can let the client proceed.");
444
            return true;
445
        case FAILED:
446
            logger.error("Attempting to capture a failed payment");
447
            return false;
448
        }
449
 
450
        long gatewayId = payment.getGatewayId();
451
 
452
        if(gatewayId == HDFC_GATEWAY_ID){
453
            //Capture and update the HDFC payment
454
            return captureAndUpdateHdfcPayment(payment);
455
        } else if (gatewayId == EBS_GATEWAY_ID){
456
            //Capture and update the EBS payment
457
            return captureAndUpdateEbsPayment(payment);
6449 rajveer 458
        } else if (HDFC_EMI_GATEWAY_IDS.contains(gatewayId)){
3583 chandransh 459
            //Capture and update the HDFC EMI payment
460
            return captureAndUpdateHdfcEmiPayment(payment);
8488 amar.kumar 461
        } else if (gatewayId == EBAY_GATEWAY_ID || gatewayId == SNAPDEAL_GATEWAY_ID) {
8208 amar.kumar 462
        	return true;
13286 amit.gupta 463
        } else if (gatewayId == PAYU_GATEWAY_ID) {
13352 amit.gupta 464
        	return captureAndUpdatePayuPayment(payment);
3010 chandransh 465
        }
466
 
467
        logger.error("We have an authorized payment from unknown gateway: " + gatewayId);
468
        return false;
469
    }
470
 
13352 amit.gupta 471
    private boolean captureAndUpdatePayuPayment(in.shop2020.payment.domain.Payment payment)  throws PaymentException{
472
    	long merchantPaymentId = payment.getId();
473
 
474
        logger.info("Capturing Payu payment with id: " + merchantPaymentId);
475
        Map<String, String> attrMap = new HashMap<String, String>();
476
        Map<String, String> captureResult = PayuPaymentHandler.captureTransaction(merchantPaymentId + "", payment.getGatewayTxnId());
477
        if(captureResult.containsKey(IPaymentHandler.ERROR)){
478
            payment.setDescription(captureResult.get(IPaymentHandler.ERROR));
479
            payment.setErrorCode(captureResult.get(IPaymentHandler.ERR_CODE));
480
            payment.setErrorTimestamp(new Date());
481
        	if(captureResult.get(IPaymentHandler.ERR_CODE).equals(Errors.CAPTURE_FAILURE)) {
482
                payment.setStatus(PaymentStatus.FAILED.getValue());
483
                paymentHandler.updatePayment(payment, attrMap);
484
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
485
        	} else {
13518 amit.gupta 486
        		logger.error("Capture attempt failed for Payu payment with id: " + merchantPaymentId);
13352 amit.gupta 487
        		payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());
488
        		paymentHandler.updatePayment(payment, attrMap);
489
        		throw new PaymentException(106, captureResult.get(IPaymentHandler.ERROR));
490
        	}
491
        	return false;
492
        } else {
493
        	logger.info("Capture attempt successful for HDFC payment with id: " + merchantPaymentId);
494
            payment.setDescription("Payment Captured");
495
            payment.setGatewayTxnStatus("captured");
496
            payment.setStatus(PaymentStatus.SUCCESS.getValue());
497
            payment.setSuccessTimestamp(new Date());           
498
            payment.setReferenceCode(captureResult.get(PayuPaymentHandler.REF_NO));
499
            attrMap.put(IPaymentHandler.CAPTURE_TXN_ID, captureResult.get(IPaymentHandler.CAPTURE_TXN_ID));
500
            attrMap.put(IPaymentHandler.CAPTURE_REF_ID, captureResult.get(IPaymentHandler.CAPTURE_REF_ID));
501
            attrMap.put(IPaymentHandler.CAPTURE_AUTH_ID, captureResult.get(IPaymentHandler.CAPTURE_AUTH_ID));
502
 
503
            SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
504
            attrMap.put(HdfcPaymentHandler.CAPTURE_TIME, captureTimeDateFormatter.format(new Date()));
505
 
506
            paymentHandler.updatePayment(payment, attrMap);
507
            return true;
508
        }
13286 amit.gupta 509
	}
510
 
511
	@Override
3956 chandransh 512
    public boolean partiallyCapturePayment(long merchantTxnId, double amount, String xferBy, String xferTxnId, long xferDate) throws PaymentException, TException {
513
        logger.info("Attempting to partially capture payment corresponding to our transaction " + merchantTxnId);
514
        List<in.shop2020.payment.domain.Payment> payments = paymentHandler.getPaymentForTxn(merchantTxnId);
515
        if(payments ==null || payments.isEmpty())
516
            throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
517
 
518
        in.shop2020.payment.domain.Payment payment = payments.get(0);
519
        switch(PaymentStatus.findByValue(payment.getStatus())){
520
        case PENDING:
521
            // COD payments lie in this state before settlement.
522
        case INIT:
523
        case PARTIALLY_CAPTURED:
524
        case AUTHORIZED:
525
            // COD payments would not be in this state but we are processing
526
            // payments in this state as well for forward compatibility since
527
            // someday we'd want to be able to capture authorized CC payments
528
            // partially.
529
            break;
530
        case SUCCESS:
531
            logger.warn("Attempting to capture an already captured payment but we can let the client proceed.");
532
            return true;
533
        case FAILED:
534
            logger.error("Attempting to capture a failed payment");
535
            return false;
536
        }
537
        SimpleDateFormat mysqlDateFormatter = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
538
        String xferDateStr = mysqlDateFormatter.format(new Date(xferDate));
539
 
540
        return settleAndUpdateCodPayment(payment, amount, xferBy, xferTxnId, xferDateStr);
541
    }
542
 
3010 chandransh 543
    /**
544
     * Capture the HDFC payment represented by the given payment object. If the
545
     * capture attempt is not successful, we mark this payment as failed. We
546
     * don't retry or anything. We'll add the support of multiple attempts later
547
     * on.
548
     * 
549
     * @param payment The payment which has to be captured.
550
     * @return True if the payment attempt is successful, false if not.
4421 mandeep.dh 551
     * @throws PaymentException 
3010 chandransh 552
     */
4421 mandeep.dh 553
    private boolean captureAndUpdateHdfcPayment(in.shop2020.payment.domain.Payment payment) throws PaymentException {
3010 chandransh 554
        long merchantPaymentId = payment.getId();
555
        logger.info("Capturing HDFC payment with id: " + merchantPaymentId);
556
        Map<String, String> captureResult = HdfcPaymentHandler.capturePayment(payment);
557
        String captureStatus = captureResult.get(IPaymentHandler.STATUS);
558
        String gatewayStatus = captureResult.get(IPaymentHandler.GATEWAY_STATUS);
559
 
560
        Map<String, String> attrMap = new HashMap<String, String>();
561
        if (!captureStatus.trim().equals("0") 
562
                || !HdfcPaymentReturnStatus.CAPTURED.value().equals(gatewayStatus)) {
563
            // Failure
3616 chandransh 564
            logger.error("Capture attempt failed for HDFC payment with id: " + merchantPaymentId);
3010 chandransh 565
            String description = captureResult.get(IPaymentHandler.ERROR);
566
            String errorCode = captureResult.get(IPaymentHandler.ERR_CODE);
567
 
568
            payment.setDescription(description);
569
            payment.setErrorCode(errorCode);
570
            payment.setErrorTimestamp(new Date());
4421 mandeep.dh 571
 
572
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
573
                payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());
574
                paymentHandler.updatePayment(payment, attrMap);
575
                throw new PaymentException(106, "Could not capture due to connection issue");
576
            }
577
            else {
578
                payment.setStatus(PaymentStatus.FAILED.getValue());
579
                paymentHandler.updatePayment(payment, attrMap);
580
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
581
            }
582
 
3010 chandransh 583
            return false;
584
        } else {
585
            // Success
3616 chandransh 586
            logger.info("Capture attempt successful for HDFC payment with id: " + merchantPaymentId);
3010 chandransh 587
            payment.setDescription("Payment Captured");
588
            payment.setGatewayTxnStatus(gatewayStatus);
589
            payment.setStatus(PaymentStatus.SUCCESS.getValue());
590
            payment.setSuccessTimestamp(new Date());           
591
 
592
            attrMap.put(IPaymentHandler.CAPTURE_TXN_ID, captureResult.get(IPaymentHandler.CAPTURE_TXN_ID));
593
            attrMap.put(IPaymentHandler.CAPTURE_REF_ID, captureResult.get(IPaymentHandler.CAPTURE_REF_ID));
594
            attrMap.put(IPaymentHandler.CAPTURE_AUTH_ID, captureResult.get(IPaymentHandler.CAPTURE_AUTH_ID));
595
 
596
            SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
597
            attrMap.put(HdfcPaymentHandler.CAPTURE_TIME, captureTimeDateFormatter.format(new Date()));
598
 
599
            paymentHandler.updatePayment(payment, attrMap);
600
            return true;
601
          }
602
    }
603
 
604
    /**
3583 chandransh 605
     * Capture the HDFC EMI payment represented by the given payment object. If
606
     * the capture attempt is not successful, we mark this payment as failed. We
607
     * don't retry or anything. We'll add the support of multiple attempts later
608
     * on.
609
     * 
610
     * @param payment
611
     *            The payment which has to be captured.
612
     * @return True if the payment attempt is successful, false if not.
4421 mandeep.dh 613
     * @throws PaymentException 
3583 chandransh 614
     */
4421 mandeep.dh 615
    private boolean captureAndUpdateHdfcEmiPayment(in.shop2020.payment.domain.Payment payment) throws PaymentException{
3583 chandransh 616
        long merchantPaymentId = payment.getId();
617
        logger.info("Capturing HDFC payment with id: " + merchantPaymentId);
618
        Map<String, String> captureResult = HdfcEmiPaymentHandler.capturePayment(payment);
619
        String captureStatus = captureResult.get(IPaymentHandler.STATUS);
620
        String gatewayStatus = captureResult.get(IPaymentHandler.GATEWAY_STATUS);
621
 
622
        Map<String, String> attrMap = new HashMap<String, String>();
623
        if (!captureStatus.trim().equals("0") 
624
                || !HdfcPaymentReturnStatus.CAPTURED.value().equals(gatewayStatus)) {
625
            // Failure
3616 chandransh 626
            logger.error("Capture attempt failed for HDFC payment with id: " + merchantPaymentId);
3583 chandransh 627
            String description = captureResult.get(IPaymentHandler.ERROR);
628
            String errorCode = captureResult.get(IPaymentHandler.ERR_CODE);
629
 
630
            payment.setDescription(description);
631
            payment.setErrorCode(errorCode);
4421 mandeep.dh 632
            payment.setErrorTimestamp(new Date());                
633
 
634
            // Not marking payments as failed in case of connection issues
635
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
636
                payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());
637
                paymentHandler.updatePayment(payment, attrMap);
638
                throw new PaymentException(106, "Could not capture due to connection issue");
639
            }
640
            else {
641
                payment.setStatus(PaymentStatus.FAILED.getValue());
642
                paymentHandler.updatePayment(payment, attrMap);
643
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
644
            }
645
 
3583 chandransh 646
            return false;
647
        } else {
648
            // Success
3616 chandransh 649
            logger.info("Capture attempt successful for HDFC payment with id: " + merchantPaymentId);
3583 chandransh 650
            payment.setDescription("Payment Captured");
651
            payment.setGatewayTxnStatus(gatewayStatus);
652
            payment.setStatus(PaymentStatus.SUCCESS.getValue());
4421 mandeep.dh 653
            payment.setSuccessTimestamp(new Date());
3583 chandransh 654
 
655
            attrMap.put(IPaymentHandler.CAPTURE_TXN_ID, captureResult.get(IPaymentHandler.CAPTURE_TXN_ID));
656
            attrMap.put(IPaymentHandler.CAPTURE_REF_ID, captureResult.get(IPaymentHandler.CAPTURE_REF_ID));
657
            attrMap.put(IPaymentHandler.CAPTURE_AUTH_ID, captureResult.get(IPaymentHandler.CAPTURE_AUTH_ID));
658
 
659
            SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
660
            attrMap.put(HdfcPaymentHandler.CAPTURE_TIME, captureTimeDateFormatter.format(new Date()));
661
 
662
            paymentHandler.updatePayment(payment, attrMap);
663
            return true;
664
          }
665
    }
666
 
667
    /**
3010 chandransh 668
     * Capture the EBS payment represented by the given payment object. If the
669
     * capture attempt is not successful, we mark this payment as failed. We
670
     * don't retry or anything. We'll add the support of multiple attempts later
671
     * on.
672
     * 
673
     * @param payment The payment which has to be captured.
674
     * @return True if the payment attempt is successful, false if not.
4421 mandeep.dh 675
     * @throws PaymentException 
3010 chandransh 676
     */
4421 mandeep.dh 677
    private boolean captureAndUpdateEbsPayment(in.shop2020.payment.domain.Payment payment) throws PaymentException{
3010 chandransh 678
        Map<String, String> captureResult = EbsPaymentHandler.capturePayment(payment);
679
        String captureStatus = captureResult.get(EbsPaymentHandler.STATUS);
8650 anupam.sin 680
        for(String key : captureResult.keySet()) {
681
            logger.info("key : " + key + " value : " + captureResult.get(key));
682
        }
3010 chandransh 683
 
8650 anupam.sin 684
        logger.info("capture status : " + captureStatus);
685
 
3010 chandransh 686
        Map<String, String> attrMap = new HashMap<String, String>();
687
        if("".equals(captureStatus)){
688
            //Failure
3616 chandransh 689
            logger.error("Capture attempt failed for EBS payment with id: " + payment.getId());
3010 chandransh 690
            String description = captureResult.get(EbsPaymentHandler.ERROR);
691
            String errorCode = captureResult.get(EbsPaymentHandler.ERR_CODE);
4421 mandeep.dh 692
 
3010 chandransh 693
            payment.setDescription(description);
694
            payment.setErrorCode(errorCode);
695
            payment.setErrorTimestamp(new Date());
4421 mandeep.dh 696
 
697
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
698
                payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());            
699
                paymentHandler.updatePayment(payment, attrMap);
700
                throw new PaymentException(106, "Could not capture due to connection issue");
701
            }
702
            else {
703
                payment.setStatus(PaymentStatus.FAILED.getValue());            
704
                paymentHandler.updatePayment(payment, attrMap);
705
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
706
            }
707
 
3010 chandransh 708
            return false;
709
        }else{
710
            //Success
3616 chandransh 711
            logger.info("Capture attempt successful for EBS payment with id: " + payment.getId());
3010 chandransh 712
            payment.setGatewayTxnStatus(captureStatus);
713
            payment.setStatus(PaymentStatus.SUCCESS.getValue());
714
            payment.setSuccessTimestamp(new Date());
715
 
716
            attrMap.put(IPaymentHandler.CAPTURE_TXN_ID, captureResult.get(IPaymentHandler.CAPTURE_TXN_ID));
717
            attrMap.put(IPaymentHandler.CAPTURE_TIME, captureResult.get(IPaymentHandler.CAPTURE_TIME));
718
            paymentHandler.updatePayment(payment, attrMap);
719
            return true;
720
        }
721
    }
722
 
6482 rajveer 723
 
3010 chandransh 724
    /**
6482 rajveer 725
     * Refund the HDFC payment represented by the given payment object. If the
726
     * refund attempt is not successful, will not any action.
727
     * 
728
     * @param payment The payment which has to be captured.
729
     * @amount amount to be refunded
730
     * @return True if the payment attempt is successful, false if not.
731
     * @throws PaymentException 
732
     */
733
    private boolean refundHdfcPayment(in.shop2020.payment.domain.Payment payment, double amount) throws PaymentException {
734
        long merchantPaymentId = payment.getId();
735
        logger.info("Refunding HDFC payment with id: " + merchantPaymentId);
736
        Map<String, String> refundResult = HdfcPaymentHandler.refundPayment(payment, amount);
6486 rajveer 737
        String refundStatus = refundResult.get(IPaymentHandler.STATUS);
6482 rajveer 738
        String gatewayStatus = refundResult.get(IPaymentHandler.GATEWAY_STATUS);
739
 
740
        Map<String, String> attrMap = new HashMap<String, String>();
6486 rajveer 741
        if (!refundStatus.trim().equals("0") 
6482 rajveer 742
                || !HdfcPaymentReturnStatus.CAPTURED.value().equals(gatewayStatus)) {
6486 rajveer 743
 
744
        	logger.error("Refund attempt failed for HDFC payment with id: " + merchantPaymentId);
745
            String description = refundResult.get(IPaymentHandler.ERROR);
746
            String errorCode = refundResult.get(IPaymentHandler.ERR_CODE);
747
 
748
            payment.setDescription(description);
749
            payment.setErrorCode(errorCode);
750
            payment.setErrorTimestamp(new Date());
751
 
752
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
753
                //payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());
754
                //paymentHandler.updatePayment(payment, attrMap);
755
                throw new PaymentException(106, "Could not capture due to connection issue. Try Later");
756
            }
757
            else {
6491 rajveer 758
//                payment.setStatus(PaymentStatus.FAILED.getValue());
759
//                paymentHandler.updatePayment(payment, attrMap);
6486 rajveer 760
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
761
            }
762
 
6482 rajveer 763
            return false;
764
        } else {
765
            // Success
766
            logger.info("Refund attempt successful for HDFC payment with id: " + merchantPaymentId);
767
            payment.setDescription("Payment Refunded");
768
            payment.setGatewayTxnStatus(gatewayStatus);
6503 rajveer 769
            payment.setStatus(PaymentStatus.REFUNDED.getValue());    
770
            payment.setRefundAmount(amount);
6482 rajveer 771
 
6486 rajveer 772
            attrMap.put(IPaymentHandler.REFUND_TXN_ID, refundResult.get(IPaymentHandler.REFUND_TXN_ID));
773
            attrMap.put(IPaymentHandler.REFUND_REF_ID, refundResult.get(IPaymentHandler.REFUND_REF_ID));
774
            attrMap.put(IPaymentHandler.REFUND_AUTH_ID, refundResult.get(IPaymentHandler.REFUND_AUTH_ID));
6503 rajveer 775
            attrMap.put(IPaymentHandler.REFUND_AMNT, refundResult.get(IPaymentHandler.REFUND_AMNT));
776
 
6482 rajveer 777
            SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
6486 rajveer 778
            attrMap.put(HdfcPaymentHandler.REFUND_TIME, captureTimeDateFormatter.format(new Date()));
6482 rajveer 779
 
780
            paymentHandler.updatePayment(payment, attrMap);
781
            return true;
782
          }
783
    }
784
 
785
 
6491 rajveer 786
    /**
787
     * Refund the HDFC EMI payment represented by the given payment object. If
788
     * the capture attempt is not successful, we will not do anything.
789
     * 
790
     * @param payment
791
     *            The payment which has to be captured.
792
     * @return True if the payment attempt is successful, false if not.
793
     * @throws PaymentException 
794
     */
795
    private boolean refundHdfcEmiPayment(in.shop2020.payment.domain.Payment payment, double amount) throws PaymentException{
796
        long merchantPaymentId = payment.getId();
797
        logger.info("Refunding HDFC payment with id: " + merchantPaymentId);
798
        Map<String, String> refundResult = HdfcEmiPaymentHandler.refundPayment(payment, amount);
799
        String refundStatus = refundResult.get(IPaymentHandler.STATUS);
800
        String gatewayStatus = refundResult.get(IPaymentHandler.GATEWAY_STATUS);
801
 
802
        Map<String, String> attrMap = new HashMap<String, String>();
803
        if (!refundStatus.trim().equals("0") 
804
                || !HdfcPaymentReturnStatus.CAPTURED.value().equals(gatewayStatus)) {
805
            // Failure
806
            logger.error("Refund attempt failed for HDFC payment with id: " + merchantPaymentId);
807
            String description = refundResult.get(IPaymentHandler.ERROR);
808
            String errorCode = refundResult.get(IPaymentHandler.ERR_CODE);
809
 
810
            payment.setDescription(description);
811
            payment.setErrorCode(errorCode);
812
            payment.setErrorTimestamp(new Date());                
813
 
814
            // Not marking payments as failed in case of connection issues
815
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
816
             //   payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());
817
             //   paymentHandler.updatePayment(payment, attrMap);
818
                throw new PaymentException(106, "Could not capture due to connection issue");
819
            }
820
            else {
821
              //  payment.setStatus(PaymentStatus.FAILED.getValue());
822
              //  paymentHandler.updatePayment(payment, attrMap);
823
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
824
            }
825
 
826
            return false;
827
        } else {
828
            // Success
829
            logger.info("Refund attempt successful for HDFC payment with id: " + merchantPaymentId);
830
            payment.setDescription("Payment Refunded");
831
            payment.setGatewayTxnStatus(gatewayStatus);
832
            payment.setStatus(PaymentStatus.REFUNDED.getValue());           
6503 rajveer 833
            payment.setRefundAmount(amount);
6491 rajveer 834
 
835
            attrMap.put(IPaymentHandler.REFUND_TXN_ID, refundResult.get(IPaymentHandler.REFUND_TXN_ID));
836
            attrMap.put(IPaymentHandler.REFUND_REF_ID, refundResult.get(IPaymentHandler.REFUND_REF_ID));
837
            attrMap.put(IPaymentHandler.REFUND_AUTH_ID, refundResult.get(IPaymentHandler.REFUND_AUTH_ID));
6503 rajveer 838
            attrMap.put(IPaymentHandler.REFUND_AMNT, refundResult.get(IPaymentHandler.REFUND_AMNT));
839
 
6491 rajveer 840
            SimpleDateFormat captureTimeDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
841
            attrMap.put(HdfcPaymentHandler.REFUND_TIME, captureTimeDateFormatter.format(new Date()));
842
 
843
            paymentHandler.updatePayment(payment, attrMap);
844
            return true;
845
          }
846
    }
6482 rajveer 847
 
848
    /**
6491 rajveer 849
     * Refund the EBS payment represented by the given payment object. If the
850
     * capture attempt is not successful, we will ignore. We don't retry or anything. 
851
     * We'll add the support of multiple attempts later on.
852
     * 
853
     * @param payment The payment which has to be captured.
854
     * @amount Amount to be refunded
855
     * @return True if the payment attempt is successful, false if not.
856
     * @throws PaymentException 
857
     */
858
    private boolean refundEbsPayment(in.shop2020.payment.domain.Payment payment, double amount) throws PaymentException{
859
        Map<String, String> refundResult = EbsPaymentHandler.refundPayment(payment, amount);
860
        String refundStatus = refundResult.get(EbsPaymentHandler.STATUS);
861
 
862
        Map<String, String> attrMap = new HashMap<String, String>();
863
        if("".equals(refundStatus)){
864
            //Failure
865
            logger.error("Refund attempt failed for EBS payment with id: " + payment.getId());
866
            String description = refundResult.get(EbsPaymentHandler.ERROR);
867
            String errorCode = refundResult.get(EbsPaymentHandler.ERR_CODE);
868
 
869
            payment.setDescription(description);
870
            payment.setErrorCode(errorCode);
871
            payment.setErrorTimestamp(new Date());
872
 
873
            if (IPaymentHandler.Errors.CONN_FAILURE.code.equals(errorCode)) {
874
//                payment.setStatus(PaymentStatus.CAPTURE_IN_PROCESS.getValue());            
875
//                paymentHandler.updatePayment(payment, attrMap);
876
                throw new PaymentException(106, "Could not capture due to connection issue");
877
            }
878
            else {
879
//                payment.setStatus(PaymentStatus.FAILED.getValue());            
880
//                paymentHandler.updatePayment(payment, attrMap);
881
                persistPaymentRequiringExtraProcessing(payment, ExtraPaymentProcessingType.FAILED_PAYMENTS);
882
            }
883
 
884
            return false;
885
        }else{
886
            //Success
887
            logger.info("Refund attempt successful for EBS payment with id: " + payment.getId());
888
            payment.setGatewayTxnStatus(refundStatus);
889
            payment.setStatus(PaymentStatus.REFUNDED.getValue());
6503 rajveer 890
            payment.setRefundAmount(amount);
6491 rajveer 891
 
892
            attrMap.put(IPaymentHandler.REFUND_TXN_ID, refundResult.get(IPaymentHandler.REFUND_TXN_ID));
893
            attrMap.put(IPaymentHandler.REFUND_TIME, refundResult.get(IPaymentHandler.REFUND_TIME));
894
            paymentHandler.updatePayment(payment, attrMap);
895
            return true;
896
        }
897
    }
898
 
899
 
900
    /**
3956 chandransh 901
     * Updates the settlement details of COD payments. Sets payment status as
902
     * either PARTIALLY CAPTURED or SUCCESS depending on whether the complete
903
     * amount has been captured. Other parameters are set as attributes.
904
     * 
905
     * @param payment
906
     *            The payment which needs to be updated.
907
     * @param amount
908
     *            Amount that has been captured.
909
     * @param xferBy
910
     *            Entity which transferred the money.
911
     * @param xferTxnId
912
     *            Transaction Id of the transfer.
913
     * @param xferDateStr
914
     *            Date on which the transfer took place.
915
     * @return true if the payment details were updated successfully.
916
     * @throws PaymentException
917
     *             if the captured amount will become more than the actual
918
     *             amount after this update.
919
     */
920
    private boolean settleAndUpdateCodPayment(in.shop2020.payment.domain.Payment payment, double amount, String xferBy, String xferTxnId, String xferDateStr) throws PaymentException{
921
        Map<String, String> attrMap = payment.getAttributeMap();
922
 
923
        double captureAmount = 0;
924
        String captureAmntStr = attrMap.get(IPaymentHandler.CAPTURE_AMNT);
925
        if(captureAmntStr != null)
926
            captureAmount = Double.parseDouble(captureAmntStr);
927
        captureAmount += amount;
5051 rajveer 928
        // If capture amount higher than payment amount by more than 50 paisa,
929
        // there is some issue and we should raise exception.
930
        if(captureAmount - payment.getAmount() > 0.5){
931
        	throw new PaymentException(105, "We've got a settlement request for an amount which is more than the transaction value.");
932
        }
3956 chandransh 933
 
5051 rajveer 934
        // If capture amount differs from payment amount by less than 50 paisa, lets mark the payment as successful. 
935
        // Else we can safely assume there will be some more orders for the payment, leading to make the payment as partially captured.
936
        if(Math.abs(captureAmount - payment.getAmount()) < 0.5){
937
        	payment.setStatus(PaymentStatus.SUCCESS.getValue());
938
        }else {
939
        	payment.setStatus(PaymentStatus.PARTIALLY_CAPTURED.getValue());   
3956 chandransh 940
        }
941
        payment.setSuccessTimestamp(new Date());
942
        attrMap.put(IPaymentHandler.CAPTURE_AMNT, captureAmount + "");
943
        attrMap.put(IPaymentHandler.XFER_TXN_ID, xferTxnId);
944
        attrMap.put(IPaymentHandler.XFER_TXN_DATE, xferDateStr);
945
        attrMap.put(IPaymentHandler.XFER_BY, xferBy);
946
        paymentHandler.updatePayment(payment, attrMap);
947
        return true;
948
    }
949
 
950
    /**
3010 chandransh 951
     * Creates a list of thrift payment objects corresponding to a list of
952
     * payment data objects.
953
     * 
954
     * @param daoPayments
955
     *            A list of payment DAO.
956
     * @return A list of Thrift payment objects.
957
     */
958
    private List<Payment> getThriftPayments(List<in.shop2020.payment.domain.Payment> daoPayments){
959
 
960
        List<Payment> payments = new ArrayList<Payment>();
961
        for(in.shop2020.payment.domain.Payment payment : daoPayments){
962
            payments.add(payment.getThriftPayment());
963
        }
964
        return payments;
965
    }
3375 rajveer 966
 
4600 varun.gupt 967
    /**
968
     * Creates a list of thrift payment gateway objects corresponding to a list of
969
     * payment gateway data objects.
970
     * 
971
     * @param daoPaymentGateways
972
     *            A list of payment gateway DAO.
973
     * @return A list of Thrift payment gateway objects.
974
     */
975
    private List<PaymentGateway> getThriftPaymentGateways(List<in.shop2020.payment.domain.PaymentGateway> daoPaymentGateways){
976
 
977
        List<PaymentGateway> paymentGateways = new ArrayList<PaymentGateway>();
978
        for(in.shop2020.payment.domain.PaymentGateway paymentGateway : daoPaymentGateways){
979
            paymentGateways.add(paymentGateway.getThriftPaymentGateway());
980
        }
981
        return paymentGateways;
982
    }
4619 mandeep.dh 983
 
3375 rajveer 984
	@Override
4619 mandeep.dh 985
	public boolean isAlive() {
986
	    try {
987
            return !paymentGatewayHandler.getActivePaymentGateways().isEmpty();
988
        } catch (Exception e) {
989
            logger.error("Could not fetch payment gateways", e);
990
        }
991
 
992
        return false;
3375 rajveer 993
	}
3956 chandransh 994
 
995
 
996
    @Override
997
    public void closeSession() throws TException {
998
        // TODO Auto-generated method stub      
999
    }
4008 mandeep.dh 1000
 
1001
    @Override
1002
    public List<Long> getPaymentsRequiringExtraProcessing (
1003
            ExtraPaymentProcessingType category) throws TException {
1004
        return paymentRequiringExtraProcessingHandler.getPaymentIds(category);
1005
    }
1006
 
1007
    @Override
1008
    public void markPaymentAsProcessed(long paymentId,
1009
            ExtraPaymentProcessingType category) throws TException {
1010
        paymentRequiringExtraProcessingHandler.delete(paymentId, category);
1011
    }
4141 chandransh 1012
 
8907 rajveer 1013
	@Override
8914 rajveer 1014
	public PaymentStatus getPaymentStatusAtGateway(long merchantTxnId, double amount, boolean isDigital) throws PaymentException, TException {
8907 rajveer 1015
	        logger.info("Attempting to get status of payment of amount " + amount + " corresponding to our transaction " + merchantTxnId);
1016
	        List<in.shop2020.payment.domain.Payment> payments;
1017
	        if(isDigital){
1018
	        	payments = paymentHandler.getPaymentForRechargeTxn(merchantTxnId);
1019
	        }else{
1020
	        	payments = paymentHandler.getPaymentForTxn(merchantTxnId);
1021
	        }
1022
	        if(payments ==null || payments.isEmpty())
1023
	            throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
1024
 
1025
	        if(payments ==null || payments.isEmpty())
1026
	            throw new PaymentException(104, "No payments found corresponding to the merchant txn " + merchantTxnId);
1027
 
1028
	        in.shop2020.payment.domain.Payment payment = payments.get(0);
1029
	        long gatewayId = payment.getGatewayId();
1030
 
1031
	        if(gatewayId == HDFC_GATEWAY_ID){
1032
	            return HdfcPaymentHandler.validateHdfcPayment(payment, amount);
1033
	        }else if (gatewayId == EBS_GATEWAY_ID){
1034
	            //return validateEbsPayment(payment, amount);
1035
	        } 
1036
	        else if (HDFC_EMI_GATEWAY_IDS.contains(gatewayId)){
1037
	            //return validateHdfcEmiPayment(payment, amount);
1038
	        }
1039
 
1040
	        logger.error("We have an payment from unknown gateway: " + gatewayId);
8914 rajveer 1041
	        return PaymentStatus.INIT;
8907 rajveer 1042
	    }
1043
 
1044
 
1946 chandransh 1045
}