Subversion Repositories SmartDukaan

Rev

Rev 24195 | Rev 24197 | 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;
9
import java.time.temporal.ChronoUnit;
10
import java.util.ArrayList;
11
import java.util.Arrays;
23723 amit.gupta 12
import java.util.HashMap;
23724 amit.gupta 13
import java.util.List;
23723 amit.gupta 14
import java.util.Map;
23724 amit.gupta 15
import java.util.stream.Collectors;
23723 amit.gupta 16
 
24184 govind 17
import javax.activation.DataSource;
24121 govind 18
import javax.mail.MessagingException;
19
import javax.mail.internet.InternetAddress;
20
import javax.mail.internet.MimeMessage;
21
 
22
import org.apache.commons.codec.CharEncoding;
23
import org.apache.commons.io.IOUtils;
23929 amit.gupta 24
import org.apache.commons.io.output.ByteArrayOutputStream;
23755 amit.gupta 25
import org.apache.logging.log4j.LogManager;
26
import org.apache.logging.log4j.Logger;
24184 govind 27
import org.apache.poi.EncryptedDocumentException;
28
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
29
import org.apache.poi.ss.usermodel.Workbook;
23723 amit.gupta 30
import org.springframework.beans.factory.annotation.Autowired;
23933 amit.gupta 31
import org.springframework.beans.factory.annotation.Qualifier;
23724 amit.gupta 32
import org.springframework.beans.factory.annotation.Value;
23929 amit.gupta 33
import org.springframework.core.io.ByteArrayResource;
34
import org.springframework.mail.javamail.JavaMailSender;
24121 govind 35
import org.springframework.mail.javamail.MimeMessageHelper;
23723 amit.gupta 36
import org.springframework.stereotype.Component;
23724 amit.gupta 37
import org.springframework.transaction.annotation.Transactional;
23723 amit.gupta 38
 
23724 amit.gupta 39
import com.spice.profitmandi.common.enumuration.RechargeStatus;
24121 govind 40
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23929 amit.gupta 41
import com.spice.profitmandi.common.model.CustomRetailer;
23724 amit.gupta 42
import com.spice.profitmandi.common.model.RechargeCredential;
24002 amit.gupta 43
import com.spice.profitmandi.common.util.FileUtil;
23929 amit.gupta 44
import com.spice.profitmandi.common.util.FormattingUtils;
45
import com.spice.profitmandi.common.util.Utils;
23724 amit.gupta 46
import com.spice.profitmandi.dao.entity.dtr.DailyRecharge;
47
import com.spice.profitmandi.dao.entity.dtr.RechargeProvider;
48
import com.spice.profitmandi.dao.entity.dtr.RechargeProviderCreditWalletHistory;
49
import com.spice.profitmandi.dao.entity.dtr.RechargeTransaction;
50
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
23929 amit.gupta 51
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
24174 govind 52
import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;
23724 amit.gupta 53
import com.spice.profitmandi.dao.entity.fofo.Purchase;
24174 govind 54
import com.spice.profitmandi.dao.entity.fofo.SaleHeadDetails;
23929 amit.gupta 55
import com.spice.profitmandi.dao.entity.transaction.Order;
23724 amit.gupta 56
import com.spice.profitmandi.dao.repository.dtr.DailyRechargeRepository;
23929 amit.gupta 57
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
23724 amit.gupta 58
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderCreditWalletHistoryRepository;
59
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderRepository;
60
import com.spice.profitmandi.dao.repository.dtr.RechargeTransactionRepository;
61
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
24174 govind 62
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
23724 amit.gupta 63
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
23929 amit.gupta 64
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
65
import com.spice.profitmandi.service.inventory.InventoryService;
23724 amit.gupta 66
import com.spice.profitmandi.service.recharge.provider.OxigenRechargeProviderService;
67
import com.spice.profitmandi.service.recharge.provider.ThinkWalnutDigitalRechargeProviderService;
68
import com.spice.profitmandi.service.scheme.SchemeService;
24121 govind 69
import com.spice.profitmandi.service.slab.TargetSlabService;
23929 amit.gupta 70
import com.spice.profitmandi.service.transaction.TransactionService;
71
import com.spice.profitmandi.service.user.RetailerService;
23739 amit.gupta 72
import com.spice.profitmandi.service.wallet.WalletService;
23723 amit.gupta 73
 
