Subversion Repositories SmartDukaan

Rev

Rev 23933 | Rev 24002 | 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
 
23929 amit.gupta 3
import java.io.PrintStream;
23739 amit.gupta 4
import java.sql.Timestamp;
23724 amit.gupta 5
import java.time.LocalDate;
6
import java.time.LocalDateTime;
7
import java.time.temporal.ChronoUnit;
8
import java.util.ArrayList;
9
import java.util.Arrays;
23723 amit.gupta 10
import java.util.HashMap;
23724 amit.gupta 11
import java.util.List;
23723 amit.gupta 12
import java.util.Map;
23724 amit.gupta 13
import java.util.stream.Collectors;
23723 amit.gupta 14
 
23929 amit.gupta 15
import org.apache.commons.csv.CSVFormat;
16
import org.apache.commons.csv.CSVPrinter;
17
import org.apache.commons.io.output.ByteArrayOutputStream;
23755 amit.gupta 18
import org.apache.logging.log4j.LogManager;
19
import org.apache.logging.log4j.Logger;
23723 amit.gupta 20
import org.springframework.beans.factory.annotation.Autowired;
23933 amit.gupta 21
import org.springframework.beans.factory.annotation.Qualifier;
23724 amit.gupta 22
import org.springframework.beans.factory.annotation.Value;
23929 amit.gupta 23
import org.springframework.core.io.ByteArrayResource;
24
import org.springframework.mail.javamail.JavaMailSender;
23723 amit.gupta 25
import org.springframework.stereotype.Component;
23724 amit.gupta 26
import org.springframework.transaction.annotation.Transactional;
23723 amit.gupta 27
 
23724 amit.gupta 28
import com.spice.profitmandi.common.enumuration.RechargeStatus;
23929 amit.gupta 29
import com.spice.profitmandi.common.model.CustomRetailer;
23724 amit.gupta 30
import com.spice.profitmandi.common.model.RechargeCredential;
23929 amit.gupta 31
import com.spice.profitmandi.common.util.FormattingUtils;
32
import com.spice.profitmandi.common.util.Utils;
23724 amit.gupta 33
import com.spice.profitmandi.dao.entity.dtr.DailyRecharge;
34
import com.spice.profitmandi.dao.entity.dtr.RechargeProvider;
35
import com.spice.profitmandi.dao.entity.dtr.RechargeProviderCreditWalletHistory;
36
import com.spice.profitmandi.dao.entity.dtr.RechargeTransaction;
37
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
23929 amit.gupta 38
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
23724 amit.gupta 39
import com.spice.profitmandi.dao.entity.fofo.Purchase;
23929 amit.gupta 40
import com.spice.profitmandi.dao.entity.transaction.Order;
23724 amit.gupta 41
import com.spice.profitmandi.dao.repository.dtr.DailyRechargeRepository;
23929 amit.gupta 42
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
23724 amit.gupta 43
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderCreditWalletHistoryRepository;
44
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderRepository;
45
import com.spice.profitmandi.dao.repository.dtr.RechargeTransactionRepository;
46
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
47
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
23929 amit.gupta 48
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
49
import com.spice.profitmandi.service.inventory.InventoryService;
23724 amit.gupta 50
import com.spice.profitmandi.service.recharge.provider.OxigenRechargeProviderService;
51
import com.spice.profitmandi.service.recharge.provider.ThinkWalnutDigitalRechargeProviderService;
52
import com.spice.profitmandi.service.scheme.SchemeService;
23929 amit.gupta 53
import com.spice.profitmandi.service.transaction.TransactionService;
54
import com.spice.profitmandi.service.user.RetailerService;
23739 amit.gupta 55
import com.spice.profitmandi.service.wallet.WalletService;
23723 amit.gupta 56
 
23739 amit.gupta 57
import in.shop2020.model.v1.order.WalletReferenceType;
58
 
