Subversion Repositories SmartDukaan

Rev

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