23739 amit.gupta 74
import in.shop2020.model.v1.order.WalletReferenceType;
24135 govind 75
import com.spice.profitmandi.dao.entity.fofo.SalesHead;;
23739 amit.gupta 76
 
23723 amit.gupta 77
@Component
23724 amit.gupta 78
@Transactional(rollbackFor = Throwable.class)
23723 amit.gupta 79
public class ScheduledTasks {
80
 
23724 amit.gupta 81
	@Value("${oxigen.recharge.transaction.url}")
82
	private String oxigenRechargeTransactionUrl;
23723 amit.gupta 83
 
23724 amit.gupta 84
	@Value("${oxigen.recharge.enquiry.url}")
85
	private String oxigenRechargeEnquiryUrl;
23723 amit.gupta 86
 
23724 amit.gupta 87
	@Value("${oxigen.recharge.auth.key}")
88
	private String oxigenRechargeAuthKey;
89
 
90
	@Value("${oxigen.recharge.validation.url}")
91
	private String oxigenRechargeValidationUrl;
92
 
93
	@Value("${oxigen.recharge.validation.auth.key}")
94
	private String oxigenRechargeValidationAuthKey;
95
 
96
	@Value("${think.walnut.digital.recharge.transaction.mobile.url}")
97
	private String thinkWalnutDigitalRechargeTransactionMobileUrl;
98
 
99
	@Value("${think.walnut.digital.recharge.transaction.dth.url}")
100
	private String thinkWalnutDigitalRechargeTransactionDthUrl;
101
 
102
	@Value("${think.walnut.digital.recharge.enquiry.url}")
103
	private String thinkWalnutDigitalRechargeEnquiryUrl;
104
 
105
	@Value("${think.walnut.digital.recharge.balance.url}")
106
	private String thinkWalnutDigitalRechargeBalanceUrl;
107
 
108
	@Value("${think.walnut.digital.recharge.username}")
109
	private String thinkWalnutDigitalRechargeUserName;
110
 
111
	@Value("${think.walnut.digital.recharge.password}")
112
	private String thinkWalnutDigitalRechargePassword;
113
 
114
	@Value("${think.walnut.digital.recharge.auth.key}")
115
	private String thinkWalnutDigitalRechargeAuthKey;
116
 
23723 amit.gupta 117
	@Autowired
23724 amit.gupta 118
	private PurchaseRepository purchaseRepository;
119
 
120
	@Autowired
121
	private SchemeService schemeService;
122
 
123
	@Autowired
124
	private RechargeTransactionRepository rechargeTransactionRepository;
125
 
126
	@Autowired
127
	private RechargeProviderCreditWalletHistoryRepository rechargeProviderCreditWalletHistoryRepository;
128
 
129
	@Autowired
130
	private FofoOrderRepository fofoOrderRepository;
23929 amit.gupta 131
 
23739 amit.gupta 132
	@Autowired
133
	private WalletService walletService;
23724 amit.gupta 134
 
135
	@Autowired
136
	private ThinkWalnutDigitalRechargeProviderService thinkWalnutDigitalRechargeProviderService;
137
 
138
	@Autowired
139
	private OxigenRechargeProviderService oxigenRechargeProviderService;
140
 
141
	@Autowired
142
	private RechargeProviderRepository rechargeProviderRepository;
143
 
144
	@Autowired
145
	private DailyRechargeRepository dailyRechargeRepository;
146
 
23929 amit.gupta 147
	@Autowired
148
	private FofoStoreRepository fofoStoreRepository;
24177 govind 149
 
24121 govind 150
	@Autowired
151
	private TargetSlabService targetService;
23929 amit.gupta 152
 
23724 amit.gupta 153
	@Value("${prod}")
154
	private boolean prod;
155
 
23929 amit.gupta 156
	@Autowired
157
	private RetailerService retailerService;
158
 
159
	@Autowired
160
	private TransactionService transactionService;
161
 
162
	@Autowired
163
	private OrderRepository orderRepository;
164
 
165
	@Autowired
166
	private JavaMailSender mailSender;
24177 govind 167
 
24174 govind 168
	@Autowired
169
	private PartnerTargetRepository partnerTargetRepository;
24002 amit.gupta 170
 
171
	@Autowired
172
	@Qualifier(value = "googleMailSender")
23932 amit.gupta 173
	private JavaMailSender googleMailSender;
23929 amit.gupta 174
 
175
	@Autowired
176
	private InventoryService inventoryService;
177
 
23755 amit.gupta 178
	private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
23724 amit.gupta 179
 
180
	public void generateDailyRecharge() {
181
		List<RechargeProviderCreditWalletHistory> allCreditHistory = rechargeProviderCreditWalletHistoryRepository
182
				.selectAll(0, 2000);
183
		List<RechargeProvider> rechargeProviders = rechargeProviderRepository.selectAll();
184
		rechargeProviders.stream().forEach(x -> x.setAmount(0));
185
 
186
		rechargeProviders.stream().forEach(x -> {
187
			Map<LocalDate, List<RechargeProviderCreditWalletHistory>> dateWiseProviderCreditsMap = allCreditHistory
188
					.stream().filter(z -> z.getProviderId() == x.getId())
189
					.collect(Collectors.groupingBy(x1 -> x1.getReceiveTimestamp().toLocalDate()));
190
 
191
			LOGGER.info("dateWiseProviderCreditsMap -- {}", dateWiseProviderCreditsMap);
192
			LocalDate endDate = LocalDate.now().plusDays(1);
193
			float previousDayClosing = 0;
194
			LocalDate date = LocalDate.of(2018, 4, 6);
195
			while (date.isBefore(endDate)) {
196
				List<RechargeTransaction> dateWiseRechargeTransactions = rechargeTransactionRepository
197
						.selectAllBetweenTimestamp(Arrays.asList(RechargeStatus.values()), date.atStartOfDay(),
198
								date.plusDays(1).atStartOfDay());
199
 
200
				List<RechargeTransaction> successfulTransactions = dateWiseRechargeTransactions.stream()
201
						.filter(y -> y.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());
202
 
203
				float dailyAmount = 0;
204
				float totalCommission = 0;
205
				for (RechargeTransaction rechargeTransaction : successfulTransactions) {
206
					if (rechargeTransaction.getProviderId() == x.getId()) {
207
						dailyAmount += rechargeTransaction.getAmount();
208
						totalCommission += rechargeTransaction.getCommission();
209
					}
210
				}
211
 
212
				List<RechargeProviderCreditWalletHistory> rechargeHistoryList = dateWiseProviderCreditsMap.get(date);
213
				float dailyWalletRecharge = 0;
214
				if (rechargeHistoryList != null) {
215
					for (RechargeProviderCreditWalletHistory rechargeProviderCreditWalletHistory : rechargeHistoryList) {
216
						if (rechargeProviderCreditWalletHistory.getProviderId() == x.getId()) {
217
							dailyWalletRecharge += rechargeProviderCreditWalletHistory.getAmount();
218
						}
219
					}
220
				}
221
				if (dailyAmount > 0 || dailyWalletRecharge > 0) {
222
					DailyRecharge dailyRecharge = null;
223
					try {
224
						dailyRecharge = dailyRechargeRepository.selectByProviderIdAndCreateDate(x.getId(), date);
225
					} catch (Exception e) {
226
						LOGGER.info("Could not find Recharge entry");
227
					}
228
					if (dailyRecharge == null) {
229
						dailyRecharge = new DailyRecharge();
230
						dailyRecharge.setCreateDate(date);
231
					}
232
					dailyRecharge.setOpeningBalance(previousDayClosing);
233
					dailyRecharge.setProviderId(x.getId());
234
					dailyRecharge.setWalletRechargeAmount(dailyWalletRecharge);
235
					dailyRecharge.setTotalAmount(dailyAmount);
236
					dailyRecharge.setTotalCommission(totalCommission);
237
					float closingBalance = dailyRecharge.getOpeningBalance() + dailyWalletRecharge - dailyAmount;
238
					dailyRecharge.setClosingBalance(closingBalance);
239
					dailyRechargeRepository.persist(dailyRecharge);
240
					x.setAmount(x.getAmount() + dailyRecharge.getClosingBalance() - dailyRecharge.getOpeningBalance());
241
					previousDayClosing = dailyRecharge.getClosingBalance();
242
				}
243
				date = date.plusDays(1);
244
			}
245
			rechargeProviderRepository.persist(x);
246
		});
23761 amit.gupta 247
		LOGGER.info("finished generating daily recharge");
23724 amit.gupta 248
	}
249
 
23738 amit.gupta 250
	public void reconcileRecharge() throws Exception {
23724 amit.gupta 251
		LocalDateTime fromDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).minusDays(30);
252
		LocalDateTime toDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
253
		List<RechargeStatus> nonSuccessRechargeStatuses = new ArrayList<>(Arrays.asList(RechargeStatus.values()));
254
		LOGGER.info("nonSuccessRechargeStatuses {} ", nonSuccessRechargeStatuses);
255
		nonSuccessRechargeStatuses.remove(RechargeStatus.SUCCESS);
256
		nonSuccessRechargeStatuses.remove(RechargeStatus.FAILED);
257
		RechargeCredential thinkWalnutDigitalRechargeEnquiryCredential = new RechargeCredential();
258
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUrl(thinkWalnutDigitalRechargeEnquiryUrl);
259
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUserName(thinkWalnutDigitalRechargeUserName);
260
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargePassword(thinkWalnutDigitalRechargePassword);
261
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeAuthKey(thinkWalnutDigitalRechargeAuthKey);
262
		Map<String, RechargeStatus> requestRechargeStatusChanged = new HashMap<>();
263
		List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository
264
				.selectAllBetweenTimestamp(nonSuccessRechargeStatuses, fromDate, toDate);
265
		for (RechargeTransaction rechargeTransaction : rechargeTransactions) {
266
			try {
267
				int providerId = rechargeTransaction.getProviderId();
268
				if (providerId == 1) {
269
					oxigenRechargeProviderService.doCheckStatusRequest(oxigenRechargeEnquiryUrl, oxigenRechargeAuthKey,
270
							rechargeTransaction);
271
				} else if (providerId == 2) {
272
					thinkWalnutDigitalRechargeProviderService
273
							.doCheckStatusRequest(thinkWalnutDigitalRechargeEnquiryCredential, rechargeTransaction);
274
				}
275
				if (rechargeTransaction.getStatus().equals(RechargeStatus.SUCCESS)
276
						|| rechargeTransaction.getStatus().equals(RechargeStatus.FAILED)) {
277
					requestRechargeStatusChanged.put(rechargeTransaction.getRequestId(),
278
							rechargeTransaction.getStatus());
279
				}
280
			} catch (Exception e) {
281
				LOGGER.info("Could not check status for Request {}", rechargeTransaction.getRequestId());
282
			}
283
		}
23738 amit.gupta 284
		LOGGER.info("Reconcile recharge ran successfully");
23724 amit.gupta 285
	}