23723 amit.gupta 59
@Component
23724 amit.gupta 60
@Transactional(rollbackFor = Throwable.class)
23723 amit.gupta 61
public class ScheduledTasks {
62
 
23724 amit.gupta 63
	@Value("${oxigen.recharge.transaction.url}")
64
	private String oxigenRechargeTransactionUrl;
23723 amit.gupta 65
 
23724 amit.gupta 66
	@Value("${oxigen.recharge.enquiry.url}")
67
	private String oxigenRechargeEnquiryUrl;
23723 amit.gupta 68
 
23724 amit.gupta 69
	@Value("${oxigen.recharge.auth.key}")
70
	private String oxigenRechargeAuthKey;
71
 
72
	@Value("${oxigen.recharge.validation.url}")
73
	private String oxigenRechargeValidationUrl;
74
 
75
	@Value("${oxigen.recharge.validation.auth.key}")
76
	private String oxigenRechargeValidationAuthKey;
77
 
78
	@Value("${think.walnut.digital.recharge.transaction.mobile.url}")
79
	private String thinkWalnutDigitalRechargeTransactionMobileUrl;
80
 
81
	@Value("${think.walnut.digital.recharge.transaction.dth.url}")
82
	private String thinkWalnutDigitalRechargeTransactionDthUrl;
83
 
84
	@Value("${think.walnut.digital.recharge.enquiry.url}")
85
	private String thinkWalnutDigitalRechargeEnquiryUrl;
86
 
87
	@Value("${think.walnut.digital.recharge.balance.url}")
88
	private String thinkWalnutDigitalRechargeBalanceUrl;
89
 
90
	@Value("${think.walnut.digital.recharge.username}")
91
	private String thinkWalnutDigitalRechargeUserName;
92
 
93
	@Value("${think.walnut.digital.recharge.password}")
94
	private String thinkWalnutDigitalRechargePassword;
95
 
96
	@Value("${think.walnut.digital.recharge.auth.key}")
97
	private String thinkWalnutDigitalRechargeAuthKey;
98
 
23723 amit.gupta 99
	@Autowired
23724 amit.gupta 100
	private PurchaseRepository purchaseRepository;
101
 
102
	@Autowired
103
	private SchemeService schemeService;
104
 
105
	@Autowired
106
	private RechargeTransactionRepository rechargeTransactionRepository;
107
 
108
	@Autowired
109
	private RechargeProviderCreditWalletHistoryRepository rechargeProviderCreditWalletHistoryRepository;
110
 
111
	@Autowired
112
	private FofoOrderRepository fofoOrderRepository;
23929 amit.gupta 113
 
23739 amit.gupta 114
	@Autowired
115
	private WalletService walletService;
23724 amit.gupta 116
 
117
	@Autowired
118
	private ThinkWalnutDigitalRechargeProviderService thinkWalnutDigitalRechargeProviderService;
119
 
120
	@Autowired
121
	private OxigenRechargeProviderService oxigenRechargeProviderService;
122
 
123
	@Autowired
124
	private RechargeProviderRepository rechargeProviderRepository;
125
 
126
	@Autowired
127
	private DailyRechargeRepository dailyRechargeRepository;
128
 
23929 amit.gupta 129
	@Autowired
130
	private FofoStoreRepository fofoStoreRepository;
131
 
23724 amit.gupta 132
	@Value("${prod}")
133
	private boolean prod;
134
 
23929 amit.gupta 135
	@Autowired
136
	private RetailerService retailerService;
137
 
138
	@Autowired
139
	private TransactionService transactionService;
140
 
141
	@Autowired
142
	private OrderRepository orderRepository;
143
 
144
	@Autowired
145
	private JavaMailSender mailSender;
23932 amit.gupta 146
 
147
	@Autowired
23933 amit.gupta 148
	@Qualifier(value="googleMailSender")
23932 amit.gupta 149
	private JavaMailSender googleMailSender;
23929 amit.gupta 150
 
151
	@Autowired
152
	private InventoryService inventoryService;
153
 
23755 amit.gupta 154
	private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
23724 amit.gupta 155
 
156
	public void generateDailyRecharge() {
157
		List<RechargeProviderCreditWalletHistory> allCreditHistory = rechargeProviderCreditWalletHistoryRepository
158
				.selectAll(0, 2000);
159
		List<RechargeProvider> rechargeProviders = rechargeProviderRepository.selectAll();
160
		rechargeProviders.stream().forEach(x -> x.setAmount(0));
161
 
162
		rechargeProviders.stream().forEach(x -> {
163
			Map<LocalDate, List<RechargeProviderCreditWalletHistory>> dateWiseProviderCreditsMap = allCreditHistory
164
					.stream().filter(z -> z.getProviderId() == x.getId())
165
					.collect(Collectors.groupingBy(x1 -> x1.getReceiveTimestamp().toLocalDate()));
166
 
167
			LOGGER.info("dateWiseProviderCreditsMap -- {}", dateWiseProviderCreditsMap);
168
			LocalDate endDate = LocalDate.now().plusDays(1);
169
			float previousDayClosing = 0;
170
			LocalDate date = LocalDate.of(2018, 4, 6);
171
			while (date.isBefore(endDate)) {
172
				List<RechargeTransaction> dateWiseRechargeTransactions = rechargeTransactionRepository
173
						.selectAllBetweenTimestamp(Arrays.asList(RechargeStatus.values()), date.atStartOfDay(),
174
								date.plusDays(1).atStartOfDay());
175
 
176
				List<RechargeTransaction> successfulTransactions = dateWiseRechargeTransactions.stream()
177
						.filter(y -> y.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());
178
 
179
				float dailyAmount = 0;
180
				float totalCommission = 0;
181
				for (RechargeTransaction rechargeTransaction : successfulTransactions) {
182
					if (rechargeTransaction.getProviderId() == x.getId()) {
183
						dailyAmount += rechargeTransaction.getAmount();
184
						totalCommission += rechargeTransaction.getCommission();
185
					}
186
				}
187
 
188
				List<RechargeProviderCreditWalletHistory> rechargeHistoryList = dateWiseProviderCreditsMap.get(date);
189
				float dailyWalletRecharge = 0;
190
				if (rechargeHistoryList != null) {
191
					for (RechargeProviderCreditWalletHistory rechargeProviderCreditWalletHistory : rechargeHistoryList) {
192
						if (rechargeProviderCreditWalletHistory.getProviderId() == x.getId()) {
193
							dailyWalletRecharge += rechargeProviderCreditWalletHistory.getAmount();
194
						}
195
					}
196
				}
197
				if (dailyAmount > 0 || dailyWalletRecharge > 0) {
198
					DailyRecharge dailyRecharge = null;
199
					try {
200
						dailyRecharge = dailyRechargeRepository.selectByProviderIdAndCreateDate(x.getId(), date);
201
					} catch (Exception e) {
202
						LOGGER.info("Could not find Recharge entry");
203
					}
204
					if (dailyRecharge == null) {
205
						dailyRecharge = new DailyRecharge();
206
						dailyRecharge.setCreateDate(date);
207
					}
208
					dailyRecharge.setOpeningBalance(previousDayClosing);
209
					dailyRecharge.setProviderId(x.getId());
210
					dailyRecharge.setWalletRechargeAmount(dailyWalletRecharge);
211
					dailyRecharge.setTotalAmount(dailyAmount);
212
					dailyRecharge.setTotalCommission(totalCommission);
213
					float closingBalance = dailyRecharge.getOpeningBalance() + dailyWalletRecharge - dailyAmount;
214
					dailyRecharge.setClosingBalance(closingBalance);
215
					dailyRechargeRepository.persist(dailyRecharge);
216
					x.setAmount(x.getAmount() + dailyRecharge.getClosingBalance() - dailyRecharge.getOpeningBalance());
217
					previousDayClosing = dailyRecharge.getClosingBalance();
218
				}
219
				date = date.plusDays(1);
220
			}
221
			rechargeProviderRepository.persist(x);
222
		});
23761 amit.gupta 223
		LOGGER.info("finished generating daily recharge");
23724 amit.gupta 224
	}
225
 
23738 amit.gupta 226
	public void reconcileRecharge() throws Exception {
23724 amit.gupta 227
		LocalDateTime fromDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).minusDays(30);
228
		LocalDateTime toDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
229
		List<RechargeStatus> nonSuccessRechargeStatuses = new ArrayList<>(Arrays.asList(RechargeStatus.values()));
230
		LOGGER.info("nonSuccessRechargeStatuses {} ", nonSuccessRechargeStatuses);
231
		nonSuccessRechargeStatuses.remove(RechargeStatus.SUCCESS);
232
		nonSuccessRechargeStatuses.remove(RechargeStatus.FAILED);
233
		RechargeCredential thinkWalnutDigitalRechargeEnquiryCredential = new RechargeCredential();
234
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUrl(thinkWalnutDigitalRechargeEnquiryUrl);
235
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUserName(thinkWalnutDigitalRechargeUserName);
236
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargePassword(thinkWalnutDigitalRechargePassword);
237
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeAuthKey(thinkWalnutDigitalRechargeAuthKey);
238
		Map<String, RechargeStatus> requestRechargeStatusChanged = new HashMap<>();
239
		List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository
240
				.selectAllBetweenTimestamp(nonSuccessRechargeStatuses, fromDate, toDate);
241
		for (RechargeTransaction rechargeTransaction : rechargeTransactions) {
242
			try {
243
				int providerId = rechargeTransaction.getProviderId();
244
				if (providerId == 1) {
245
					oxigenRechargeProviderService.doCheckStatusRequest(oxigenRechargeEnquiryUrl, oxigenRechargeAuthKey,
246
							rechargeTransaction);
247
				} else if (providerId == 2) {
248
					thinkWalnutDigitalRechargeProviderService
249
							.doCheckStatusRequest(thinkWalnutDigitalRechargeEnquiryCredential, rechargeTransaction);
250
				}
251
				if (rechargeTransaction.getStatus().equals(RechargeStatus.SUCCESS)
252
						|| rechargeTransaction.getStatus().equals(RechargeStatus.FAILED)) {
253
					requestRechargeStatusChanged.put(rechargeTransaction.getRequestId(),
254
							rechargeTransaction.getStatus());
255
				}
256
			} catch (Exception e) {
257
				LOGGER.info("Could not check status for Request {}", rechargeTransaction.getRequestId());
258
			}
259
		}
23738 amit.gupta 260
		LOGGER.info("Reconcile recharge ran successfully");
23724 amit.gupta 261
	}
