Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
23724 amit.gupta 1
package com.smartdukaan.cron.scheduled;
23723 amit.gupta 2
 
23739 amit.gupta 3
import java.sql.Timestamp;
23724 amit.gupta 4
import java.time.LocalDate;
5
import java.time.LocalDateTime;
6
import java.time.temporal.ChronoUnit;
7
import java.util.ArrayList;
8
import java.util.Arrays;
23723 amit.gupta 9
import java.util.HashMap;
23724 amit.gupta 10
import java.util.List;
23723 amit.gupta 11
import java.util.Map;
23724 amit.gupta 12
import java.util.stream.Collectors;
23723 amit.gupta 13
 
23755 amit.gupta 14
import org.apache.logging.log4j.LogManager;
15
import org.apache.logging.log4j.Logger;
23723 amit.gupta 16
import org.springframework.beans.factory.annotation.Autowired;
23724 amit.gupta 17
import org.springframework.beans.factory.annotation.Value;
23723 amit.gupta 18
import org.springframework.stereotype.Component;
23724 amit.gupta 19
import org.springframework.transaction.annotation.Transactional;
23723 amit.gupta 20
 
23724 amit.gupta 21
import com.spice.profitmandi.common.enumuration.RechargeStatus;
22
import com.spice.profitmandi.common.model.RechargeCredential;
23
import com.spice.profitmandi.dao.entity.dtr.DailyRecharge;
24
import com.spice.profitmandi.dao.entity.dtr.RechargeProvider;
25
import com.spice.profitmandi.dao.entity.dtr.RechargeProviderCreditWalletHistory;
26
import com.spice.profitmandi.dao.entity.dtr.RechargeTransaction;
27
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
28
import com.spice.profitmandi.dao.entity.fofo.Purchase;
29
import com.spice.profitmandi.dao.repository.dtr.DailyRechargeRepository;
30
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderCreditWalletHistoryRepository;
31
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderRepository;
32
import com.spice.profitmandi.dao.repository.dtr.RechargeTransactionRepository;
33
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
34
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
35
import com.spice.profitmandi.service.recharge.provider.OxigenRechargeProviderService;
36
import com.spice.profitmandi.service.recharge.provider.ThinkWalnutDigitalRechargeProviderService;
37
import com.spice.profitmandi.service.scheme.SchemeService;
23739 amit.gupta 38
import com.spice.profitmandi.service.wallet.WalletService;
23723 amit.gupta 39
 
23739 amit.gupta 40
import in.shop2020.model.v1.order.WalletReferenceType;
41
 