286
 
23738 amit.gupta 287
	public void processScheme() throws Exception {
23724 amit.gupta 288
		LocalDateTime fromDate = LocalDateTime.now().minusDays(15);
289
		LOGGER.info("Started execution at {}", LocalDateTime.now());
290
		List<Purchase> purchases = purchaseRepository.selectFromPurchaseCompleteDate(fromDate);
291
		for (Purchase purchase : purchases) {
292
			try {
293
				schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
294
			} catch (Exception e) {
295
				LOGGER.error("Error while processing purchase {} for scheme In ", purchase.getId());
296
				e.printStackTrace();
297
 
298
			}
299
		}
300
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(fromDate);
301
		for (FofoOrder fofoOrder : fofoOrders) {
302
			try {
303
				schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
304
			} catch (Exception e) {
305
				LOGGER.error("Error while processing sale order {} for scheme Out", fofoOrder.getId());
306
			}
307
		}
308
		LOGGER.info("Schemes process successfully.");
309
	}
23929 amit.gupta 310
 
23739 amit.gupta 311
	public void processRechargeCashback() throws Throwable {
23761 amit.gupta 312
		LocalDateTime cashbackTime = LocalDateTime.now();
23929 amit.gupta 313
		int referenceId = (int) Timestamp.valueOf(cashbackTime).getTime() / 1000;
314
		List<RechargeTransaction> pendingTransactions = rechargeTransactionRepository
315
				.getPendingCashBackRehargeTransactions();
316
		Map<Object, Double> totalRetailerCashbacks = pendingTransactions.stream().collect(
317
				Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingDouble(x -> x.getCommission())));
