Subversion Repositories SmartDukaan

Rev

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