Subversion Repositories SmartDukaan

Rev

Rev 24337 | Rev 24431 | 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
 
24121 govind 3
import java.io.IOException;
4
import java.io.InputStream;
23739 amit.gupta 5
import java.sql.Timestamp;
24174 govind 6
import java.text.MessageFormat;
23724 amit.gupta 7
import java.time.LocalDate;
8
import java.time.LocalDateTime;
24256 amit.gupta 9
import java.time.LocalTime;
23724 amit.gupta 10
import java.time.temporal.ChronoUnit;
11
import java.util.ArrayList;
12
import java.util.Arrays;
23723 amit.gupta 13
import java.util.HashMap;
24241 amit.gupta 14
import java.util.HashSet;
23724 amit.gupta 15
import java.util.List;
23723 amit.gupta 16
import java.util.Map;
24242 amit.gupta 17
import java.util.Optional;
23724 amit.gupta 18
import java.util.stream.Collectors;
23723 amit.gupta 19
 
24121 govind 20
import javax.mail.MessagingException;
21
import javax.mail.internet.InternetAddress;
22
import javax.mail.internet.MimeMessage;
23
 
24
import org.apache.commons.codec.CharEncoding;
25
import org.apache.commons.io.IOUtils;
23929 amit.gupta 26
import org.apache.commons.io.output.ByteArrayOutputStream;
23755 amit.gupta 27
import org.apache.logging.log4j.LogManager;
28
import org.apache.logging.log4j.Logger;
24184 govind 29
import org.apache.poi.EncryptedDocumentException;
30
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
23723 amit.gupta 31
import org.springframework.beans.factory.annotation.Autowired;
23933 amit.gupta 32
import org.springframework.beans.factory.annotation.Qualifier;
23724 amit.gupta 33
import org.springframework.beans.factory.annotation.Value;
23929 amit.gupta 34
import org.springframework.core.io.ByteArrayResource;
35
import org.springframework.mail.javamail.JavaMailSender;
24121 govind 36
import org.springframework.mail.javamail.MimeMessageHelper;
23723 amit.gupta 37
import org.springframework.stereotype.Component;
23724 amit.gupta 38
import org.springframework.transaction.annotation.Transactional;
23723 amit.gupta 39
 
23724 amit.gupta 40
import com.spice.profitmandi.common.enumuration.RechargeStatus;
24121 govind 41
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23929 amit.gupta 42
import com.spice.profitmandi.common.model.CustomRetailer;
23724 amit.gupta 43
import com.spice.profitmandi.common.model.RechargeCredential;
24002 amit.gupta 44
import com.spice.profitmandi.common.util.FileUtil;
23929 amit.gupta 45
import com.spice.profitmandi.common.util.FormattingUtils;
46
import com.spice.profitmandi.common.util.Utils;
23724 amit.gupta 47
import com.spice.profitmandi.dao.entity.dtr.DailyRecharge;
48
import com.spice.profitmandi.dao.entity.dtr.RechargeProvider;
49
import com.spice.profitmandi.dao.entity.dtr.RechargeProviderCreditWalletHistory;
50
import com.spice.profitmandi.dao.entity.dtr.RechargeTransaction;
51
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
23929 amit.gupta 52
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
24249 amit.gupta 53
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
24277 amit.gupta 54
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
24174 govind 55
import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;
23724 amit.gupta 56
import com.spice.profitmandi.dao.entity.fofo.Purchase;
24174 govind 57
import com.spice.profitmandi.dao.entity.fofo.SaleHeadDetails;
24242 amit.gupta 58
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
24241 amit.gupta 59
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
24250 amit.gupta 60
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
24242 amit.gupta 61
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
24249 amit.gupta 62
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
24241 amit.gupta 63
import com.spice.profitmandi.dao.repository.catalog.SchemeRepository;
23724 amit.gupta 64
import com.spice.profitmandi.dao.repository.dtr.DailyRechargeRepository;
23929 amit.gupta 65
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
23724 amit.gupta 66
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderCreditWalletHistoryRepository;
67
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderRepository;
68
import com.spice.profitmandi.dao.repository.dtr.RechargeTransactionRepository;
69
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
24249 amit.gupta 70
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
24277 amit.gupta 71
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
24174 govind 72
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
23724 amit.gupta 73
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
24242 amit.gupta 74
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
24241 amit.gupta 75
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
23929 amit.gupta 76
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
24337 amit.gupta 77
import com.spice.profitmandi.service.PartnerInvestmentService;
23929 amit.gupta 78
import com.spice.profitmandi.service.inventory.InventoryService;
24271 amit.gupta 79
import com.spice.profitmandi.service.order.OrderService;
23724 amit.gupta 80
import com.spice.profitmandi.service.recharge.provider.OxigenRechargeProviderService;
81
import com.spice.profitmandi.service.recharge.provider.ThinkWalnutDigitalRechargeProviderService;
82
import com.spice.profitmandi.service.scheme.SchemeService;
24121 govind 83
import com.spice.profitmandi.service.slab.TargetSlabService;
23929 amit.gupta 84
import com.spice.profitmandi.service.transaction.TransactionService;
85
import com.spice.profitmandi.service.user.RetailerService;
23739 amit.gupta 86
import com.spice.profitmandi.service.wallet.WalletService;
23723 amit.gupta 87
 