318
		for (Map.Entry<Object, Double> totalRetailerCashback : totalRetailerCashbacks.entrySet()) {
319
			int retailerId = (Integer) totalRetailerCashback.getKey();
23739 amit.gupta 320
			float amount = totalRetailerCashback.getValue().floatValue();
23929 amit.gupta 321
			if (Math.round(amount) > 0) {
322
				walletService.addAmountToWallet(retailerId, referenceId, WalletReferenceType.CASHBACK,
323
						"Recharge Cashback", Math.round(amount));
23762 amit.gupta 324
			}
23739 amit.gupta 325
		}
23929 amit.gupta 326
		for (RechargeTransaction rt : pendingTransactions) {
23761 amit.gupta 327
			rt.setCashbackTimestamp(cashbackTime);
328
			rt.setCashbackReference(referenceId);
329
			rechargeTransactionRepository.persist(rt);
330
		}
23739 amit.gupta 331
		LOGGER.info("Cashbacks for Recharge processed Successfully");
332
	}
23724 amit.gupta 333
 
23929 amit.gupta 334
	public void sendPartnerInvestmentDetails() throws Exception {
23934 amit.gupta 335
		String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
23929 amit.gupta 336
 
337
		List<FofoStore> fofoStores = fofoStoreRepository.selectAll();
338
		Map<Integer, CustomRetailer> customRetailerMap = retailerService
339
				.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
340
 
24002 amit.gupta 341
		List<String> headers = Arrays.asList("Code", "StoreName", "Email", "Mobile", "WalletAmount", "InStockAmount",
342
				"UnbilledStockAmount", "GrnPendingStockAmount", "MinimumInvestment", "TotalInvested", "ShortAmount");
343
		List<List<Object>> rows = new ArrayList<>();
344
		for (FofoStore fofoStore : fofoStores) {
345
			CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
346
			if (retailer == null) {
347
				LOGGER.info("Could not find retailer with retailer Id {}", fofoStore.getId());
348
				continue;
349
			}
350
			float walletAmount = walletService.getUserWallet(fofoStore.getId()).getAmount();
351
			float inStockAmount = inventoryService.getTotalAmountInStock(fofoStore.getId());
23929 amit.gupta 352
 
24002 amit.gupta 353
			float unbilledStockAmount = 0;
354
			List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoStore.getId());
355
			for (Order unBilledOrder : unbilledOrders) {
356
				unbilledStockAmount += unBilledOrder.getTotalAmount();
23929 amit.gupta 357
			}
358
 
24002 amit.gupta 359
			float grnPendingStockAmount = 0;
360
			List<Order> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoStore.getId());