262
 
23738 amit.gupta 263
	public void processScheme() throws Exception {
23724 amit.gupta 264
		LocalDateTime fromDate = LocalDateTime.now().minusDays(15);
265
		LOGGER.info("Started execution at {}", LocalDateTime.now());
266
		List<Purchase> purchases = purchaseRepository.selectFromPurchaseCompleteDate(fromDate);
267
		for (Purchase purchase : purchases) {
268
			try {
269
				schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
270
			} catch (Exception e) {
271
				LOGGER.error("Error while processing purchase {} for scheme In ", purchase.getId());
272
				e.printStackTrace();
273
 
274
			}
275
		}
276
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(fromDate);
277
		for (FofoOrder fofoOrder : fofoOrders) {
278
			try {
279
				schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
280
			} catch (Exception e) {
281
				LOGGER.error("Error while processing sale order {} for scheme Out", fofoOrder.getId());
282
			}
283
		}
284
		LOGGER.info("Schemes process successfully.");
285
	}
23929 amit.gupta 286
 
23739 amit.gupta 287
	public void processRechargeCashback() throws Throwable {
23761 amit.gupta 288
		LocalDateTime cashbackTime = LocalDateTime.now();
23929 amit.gupta 289
		int referenceId = (int) Timestamp.valueOf(cashbackTime).getTime() / 1000;
290
		List<RechargeTransaction> pendingTransactions = rechargeTransactionRepository
291
				.getPendingCashBackRehargeTransactions();
292
		Map<Object, Double> totalRetailerCashbacks = pendingTransactions.stream().collect(
293
				Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingDouble(x -> x.getCommission())));