24197 amit.gupta 88
import in.shop2020.model.v1.order.WalletReferenceType;;
23739 amit.gupta 89
 
23723 amit.gupta 90
@Component
23724 amit.gupta 91
@Transactional(rollbackFor = Throwable.class)
23723 amit.gupta 92
public class ScheduledTasks {
93
 
23724 amit.gupta 94
	@Value("${oxigen.recharge.transaction.url}")
95
	private String oxigenRechargeTransactionUrl;
23723 amit.gupta 96
 
23724 amit.gupta 97
	@Value("${oxigen.recharge.enquiry.url}")
98
	private String oxigenRechargeEnquiryUrl;
23723 amit.gupta 99
 
23724 amit.gupta 100
	@Value("${oxigen.recharge.auth.key}")
101
	private String oxigenRechargeAuthKey;
102
 
103
	@Value("${oxigen.recharge.validation.url}")
104
	private String oxigenRechargeValidationUrl;
105
 
106
	@Value("${oxigen.recharge.validation.auth.key}")
107
	private String oxigenRechargeValidationAuthKey;
108
 
109
	@Value("${think.walnut.digital.recharge.transaction.mobile.url}")
110
	private String thinkWalnutDigitalRechargeTransactionMobileUrl;
111
 
112
	@Value("${think.walnut.digital.recharge.transaction.dth.url}")
113
	private String thinkWalnutDigitalRechargeTransactionDthUrl;
114
 
115
	@Value("${think.walnut.digital.recharge.enquiry.url}")
116
	private String thinkWalnutDigitalRechargeEnquiryUrl;
117
 
118
	@Value("${think.walnut.digital.recharge.balance.url}")
119
	private String thinkWalnutDigitalRechargeBalanceUrl;
120
 
121
	@Value("${think.walnut.digital.recharge.username}")
122
	private String thinkWalnutDigitalRechargeUserName;
123
 
124
	@Value("${think.walnut.digital.recharge.password}")
125
	private String thinkWalnutDigitalRechargePassword;
126
 
127
	@Value("${think.walnut.digital.recharge.auth.key}")
128
	private String thinkWalnutDigitalRechargeAuthKey;
129
 
23723 amit.gupta 130
	@Autowired
23724 amit.gupta 131
	private PurchaseRepository purchaseRepository;
132
 
133
	@Autowired
134
	private SchemeService schemeService;
135
 
136
	@Autowired
24271 amit.gupta 137
	private OrderService orderService;
138
 
139
	@Autowired
24337 amit.gupta 140
	private PartnerInvestmentService partnerInvestmentService;
141
 
142
	@Autowired
24277 amit.gupta 143
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
144
 
145
	@Autowired
24241 amit.gupta 146
	private SchemeInOutRepository schemeInOutRepository;
147
 
148
	@Autowired
23724 amit.gupta 149
	private RechargeTransactionRepository rechargeTransactionRepository;
150
 
151
	@Autowired
152
	private RechargeProviderCreditWalletHistoryRepository rechargeProviderCreditWalletHistoryRepository;
153
 
154
	@Autowired
155
	private FofoOrderRepository fofoOrderRepository;
24250 amit.gupta 156
 
24249 amit.gupta 157
	@Autowired
158
	private InventoryItemRepository inventoryItemRepository;
23929 amit.gupta 159
 
23739 amit.gupta 160
	@Autowired
161
	private WalletService walletService;
23724 amit.gupta 162
 
163
	@Autowired
164
	private ThinkWalnutDigitalRechargeProviderService thinkWalnutDigitalRechargeProviderService;
165
 
166
	@Autowired
167
	private OxigenRechargeProviderService oxigenRechargeProviderService;
168
 
169
	@Autowired
170
	private RechargeProviderRepository rechargeProviderRepository;
171
 
172
	@Autowired
24242 amit.gupta 173
	private ScanRecordRepository scanRecordRepository;
174
 
175
	@Autowired
23724 amit.gupta 176
	private DailyRechargeRepository dailyRechargeRepository;
177
 
23929 amit.gupta 178
	@Autowired
179
	private FofoStoreRepository fofoStoreRepository;
24177 govind 180
 
24121 govind 181
	@Autowired
182
	private TargetSlabService targetService;
23929 amit.gupta 183
 
23724 amit.gupta 184
	@Value("${prod}")
185
	private boolean prod;
186
 
23929 amit.gupta 187
	@Autowired
188
	private RetailerService retailerService;
189
 
190
	@Autowired
191
	private TransactionService transactionService;
24250 amit.gupta 192
 
24249 amit.gupta 193
	@Autowired
194
	private ItemRepository itemRepository;
23929 amit.gupta 195
 
196
	@Autowired
197
	private OrderRepository orderRepository;
198
 
199
	@Autowired
24241 amit.gupta 200
	private SchemeRepository schemeRepository;
201
 
202
	@Autowired
23929 amit.gupta 203
	private JavaMailSender mailSender;
24177 govind 204
 
24174 govind 205
	@Autowired
206
	private PartnerTargetRepository partnerTargetRepository;
24002 amit.gupta 207
 
208
	@Autowired
209
	@Qualifier(value = "googleMailSender")
23932 amit.gupta 210
	private JavaMailSender googleMailSender;
23929 amit.gupta 211
 
212
	@Autowired
213
	private InventoryService inventoryService;
214
 
23755 amit.gupta 215
	private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
23724 amit.gupta 216
 
217
	public void generateDailyRecharge() {
218
		List<RechargeProviderCreditWalletHistory> allCreditHistory = rechargeProviderCreditWalletHistoryRepository
219
				.selectAll(0, 2000);
220
		List<RechargeProvider> rechargeProviders = rechargeProviderRepository.selectAll();
221
		rechargeProviders.stream().forEach(x -> x.setAmount(0));
222
 
223
		rechargeProviders.stream().forEach(x -> {
224
			Map<LocalDate, List<RechargeProviderCreditWalletHistory>> dateWiseProviderCreditsMap = allCreditHistory
225
					.stream().filter(z -> z.getProviderId() == x.getId())
226
					.collect(Collectors.groupingBy(x1 -> x1.getReceiveTimestamp().toLocalDate()));
227
 
228
			LOGGER.info("dateWiseProviderCreditsMap -- {}", dateWiseProviderCreditsMap);
229
			LocalDate endDate = LocalDate.now().plusDays(1);
230
			float previousDayClosing = 0;
231
			LocalDate date = LocalDate.of(2018, 4, 6);
232
			while (date.isBefore(endDate)) {
233
				List<RechargeTransaction> dateWiseRechargeTransactions = rechargeTransactionRepository
234
						.selectAllBetweenTimestamp(Arrays.asList(RechargeStatus.values()), date.atStartOfDay(),
235
								date.plusDays(1).atStartOfDay());
236
 
237
				List<RechargeTransaction> successfulTransactions = dateWiseRechargeTransactions.stream()
238
						.filter(y -> y.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());
239
 
240
				float dailyAmount = 0;
241
				float totalCommission = 0;
242
				for (RechargeTransaction rechargeTransaction : successfulTransactions) {
243
					if (rechargeTransaction.getProviderId() == x.getId()) {
244
						dailyAmount += rechargeTransaction.getAmount();
245
						totalCommission += rechargeTransaction.getCommission();
246
					}
247
				}
248
 
249
				List<RechargeProviderCreditWalletHistory> rechargeHistoryList = dateWiseProviderCreditsMap.get(date);
250
				float dailyWalletRecharge = 0;
251
				if (rechargeHistoryList != null) {
252
					for (RechargeProviderCreditWalletHistory rechargeProviderCreditWalletHistory : rechargeHistoryList) {
253
						if (rechargeProviderCreditWalletHistory.getProviderId() == x.getId()) {
254
							dailyWalletRecharge += rechargeProviderCreditWalletHistory.getAmount();
255
						}
256
					}
257
				}
258
				if (dailyAmount > 0 || dailyWalletRecharge > 0) {
259
					DailyRecharge dailyRecharge = null;
260
					try {
261
						dailyRecharge = dailyRechargeRepository.selectByProviderIdAndCreateDate(x.getId(), date);
262
					} catch (Exception e) {
263
						LOGGER.info("Could not find Recharge entry");
264
					}
265
					if (dailyRecharge == null) {
266
						dailyRecharge = new DailyRecharge();
267
						dailyRecharge.setCreateDate(date);
268
					}
269
					dailyRecharge.setOpeningBalance(previousDayClosing);
270
					dailyRecharge.setProviderId(x.getId());
271
					dailyRecharge.setWalletRechargeAmount(dailyWalletRecharge);
272
					dailyRecharge.setTotalAmount(dailyAmount);
273
					dailyRecharge.setTotalCommission(totalCommission);
274
					float closingBalance = dailyRecharge.getOpeningBalance() + dailyWalletRecharge - dailyAmount;
275
					dailyRecharge.setClosingBalance(closingBalance);
276
					dailyRechargeRepository.persist(dailyRecharge);
277
					x.setAmount(x.getAmount() + dailyRecharge.getClosingBalance() - dailyRecharge.getOpeningBalance());
278
					previousDayClosing = dailyRecharge.getClosingBalance();
279
				}
280
				date = date.plusDays(1);
281
			}
282
			rechargeProviderRepository.persist(x);
283
		});
23761 amit.gupta 284
		LOGGER.info("finished generating daily recharge");
23724 amit.gupta 285
	}
286
 
23738 amit.gupta 287
	public void reconcileRecharge() throws Exception {
23724 amit.gupta 288
		LocalDateTime fromDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).minusDays(30);
289
		LocalDateTime toDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
290
		List<RechargeStatus> nonSuccessRechargeStatuses = new ArrayList<>(Arrays.asList(RechargeStatus.values()));
291
		LOGGER.info("nonSuccessRechargeStatuses {} ", nonSuccessRechargeStatuses);
292
		nonSuccessRechargeStatuses.remove(RechargeStatus.SUCCESS);
293
		nonSuccessRechargeStatuses.remove(RechargeStatus.FAILED);
294
		RechargeCredential thinkWalnutDigitalRechargeEnquiryCredential = new RechargeCredential();
295
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUrl(thinkWalnutDigitalRechargeEnquiryUrl);
296
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUserName(thinkWalnutDigitalRechargeUserName);
297
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargePassword(thinkWalnutDigitalRechargePassword);
298
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeAuthKey(thinkWalnutDigitalRechargeAuthKey);
299
		Map<String, RechargeStatus> requestRechargeStatusChanged = new HashMap<>();
300
		List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository
301
				.selectAllBetweenTimestamp(nonSuccessRechargeStatuses, fromDate, toDate);
302
		for (RechargeTransaction rechargeTransaction : rechargeTransactions) {
303
			try {
304
				int providerId = rechargeTransaction.getProviderId();
305
				if (providerId == 1) {
306
					oxigenRechargeProviderService.doCheckStatusRequest(oxigenRechargeEnquiryUrl, oxigenRechargeAuthKey,
307
							rechargeTransaction);
308
				} else if (providerId == 2) {
309
					thinkWalnutDigitalRechargeProviderService
310
							.doCheckStatusRequest(thinkWalnutDigitalRechargeEnquiryCredential, rechargeTransaction);
311
				}
312
				if (rechargeTransaction.getStatus().equals(RechargeStatus.SUCCESS)
313
						|| rechargeTransaction.getStatus().equals(RechargeStatus.FAILED)) {
314
					requestRechargeStatusChanged.put(rechargeTransaction.getRequestId(),
315
							rechargeTransaction.getStatus());
316
				}
317
			} catch (Exception e) {
318
				LOGGER.info("Could not check status for Request {}", rechargeTransaction.getRequestId());
319
			}
320
		}
23738 amit.gupta 321
		LOGGER.info("Reconcile recharge ran successfully");
23724 amit.gupta 322
	}