361
			for (Order grnPendingOrder : grnPendingOrders) {
362
				LOGGER.info("Grn pending for Order {} and partner {}", grnPendingOrder.getId(),
363
						grnPendingOrder.getRetailerEmailId());
364
				grnPendingStockAmount += grnPendingOrder.getTotalAmount();
365
			}
366
			float totalInvestedAmount = walletAmount + inStockAmount + unbilledStockAmount + grnPendingStockAmount;
367
			List<Object> row = Arrays.asList(fofoStore.getCode(), retailer.getBusinessName(), retailer.getEmail(),
368
					retailer.getMobileNumber(), walletAmount, inStockAmount, unbilledStockAmount, grnPendingStockAmount,
369
					fofoStore.getMinimumInvestment(), totalInvestedAmount,
370
					fofoStore.getMinimumInvestment() - totalInvestedAmount);
371
			rows.add(row);
372
 
23929 amit.gupta 373
		}
24002 amit.gupta 374
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
375
		Utils.sendMailWithAttachment(googleMailSender, "adeel.yazdani@smartdukaan.com",
376
				new String[] { "amandeep.singh@smartdukaan.com", "tarun.verma@smartdukaan.com",
24052 amit.gupta 377
						"kamini.sharma@smartdukaan.com", "dhruv.kathpal@smartdukaan.com" },
24002 amit.gupta 378
				"Partner Investment Summary", "PFA", fileName, new ByteArrayResource(baos.toByteArray()));
23929 amit.gupta 379
	}
24177 govind 380
 
381
	private void sendMailWithAttachments(String[] email, String[] ccEmails, String body, String subject,
24187 govind 382
			Map<String, InputStream> inputStreams)
24177 govind 383
			throws MessagingException, ProfitMandiBusinessException, IOException {
24121 govind 384
		MimeMessage message = mailSender.createMimeMessage();
24177 govind 385
		MimeMessageHelper helper = new MimeMessageHelper(message, true, CharEncoding.UTF_8);
386
		helper.setSubject(subject);
387
		helper.setText(body);
388
		if (ccEmails != null) {
389
			helper.setCc(ccEmails);
390
		}
24187 govind 391
		for(String attachment:inputStreams.keySet())
392
		{
393
		helper.addAttachment(attachment+"_"+LocalDate.now()+".xls",new ByteArrayResource(IOUtils.toByteArray(inputStreams.get(attachment))));
394
		}
24177 govind 395
		helper.setTo(email);
24195 govind 396
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
24177 govind 397
		helper.setFrom(senderAddress);
398
		mailSender.send(message);
24135 govind 399
	}