294
		for (Map.Entry<Object, Double> totalRetailerCashback : totalRetailerCashbacks.entrySet()) {
295
			int retailerId = (Integer) totalRetailerCashback.getKey();
23739 amit.gupta 296
			float amount = totalRetailerCashback.getValue().floatValue();
23929 amit.gupta 297
			if (Math.round(amount) > 0) {
298
				walletService.addAmountToWallet(retailerId, referenceId, WalletReferenceType.CASHBACK,
299
						"Recharge Cashback", Math.round(amount));
23762 amit.gupta 300
			}
23739 amit.gupta 301
		}
23929 amit.gupta 302
		for (RechargeTransaction rt : pendingTransactions) {
23761 amit.gupta 303
			rt.setCashbackTimestamp(cashbackTime);
304
			rt.setCashbackReference(referenceId);
305
			rechargeTransactionRepository.persist(rt);
306
		}
23739 amit.gupta 307
		LOGGER.info("Cashbacks for Recharge processed Successfully");
308
	}
23724 amit.gupta 309
 
23929 amit.gupta 310
	public void sendPartnerInvestmentDetails() throws Exception {
23934 amit.gupta 311
		String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
23929 amit.gupta 312
 
313
		List<FofoStore> fofoStores = fofoStoreRepository.selectAll();
314
		Map<Integer, CustomRetailer> customRetailerMap = retailerService
315
				.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
316
		try (
317
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
318
				PrintStream writer = new PrintStream(baos);
319
				CSVPrinter csvPrinter = new CSVPrinter(writer,
320
						CSVFormat.EXCEL.withTrim().withHeader("Code", "StoreName", "Email", "Mobile", "WalletAmount",
321
								"InStockAmount", "UnbilledStockAmount", "GrnPendingStockAmount", "MinimumInvestment",
322
								"TotalInvested", "ShortAmount"));) {
323
			for (FofoStore fofoStore : fofoStores) {
23930 amit.gupta 324
 
23929 amit.gupta 325
				CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
23930 amit.gupta 326
				if(retailer==null) {
327
					LOGGER.info("Could not find retailer with retailer Id {}",fofoStore.getId() );
23931 amit.gupta 328
					continue;
23930 amit.gupta 329
				}
23929 amit.gupta 330
				float walletAmount = walletService.getUserWallet(fofoStore.getId()).getAmount();
331
				float inStockAmount = inventoryService.getTotalAmountInStock(fofoStore.getId());
332
 
333
				float unbilledStockAmount = 0;
334
				List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoStore.getId());
335
				for (Order unBilledOrder : unbilledOrders) {
336
					unbilledStockAmount += unBilledOrder.getTotalAmount();
337
				}
338
 
339
				float grnPendingStockAmount = 0;
340
				List<Order> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoStore.getId());
341
				for (Order grnPendingOrder : grnPendingOrders) {
342
					LOGGER.info("Grn pending for Order {} and partner {}", grnPendingOrder.getId(),
343
							grnPendingOrder.getRetailerEmailId());
344
					grnPendingStockAmount += grnPendingOrder.getTotalAmount();
345
				}
346
				float totalInvestedAmount = walletAmount + inStockAmount + unbilledStockAmount + grnPendingStockAmount;
23930 amit.gupta 347
				try {
348
				csvPrinter.printRecord(fofoStore.getCode(), retailer.getBusinessName(),
349
						retailer.getEmail(), retailer.getMobileNumber(), walletAmount,
350
						inStockAmount, unbilledStockAmount, grnPendingStockAmount, fofoStore.getMinimumInvestment(), totalInvestedAmount,
23929 amit.gupta 351
						fofoStore.getMinimumInvestment() - totalInvestedAmount);
23930 amit.gupta 352
				} catch (Exception e) {
353
					LOGGER.info("Could not get investment details for partner {}, re", retailer.getEmail());
354
					e.printStackTrace();
355
				}
23929 amit.gupta 356
			}
23932 amit.gupta 357
			Utils.sendMailWithAttachment(googleMailSender, "kamini.sharma@smartdukaan.com",
23934 amit.gupta 358
					new String[] { "amandeep.singh@smartdukaan.com", "tarun.verma@smartdukaan.com"},
23929 amit.gupta 359
					"Partner Investment Summary", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
360
 
361
		}
362
	}
363
 
23724 amit.gupta 364
}