Subversion Repositories SmartDukaan

Rev

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