24184 govind 400
	private void sendMailWithAttachmentsForPartners(String email, String body, String subject,
401
			InputStream is)
402
			throws MessagingException, ProfitMandiBusinessException, IOException {
403
		MimeMessage message = mailSender.createMimeMessage();
404
		MimeMessageHelper helper = new MimeMessageHelper(message, true, CharEncoding.UTF_8);
405
		helper.setSubject(subject);
406
		helper.setText(body);
407
		helper.addAttachment("DailySaleTargetReports_"+LocalDate.now()+".xls",new ByteArrayResource(IOUtils.toByteArray(is)));
408
		helper.setTo(email);
24195 govind 409
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
24184 govind 410
		helper.setFrom(senderAddress);
411
		mailSender.send(message);
412
	}
24177 govind 413
 
414
	public void sendMailToSalesHeadAboutTargetAndSales(SaleHeadDetails salesHeadDetail)
415
			throws MessagingException, ProfitMandiBusinessException, IOException {
416
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
417
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
418
		Map<String, InputStream> inputStreams = new HashMap<>();
419
		for (PartnerTargetDetails partnerTargetDetail : partnerTargetDetails) {
420
			InputStream is = targetService.getDailySaleReportVsTargetForSaleHead(partnerTargetDetail,
421
					salesHeadDetail.getName());
422
 
423
 
424
			inputStreams.put(partnerTargetDetail.getTargetName(), is);
425
 
24174 govind 426
		}
24196 govind 427
		//String[] ccEmails = null;
428
		String[] ccEmails={"Tarun.verma@smartdukaan.com","Kamini.sharma@smartdukaan.com","chaitnaya.vats@smartdukaan.com","dhruv.kathpal@smartdukaan.com"};
24177 govind 429
		String subject = "Daily Sales Report ";
430
		String message = MessageFormat.format("Sale Target summary for {0}", LocalDate.now());
431
		LOGGER.info("message" + message);
432
		if (salesHeadDetail.getName().equals("Kamal")) {
433
			LOGGER.info("salesHeadDetail.getName()" + salesHeadDetail.getName());
434
			String[] to = { salesHeadDetail.getEmail(), "mohinder.mutreja@smartdukaan.com" };
435
 
24187 govind 436
			this.sendMailWithAttachments(to, ccEmails, message, subject, inputStreams);
24177 govind 437
 
438
		} else {
439
			LOGGER.info("salesHeadDetail.getName()" + salesHeadDetail.getName());
440
			String[] to = { salesHeadDetail.getEmail() };
24187 govind 441
			this.sendMailWithAttachments(to, ccEmails, message, subject, inputStreams);
24177 govind 442
		}
24121 govind 443
	}
24177 govind 444
 
445
	public void sendMailToPartnerAboutTargetAndSales()
24184 govind 446
			throws ProfitMandiBusinessException, MessagingException, IOException, EncryptedDocumentException, InvalidFormatException {
24177 govind 447
		List<Integer> fofoIds = targetService.getfofoIdsFromfofoStore();
448
		Map<Integer, CustomRetailer> fofoIdsAndCustomRetailer = retailerService
449
				.getFofoRetailers(new ArrayList<>(fofoIds));
24184 govind 450
		List<InputStream> input=new ArrayList<>();
24177 govind 451
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
452
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
453
		for (Integer fofoId : fofoIds) {
24184 govind 454
			InputStream is=targetService.getDailySaleReportVsTargetForPartner(fofoId,partnerTargetDetails);
24193 govind 455
			LOGGER.info("is"+is);
24192 govind 456
			if(is==null)
24189 govind 457
			{
24192 govind 458
				continue;
459
			}
24177 govind 460
			LOGGER.info("fofoId"+fofoId);
24193 govind 461
 
24177 govind 462
			LOGGER.info(fofoIdsAndCustomRetailer.get(fofoId).getEmail());
463
			String subject="Daily Sales Report";
464
			String message = MessageFormat.format("Sale Target summary for {0}",LocalDate.now());
465
			LOGGER.info(message);
24194 govind 466
			this.sendMailWithAttachmentsForPartners(fofoIdsAndCustomRetailer.get(fofoId).getEmail(),message, subject, is);
24189 govind 467
 
24192 govind 468
 
24174 govind 469
		}
470
	}
23929 amit.gupta 471
 
23724 amit.gupta 472
}