24240 amit.gupta 323
 
324
	// TemporaryMethod
24237 amit.gupta 325
	public void migrateInvoice() {
326
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(LocalDateTime.now().minusDays(3));
327
		Map<Integer, List<FofoOrder>> partnerOrdersMap = new HashMap<>();
24241 amit.gupta 328
		partnerOrdersMap = fofoOrders.stream()
329
				.collect(Collectors.groupingBy(FofoOrder::getFofoId, Collectors.toList()));
24237 amit.gupta 330
		for (List<FofoOrder> orderList : partnerOrdersMap.values()) {
24240 amit.gupta 331
			int sequence = 0;
332
			String prefix = "";
24241 amit.gupta 333
			List<FofoOrder> sortedList = orderList.stream().sorted((x1, x2) -> x1.getId() - x2.getId())
334
					.collect(Collectors.toList());
335
			for (FofoOrder order : sortedList) {
336
 
24240 amit.gupta 337
				LOGGER.info("Order Id is {}, partner Id is {}", order.getId(), order.getFofoId());
24241 amit.gupta 338
				if (!order.getInvoiceNumber().contains("SEC")) {
24240 amit.gupta 339
					sequence = Integer.parseInt(order.getInvoiceNumber().split("/")[1]);
340
					prefix = order.getInvoiceNumber().split("/")[0];
341
				} else {
342
					sequence += 1;
24241 amit.gupta 343
					String invoiceNumber = prefix + "/" + sequence;
24240 amit.gupta 344
					order.setInvoiceNumber(invoiceNumber);
345
					fofoOrderRepository.persist(order);
346
				}
347
			}
24241 amit.gupta 348
 
24237 amit.gupta 349
		}
350
	}