23723 amit.gupta 42
@Component
23724 amit.gupta 43
@Transactional(rollbackFor = Throwable.class)
23723 amit.gupta 44
public class ScheduledTasks {
45
 
23724 amit.gupta 46
	@Value("${oxigen.recharge.transaction.url}")
47
	private String oxigenRechargeTransactionUrl;
23723 amit.gupta 48
 
23724 amit.gupta 49
	@Value("${oxigen.recharge.enquiry.url}")
50
	private String oxigenRechargeEnquiryUrl;
23723 amit.gupta 51
 
23724 amit.gupta 52
	@Value("${oxigen.recharge.auth.key}")
53
	private String oxigenRechargeAuthKey;
54
 
55
	@Value("${oxigen.recharge.validation.url}")
56
	private String oxigenRechargeValidationUrl;
57
 
58
	@Value("${oxigen.recharge.validation.auth.key}")
59
	private String oxigenRechargeValidationAuthKey;
60
 
61
	@Value("${think.walnut.digital.recharge.transaction.mobile.url}")
62
	private String thinkWalnutDigitalRechargeTransactionMobileUrl;
63
 
64
	@Value("${think.walnut.digital.recharge.transaction.dth.url}")
65
	private String thinkWalnutDigitalRechargeTransactionDthUrl;
66
 
67
	@Value("${think.walnut.digital.recharge.enquiry.url}")
68
	private String thinkWalnutDigitalRechargeEnquiryUrl;
69
 
70
	@Value("${think.walnut.digital.recharge.balance.url}")
71
	private String thinkWalnutDigitalRechargeBalanceUrl;
72
 
73
	@Value("${think.walnut.digital.recharge.username}")
74
	private String thinkWalnutDigitalRechargeUserName;
75
 
76
	@Value("${think.walnut.digital.recharge.password}")
77
	private String thinkWalnutDigitalRechargePassword;
78
 
79
	@Value("${think.walnut.digital.recharge.auth.key}")
80
	private String thinkWalnutDigitalRechargeAuthKey;
81
 
23723 amit.gupta 82
	@Autowired
23724 amit.gupta 83
	private PurchaseRepository purchaseRepository;
84
 
85
	@Autowired
86
	private SchemeService schemeService;
87
 
88
	@Autowired
89
	private RechargeTransactionRepository rechargeTransactionRepository;
90
 
91
	@Autowired
92
	private RechargeProviderCreditWalletHistoryRepository rechargeProviderCreditWalletHistoryRepository;
93
 
94
	@Autowired
95
	private FofoOrderRepository fofoOrderRepository;
23739 amit.gupta 96
 
97
	@Autowired
98
	private WalletService walletService;
23724 amit.gupta 99
 
100
	@Autowired
101
	private ThinkWalnutDigitalRechargeProviderService thinkWalnutDigitalRechargeProviderService;
102
 
103
	@Autowired
104
	private OxigenRechargeProviderService oxigenRechargeProviderService;
105
 
106
	@Autowired
107
	private RechargeProviderRepository rechargeProviderRepository;
108
 
109
	@Autowired
110
	private DailyRechargeRepository dailyRechargeRepository;
111
 
112
	@Value("${prod}")
113
	private boolean prod;
114
 
23755 amit.gupta 115
	private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
23724 amit.gupta 116
 
117
 
118
	public void generateDailyRecharge() {
119
		List<RechargeProviderCreditWalletHistory> allCreditHistory = rechargeProviderCreditWalletHistoryRepository
120
				.selectAll(0, 2000);
121
		List<RechargeProvider> rechargeProviders = rechargeProviderRepository.selectAll();
122
		rechargeProviders.stream().forEach(x -> x.setAmount(0));
123
 
124
		rechargeProviders.stream().forEach(x -> {
125
			Map<LocalDate, List<RechargeProviderCreditWalletHistory>> dateWiseProviderCreditsMap = allCreditHistory
126
					.stream().filter(z -> z.getProviderId() == x.getId())
127
					.collect(Collectors.groupingBy(x1 -> x1.getReceiveTimestamp().toLocalDate()));
128
 
129
			LOGGER.info("dateWiseProviderCreditsMap -- {}", dateWiseProviderCreditsMap);
130
			LocalDate endDate = LocalDate.now().plusDays(1);
131
			float previousDayClosing = 0;
132
			LocalDate date = LocalDate.of(2018, 4, 6);
133
			while (date.isBefore(endDate)) {
134
				List<RechargeTransaction> dateWiseRechargeTransactions = rechargeTransactionRepository
135
						.selectAllBetweenTimestamp(Arrays.asList(RechargeStatus.values()), date.atStartOfDay(),
136
								date.plusDays(1).atStartOfDay());
137
 
138
				List<RechargeTransaction> successfulTransactions = dateWiseRechargeTransactions.stream()
139
						.filter(y -> y.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());
140
 
141
				float dailyAmount = 0;
142
				float totalCommission = 0;
143
				for (RechargeTransaction rechargeTransaction : successfulTransactions) {
144
					if (rechargeTransaction.getProviderId() == x.getId()) {
145
						dailyAmount += rechargeTransaction.getAmount();
146
						totalCommission += rechargeTransaction.getCommission();
147
					}
148
				}
149
 
150
				List<RechargeProviderCreditWalletHistory> rechargeHistoryList = dateWiseProviderCreditsMap.get(date);
151
				float dailyWalletRecharge = 0;
152
				if (rechargeHistoryList != null) {
153
					for (RechargeProviderCreditWalletHistory rechargeProviderCreditWalletHistory : rechargeHistoryList) {
154
						if (rechargeProviderCreditWalletHistory.getProviderId() == x.getId()) {
155
							dailyWalletRecharge += rechargeProviderCreditWalletHistory.getAmount();
156
						}
157
					}
158
				}
159
				if (dailyAmount > 0 || dailyWalletRecharge > 0) {
160
					DailyRecharge dailyRecharge = null;
161
					try {
162
						dailyRecharge = dailyRechargeRepository.selectByProviderIdAndCreateDate(x.getId(), date);
163
					} catch (Exception e) {
164
						LOGGER.info("Could not find Recharge entry");
165
					}
166
					if (dailyRecharge == null) {
167
						dailyRecharge = new DailyRecharge();
168
						dailyRecharge.setCreateDate(date);
169
					}
170
					dailyRecharge.setOpeningBalance(previousDayClosing);
171
					dailyRecharge.setProviderId(x.getId());
172
					dailyRecharge.setWalletRechargeAmount(dailyWalletRecharge);
173
					dailyRecharge.setTotalAmount(dailyAmount);
174
					dailyRecharge.setTotalCommission(totalCommission);
175
					float closingBalance = dailyRecharge.getOpeningBalance() + dailyWalletRecharge - dailyAmount;
176
					dailyRecharge.setClosingBalance(closingBalance);
177
					dailyRechargeRepository.persist(dailyRecharge);
178
					x.setAmount(x.getAmount() + dailyRecharge.getClosingBalance() - dailyRecharge.getOpeningBalance());
179
					previousDayClosing = dailyRecharge.getClosingBalance();
180
				}
181
				date = date.plusDays(1);
182
			}
183
			rechargeProviderRepository.persist(x);
184
		});
23761 amit.gupta 185
		LOGGER.info("finished generating daily recharge");
23724 amit.gupta 186
	}
187
 
23738 amit.gupta 188
	public void reconcileRecharge() throws Exception {
23724 amit.gupta 189
		LocalDateTime fromDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).minusDays(30);
190
		LocalDateTime toDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
191
		List<RechargeStatus> nonSuccessRechargeStatuses = new ArrayList<>(Arrays.asList(RechargeStatus.values()));
192
		LOGGER.info("nonSuccessRechargeStatuses {} ", nonSuccessRechargeStatuses);
193
		nonSuccessRechargeStatuses.remove(RechargeStatus.SUCCESS);
194
		nonSuccessRechargeStatuses.remove(RechargeStatus.FAILED);
195
		RechargeCredential thinkWalnutDigitalRechargeEnquiryCredential = new RechargeCredential();
196
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUrl(thinkWalnutDigitalRechargeEnquiryUrl);
197
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUserName(thinkWalnutDigitalRechargeUserName);
198
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargePassword(thinkWalnutDigitalRechargePassword);
199
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeAuthKey(thinkWalnutDigitalRechargeAuthKey);
200
		Map<String, RechargeStatus> requestRechargeStatusChanged = new HashMap<>();
201
		List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository
202
				.selectAllBetweenTimestamp(nonSuccessRechargeStatuses, fromDate, toDate);
203
		for (RechargeTransaction rechargeTransaction : rechargeTransactions) {
204
			try {
205
				int providerId = rechargeTransaction.getProviderId();
206
				if (providerId == 1) {
207
					oxigenRechargeProviderService.doCheckStatusRequest(oxigenRechargeEnquiryUrl, oxigenRechargeAuthKey,
208
							rechargeTransaction);
209
				} else if (providerId == 2) {
210
					thinkWalnutDigitalRechargeProviderService
211
							.doCheckStatusRequest(thinkWalnutDigitalRechargeEnquiryCredential, rechargeTransaction);
212
				}
213
				if (rechargeTransaction.getStatus().equals(RechargeStatus.SUCCESS)
214
						|| rechargeTransaction.getStatus().equals(RechargeStatus.FAILED)) {
215
					requestRechargeStatusChanged.put(rechargeTransaction.getRequestId(),
216
							rechargeTransaction.getStatus());
217
				}
218
			} catch (Exception e) {
219
				LOGGER.info("Could not check status for Request {}", rechargeTransaction.getRequestId());
220
			}
221
		}
23738 amit.gupta 222
		LOGGER.info("Reconcile recharge ran successfully");
23724 amit.gupta 223
	}
