Subversion Repositories SmartDukaan

Rev

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