23724 amit.gupta 351
 
24241 amit.gupta 352
	// Temporary Method
24252 amit.gupta 353
	public void evaluateExcessSchemeOut() throws Exception {
24244 amit.gupta 354
		Map<Integer, String> userNameMap = retailerService.getAllFofoRetailerIdNameMap();
355
		Map<Integer, Float> userAmountMap = new HashMap<>();
24252 amit.gupta 356
 
357
		List<List<Object>> rows = new ArrayList<>();
24271 amit.gupta 358
		List<String> headers = Arrays.asList("Scheme", "Item", "Partner", "Amount", "Credited On", "Invoice Number",
359
				"Sale On", "Scheme Start", "Scheme End", "Active On", "Expired On");
24241 amit.gupta 360
		schemeRepository.selectAll().stream().forEach(x -> {
24250 amit.gupta 361
			if (x.getType().equals(SchemeType.OUT)) {
362
				List<SchemeInOut> sioList = schemeInOutRepository
363
						.selectBySchemeIds(new HashSet<>(Arrays.asList(x.getId())));
364
				if (x.getActiveTimestamp() != null) {
365
					LocalDateTime endDateTime = x.getEndDateTime();
366
					if (x.getExpireTimestamp() != null && x.getExpireTimestamp().isBefore(x.getEndDateTime())) {
367
						endDateTime = x.getExpireTimestamp();
24249 amit.gupta 368
					}
24250 amit.gupta 369
					for (SchemeInOut sio : sioList) {
370
						InventoryItem inventoryItem = null;
24266 amit.gupta 371
						inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
24271 amit.gupta 372
						FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndSerialNumber(
373
								inventoryItem.getFofoId(), inventoryItem.getSerialNumber(), null, null, 0, 1).get(0);
24250 amit.gupta 374
						Optional<ScanRecord> record = scanRecordRepository
375
								.selectByInventoryItemId(sio.getInventoryItemId()).stream()
376
								.filter(y -> y.getType().equals(ScanType.SALE)).findFirst();
377
						if (record.isPresent()) {
378
							int fofoId = record.get().getFofoId();
379
							if (record.get().getCreateTimestamp().isAfter(endDateTime)
380
									|| record.get().getCreateTimestamp().isBefore(x.getStartDateTime())) {
381
								if (!userAmountMap.containsKey(fofoId)) {
382
									userAmountMap.put(fofoId, 0f);
383
								}
384
								userAmountMap.put(fofoId, sio.getAmount() + userAmountMap.get(fofoId));
385
								try {
24252 amit.gupta 386
									rows.add(Arrays.asList(x.getDescription(),
24250 amit.gupta 387
											itemRepository.selectById(inventoryItem.getItemId()).getItemDescription(),
24252 amit.gupta 388
											userNameMap.get(fofoId), sio.getAmount(),
24253 amit.gupta 389
											FormattingUtils.formatDate(sio.getCreateTimestamp()),
390
											fofoOrder.getInvoiceNumber(),
391
											FormattingUtils.formatDate(record.get().getCreateTimestamp()),
392
											FormattingUtils.formatDate(x.getStartDateTime()),
393
											FormattingUtils.formatDate(x.getEndDateTime()),
394
											FormattingUtils.formatDate(x.getActiveTimestamp()),
395
											FormattingUtils.formatDate(x.getExpireTimestamp())));
24250 amit.gupta 396
								} catch (Exception e) {
397
									e.printStackTrace();
398
								}
24242 amit.gupta 399
							}
24241 amit.gupta 400
						}
401
					}
402
				}
403
			}
404
		});
24246 amit.gupta 405
		userAmountMap.entrySet().stream()
406
				.forEach(x -> LOGGER.info("{} to be deducted from {}({}) for wrongly disbursed due to technical error.",
407
						x.getValue(), userNameMap.get(x.getKey())));
24241 amit.gupta 408
 
24252 amit.gupta 409
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
24271 amit.gupta 410
		Utils.sendMailWithAttachment(googleMailSender,
411
				new String[] { "amit.gupta@shop2020.in", "adeel.yazdani@smartdukaan.com" }, null,
412
				"Partner Excess Amount", "PFA", "ListofSchemes.csv", new ByteArrayResource(baos.toByteArray()));
24252 amit.gupta 413
 
24241 amit.gupta 414
	}