224
 
23738 amit.gupta 225
	public void processScheme() throws Exception {
23724 amit.gupta 226
		LocalDateTime fromDate = LocalDateTime.now().minusDays(15);
227
		LOGGER.info("Started execution at {}", LocalDateTime.now());
228
		List<Purchase> purchases = purchaseRepository.selectFromPurchaseCompleteDate(fromDate);
229
		for (Purchase purchase : purchases) {
230
			try {
231
				schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
232
			} catch (Exception e) {
233
				LOGGER.error("Error while processing purchase {} for scheme In ", purchase.getId());
234
				e.printStackTrace();
235
 
236
			}
237
		}
238
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(fromDate);
239
		for (FofoOrder fofoOrder : fofoOrders) {
240
			try {
241
				schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
242
			} catch (Exception e) {
243
				LOGGER.error("Error while processing sale order {} for scheme Out", fofoOrder.getId());
244
			}
245
		}
246
		LOGGER.info("Schemes process successfully.");
247
	}
23739 amit.gupta 248
 
249
	public void processRechargeCashback() throws Throwable {
23761 amit.gupta 250
		LocalDateTime cashbackTime = LocalDateTime.now();
251
		int referenceId = (int)Timestamp.valueOf(cashbackTime).getTime()/1000;
23739 amit.gupta 252
		List<RechargeTransaction> pendingTransactions = rechargeTransactionRepository.getPendingCashBackRehargeTransactions();
23761 amit.gupta 253
		Map<Object, Double> totalRetailerCashbacks = pendingTransactions.stream().collect(Collectors.groupingBy(x->x.getRetailerId(), Collectors.summingDouble(x->x.getCommission())));
23739 amit.gupta 254
		for (Map.Entry<Object, Double>totalRetailerCashback : totalRetailerCashbacks.entrySet()) {
255
			int retailerId = (Integer)totalRetailerCashback.getKey();
256
			float amount = totalRetailerCashback.getValue().floatValue();
23762 amit.gupta 257
			if(Math.round(amount) > 0) {
258
				walletService.addAmountToWallet(retailerId, referenceId, WalletReferenceType.CASHBACK, "Recharge Cashback", Math.round(amount));
259
			}
23739 amit.gupta 260
		}
23761 amit.gupta 261
		for(RechargeTransaction rt : pendingTransactions) {
262
			rt.setCashbackTimestamp(cashbackTime);
263
			rt.setCashbackReference(referenceId);
264
			rechargeTransactionRepository.persist(rt);
265
		}
23739 amit.gupta 266
		LOGGER.info("Cashbacks for Recharge processed Successfully");
267
	}
23724 amit.gupta 268
 
269
}