24271 amit.gupta 415
 
24256 amit.gupta 416
	public void processScheme(int offset) throws Exception {
24271 amit.gupta 417
		LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(30 * offset);
24259 amit.gupta 418
		LocalDateTime endDate = startDate.plusDays(30);
24258 amit.gupta 419
		processScheme(startDate, endDate);
24256 amit.gupta 420
	}
24271 amit.gupta 421
 
23738 amit.gupta 422
	public void processScheme() throws Exception {
24256 amit.gupta 423
		LocalDateTime fromDate = LocalDateTime.now().minusDays(30);
424
		processScheme(fromDate, LocalDateTime.now());
425
	}
24271 amit.gupta 426
 
24256 amit.gupta 427
	public void processScheme(LocalDateTime startDate, LocalDateTime endDate) throws Exception {
23724 amit.gupta 428
		LOGGER.info("Started execution at {}", LocalDateTime.now());
24256 amit.gupta 429
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
23724 amit.gupta 430
		for (Purchase purchase : purchases) {
431
			try {
432
				schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
433
			} catch (Exception e) {
434
				LOGGER.error("Error while processing purchase {} for scheme In ", purchase.getId());
435
				e.printStackTrace();
24271 amit.gupta 436
 
23724 amit.gupta 437
			}
438
		}
24256 amit.gupta 439
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
23724 amit.gupta 440
		for (FofoOrder fofoOrder : fofoOrders) {
441
			try {
442
				schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
443
			} catch (Exception e) {
444
				LOGGER.error("Error while processing sale order {} for scheme Out", fofoOrder.getId());
445
			}
446
		}
447
		LOGGER.info("Schemes process successfully.");
448
	}
23929 amit.gupta 449
 
23739 amit.gupta 450
	public void processRechargeCashback() throws Throwable {
23761 amit.gupta 451
		LocalDateTime cashbackTime = LocalDateTime.now();
23929 amit.gupta 452
		int referenceId = (int) Timestamp.valueOf(cashbackTime).getTime() / 1000;
453
		List<RechargeTransaction> pendingTransactions = rechargeTransactionRepository
454
				.getPendingCashBackRehargeTransactions();
455
		Map<Object, Double> totalRetailerCashbacks = pendingTransactions.stream().collect(
456
				Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingDouble(x -> x.getCommission())));
457
		for (Map.Entry<Object, Double> totalRetailerCashback : totalRetailerCashbacks.entrySet()) {
458
			int retailerId = (Integer) totalRetailerCashback.getKey();
23739 amit.gupta 459
			float amount = totalRetailerCashback.getValue().floatValue();
23929 amit.gupta 460
			if (Math.round(amount) > 0) {
461
				walletService.addAmountToWallet(retailerId, referenceId, WalletReferenceType.CASHBACK,
462
						"Recharge Cashback", Math.round(amount));
23762 amit.gupta 463
			}
23739 amit.gupta 464
		}
23929 amit.gupta 465
		for (RechargeTransaction rt : pendingTransactions) {
23761 amit.gupta 466
			rt.setCashbackTimestamp(cashbackTime);
467
			rt.setCashbackReference(referenceId);
468
			rechargeTransactionRepository.persist(rt);
469
		}
23739 amit.gupta 470
		LOGGER.info("Cashbacks for Recharge processed Successfully");
471
	}
23724 amit.gupta 472
 
24271 amit.gupta 473
	public void sendPartnerInvestmentDetails(List<String> sendTo) throws Exception {
24277 amit.gupta 474
		LocalDate yesterDay = LocalDate.now().minusDays(1);
23929 amit.gupta 475
		List<FofoStore> fofoStores = fofoStoreRepository.selectAll();
476
		Map<Integer, CustomRetailer> customRetailerMap = retailerService
477
				.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
478
 
24271 amit.gupta 479
		List<String> headers = Arrays.asList("Code", "StoreName", "Email", "Mobile", "Wallet Amount",
480
				"Yesterday's Sale", "In Stock Amount", "Return In Transit Stock", "Unbilled Amount",
481
				"Grn Pending Amount", "Min Investment", "Investment Amount", "Investment Short");
24002 amit.gupta 482
		List<List<Object>> rows = new ArrayList<>();
483
		for (FofoStore fofoStore : fofoStores) {
484
			CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
485
			if (retailer == null) {
486
				LOGGER.info("Could not find retailer with retailer Id {}", fofoStore.getId());
487
				continue;
488
			}
24337 amit.gupta 489
			PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService
490
					.getInvestment(fofoStore.getId(), 1);
491
			partnerDailyInvestment.setDate(yesterDay);
492
			partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
24314 amit.gupta 493
 
24002 amit.gupta 494
			List<Object> row = Arrays.asList(fofoStore.getCode(), retailer.getBusinessName(), retailer.getEmail(),
24337 amit.gupta 495
					retailer.getMobileNumber(), partnerDailyInvestment.getWalletAmount(),
496
					partnerDailyInvestment.getSalesAmount(), partnerDailyInvestment.getInStockAmount(), 0,
24415 amit.gupta 497
					partnerDailyInvestment.getUnbilledAmount(), partnerDailyInvestment.getGrnPendingAmount(),
24337 amit.gupta 498
					partnerDailyInvestment.getMinInvestment(), partnerDailyInvestment.getTotalInvestment(), partnerDailyInvestment.getShortInvestment());
24002 amit.gupta 499
			rows.add(row);
500
 
23929 amit.gupta 501
		}
24271 amit.gupta 502
		String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
24002 amit.gupta 503
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
24271 amit.gupta 504
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
505
 
506
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Partner Investment Summary", "PFA", fileName,
507
				new ByteArrayResource(baos.toByteArray()));
508
 
23929 amit.gupta 509
	}
24177 govind 510
 
24271 amit.gupta 511
	public void sendPartnerInvestmentDetails() throws Exception {
512
		List<String> sendTo = Arrays.asList("adeel.yazdani@smartdukaan.com", "amandeep.singh@smartdukaan.com",
513
				"tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "dhruv.kathpal@smartdukaan.com",
514
				"neeraj.gupta@smartdukaan.com");
515
		this.sendPartnerInvestmentDetails(sendTo);
516
 
517
	}
518
 
24177 govind 519
	private void sendMailWithAttachments(String[] email, String[] ccEmails, String body, String subject,
24187 govind 520
			Map<String, InputStream> inputStreams)
24177 govind 521
			throws MessagingException, ProfitMandiBusinessException, IOException {
24121 govind 522
		MimeMessage message = mailSender.createMimeMessage();
24177 govind 523
		MimeMessageHelper helper = new MimeMessageHelper(message, true, CharEncoding.UTF_8);
524
		helper.setSubject(subject);
525
		helper.setText(body);
526
		if (ccEmails != null) {
527
			helper.setCc(ccEmails);
528
		}
24240 amit.gupta 529
		for (String attachment : inputStreams.keySet()) {
530
			helper.addAttachment(attachment + "_" + LocalDate.now() + ".xls",
531
					new ByteArrayResource(IOUtils.toByteArray(inputStreams.get(attachment))));
24187 govind 532
		}
24177 govind 533
		helper.setTo(email);
24195 govind 534
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
24177 govind 535
		helper.setFrom(senderAddress);
536
		mailSender.send(message);
24135 govind 537
	}
24240 amit.gupta 538
 
539
	private void sendMailWithAttachmentsForPartners(String email, String body, String subject, InputStream is)
24184 govind 540
			throws MessagingException, ProfitMandiBusinessException, IOException {
541
		MimeMessage message = mailSender.createMimeMessage();
542
		MimeMessageHelper helper = new MimeMessageHelper(message, true, CharEncoding.UTF_8);
543
		helper.setSubject(subject);
544
		helper.setText(body);
24240 amit.gupta 545
		helper.addAttachment("DailySaleTargetReports_" + LocalDate.now() + ".xls",
546
				new ByteArrayResource(IOUtils.toByteArray(is)));
24184 govind 547
		helper.setTo(email);
24195 govind 548
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
24184 govind 549
		helper.setFrom(senderAddress);
550
		mailSender.send(message);
551
	}
24177 govind 552
 
553
	public void sendMailToSalesHeadAboutTargetAndSales(SaleHeadDetails salesHeadDetail)
554
			throws MessagingException, ProfitMandiBusinessException, IOException {
555
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
556
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
557
		Map<String, InputStream> inputStreams = new HashMap<>();
558
		for (PartnerTargetDetails partnerTargetDetail : partnerTargetDetails) {
559
			InputStream is = targetService.getDailySaleReportVsTargetForSaleHead(partnerTargetDetail,
560
					salesHeadDetail.getName());
24240 amit.gupta 561
 
24177 govind 562
			inputStreams.put(partnerTargetDetail.getTargetName(), is);
563
 
24174 govind 564
		}
24240 amit.gupta 565
		// String[] ccEmails = null;
24271 amit.gupta 566
		if (partnerTargetDetails.size() > 0) {
24254 govind 567
			String[] ccEmails = { "Tarun.verma@smartdukaan.com", "Kamini.sharma@smartdukaan.com",
568
					"chaitnaya.vats@smartdukaan.com", "dhruv.kathpal@smartdukaan.com" };
569
			String subject = "Daily Sales Report ";
570
			String message = MessageFormat.format("Sale Target summary for {0}", LocalDate.now());
571
			LOGGER.info("message" + message);
572
			if (salesHeadDetail.getName().equals("Kamal")) {
573
				LOGGER.info("salesHeadDetail.getName()" + salesHeadDetail.getName());
574
				String[] to = { salesHeadDetail.getEmail(), "mohinder.mutreja@smartdukaan.com" };
24177 govind 575
 
24271 amit.gupta 576
				this.sendMailWithAttachments(to, ccEmails, message, subject, inputStreams);
24177 govind 577
 
24271 amit.gupta 578
			} else {
579
				LOGGER.info("salesHeadDetail.getName()" + salesHeadDetail.getName());
580
				String[] to = { salesHeadDetail.getEmail() };
581
				this.sendMailWithAttachments(to, ccEmails, message, subject, inputStreams);
582
			}
24177 govind 583
		}
24121 govind 584
	}
24177 govind 585
 
24240 amit.gupta 586
	public void sendMailToPartnerAboutTargetAndSales() throws ProfitMandiBusinessException, MessagingException,
587
			IOException, EncryptedDocumentException, InvalidFormatException {
24177 govind 588
		List<Integer> fofoIds = targetService.getfofoIdsFromfofoStore();
589
		Map<Integer, CustomRetailer> fofoIdsAndCustomRetailer = retailerService
590
				.getFofoRetailers(new ArrayList<>(fofoIds));
24240 amit.gupta 591
		List<InputStream> input = new ArrayList<>();
24177 govind 592
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
593
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
594
		for (Integer fofoId : fofoIds) {
24240 amit.gupta 595
			InputStream is = targetService.getDailySaleReportVsTargetForPartner(fofoId, partnerTargetDetails);
596
			LOGGER.info("is" + is);
597
			if (is == null) {
24192 govind 598
				continue;
599
			}
24240 amit.gupta 600
			LOGGER.info("fofoId" + fofoId);
601
 
24177 govind 602
			LOGGER.info(fofoIdsAndCustomRetailer.get(fofoId).getEmail());
24240 amit.gupta 603
			String subject = "Daily Sales Report";
604
			String message = MessageFormat.format("Sale Target summary for {0}", LocalDate.now());
24177 govind 605
			LOGGER.info(message);
24240 amit.gupta 606
			this.sendMailWithAttachmentsForPartners(fofoIdsAndCustomRetailer.get(fofoId).getEmail(), message, subject,
607
					is);
608
 
24174 govind 609
		}
610
	}
23929 amit.gupta 611
 
23724 amit.gupta 612
}