Subversion Repositories SmartDukaan

Rev

Rev 24670 | Rev 24677 | 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;
24653 govind 7
import java.time.Duration;
23724 amit.gupta 8
import java.time.LocalDate;
9
import java.time.LocalDateTime;
24256 amit.gupta 10
import java.time.LocalTime;
24653 govind 11
import java.time.ZoneOffset;
12
import java.time.format.DateTimeFormatter;
23724 amit.gupta 13
import java.time.temporal.ChronoUnit;
14
import java.util.ArrayList;
15
import java.util.Arrays;
24627 amit.gupta 16
import java.util.Collections;
23723 amit.gupta 17
import java.util.HashMap;
24241 amit.gupta 18
import java.util.HashSet;
23724 amit.gupta 19
import java.util.List;
23723 amit.gupta 20
import java.util.Map;
24653 govind 21
import java.util.Map.Entry;
24242 amit.gupta 22
import java.util.Optional;
24542 amit.gupta 23
import java.util.Set;
23724 amit.gupta 24
import java.util.stream.Collectors;
23723 amit.gupta 25
 
24121 govind 26
import javax.mail.MessagingException;
27
import javax.mail.internet.InternetAddress;
28
import javax.mail.internet.MimeMessage;
29
 
30
import org.apache.commons.codec.CharEncoding;
31
import org.apache.commons.io.IOUtils;
23929 amit.gupta 32
import org.apache.commons.io.output.ByteArrayOutputStream;
23755 amit.gupta 33
import org.apache.logging.log4j.LogManager;
34
import org.apache.logging.log4j.Logger;
24184 govind 35
import org.apache.poi.EncryptedDocumentException;
36
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
23723 amit.gupta 37
import org.springframework.beans.factory.annotation.Autowired;
23933 amit.gupta 38
import org.springframework.beans.factory.annotation.Qualifier;
23724 amit.gupta 39
import org.springframework.beans.factory.annotation.Value;
23929 amit.gupta 40
import org.springframework.core.io.ByteArrayResource;
41
import org.springframework.mail.javamail.JavaMailSender;
24121 govind 42
import org.springframework.mail.javamail.MimeMessageHelper;
23723 amit.gupta 43
import org.springframework.stereotype.Component;
23724 amit.gupta 44
import org.springframework.transaction.annotation.Transactional;
23723 amit.gupta 45
 
24542 amit.gupta 46
import com.google.common.collect.Lists;
23724 amit.gupta 47
import com.spice.profitmandi.common.enumuration.RechargeStatus;
24121 govind 48
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23929 amit.gupta 49
import com.spice.profitmandi.common.model.CustomRetailer;
24542 amit.gupta 50
import com.spice.profitmandi.common.model.GstRate;
23724 amit.gupta 51
import com.spice.profitmandi.common.model.RechargeCredential;
24002 amit.gupta 52
import com.spice.profitmandi.common.util.FileUtil;
23929 amit.gupta 53
import com.spice.profitmandi.common.util.FormattingUtils;
54
import com.spice.profitmandi.common.util.Utils;
24592 amit.gupta 55
import com.spice.profitmandi.common.util.Utils.Attachment;
24653 govind 56
import com.spice.profitmandi.dao.entity.auth.AuthUser;
24590 amit.gupta 57
import com.spice.profitmandi.dao.entity.catalog.Scheme;
24533 govind 58
import com.spice.profitmandi.dao.entity.cs.Ticket;
59
import com.spice.profitmandi.dao.entity.cs.TicketAssigned;
23724 amit.gupta 60
import com.spice.profitmandi.dao.entity.dtr.DailyRecharge;
24653 govind 61
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaigns;
23724 amit.gupta 62
import com.spice.profitmandi.dao.entity.dtr.RechargeProvider;
63
import com.spice.profitmandi.dao.entity.dtr.RechargeProviderCreditWalletHistory;
64
import com.spice.profitmandi.dao.entity.dtr.RechargeTransaction;
24653 govind 65
import com.spice.profitmandi.dao.entity.fofo.ActivityType;
24542 amit.gupta 66
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
24590 amit.gupta 67
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
23724 amit.gupta 68
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
24542 amit.gupta 69
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23929 amit.gupta 70
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
24249 amit.gupta 71
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
24277 amit.gupta 72
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
24653 govind 73
import com.spice.profitmandi.dao.entity.fofo.PartnerTarget;
24174 govind 74
import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;
23724 amit.gupta 75
import com.spice.profitmandi.dao.entity.fofo.Purchase;
24174 govind 76
import com.spice.profitmandi.dao.entity.fofo.SaleHeadDetails;
24242 amit.gupta 77
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
24241 amit.gupta 78
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
24431 amit.gupta 79
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
24587 amit.gupta 80
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
24580 amit.gupta 81
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
24542 amit.gupta 82
import com.spice.profitmandi.dao.entity.user.Address;
24250 amit.gupta 83
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
24653 govind 84
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
24242 amit.gupta 85
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
24533 govind 86
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
24249 amit.gupta 87
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
24241 amit.gupta 88
import com.spice.profitmandi.dao.repository.catalog.SchemeRepository;
24533 govind 89
import com.spice.profitmandi.dao.repository.cs.TicketAssignedRepository;
90
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
24653 govind 91
import com.spice.profitmandi.dao.repository.cs.TicketSubCategoryRepository;
23724 amit.gupta 92
import com.spice.profitmandi.dao.repository.dtr.DailyRechargeRepository;
23929 amit.gupta 93
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
24653 govind 94
import com.spice.profitmandi.dao.repository.dtr.Mongo;
23724 amit.gupta 95
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderCreditWalletHistoryRepository;
96
import com.spice.profitmandi.dao.repository.dtr.RechargeProviderRepository;
97
import com.spice.profitmandi.dao.repository.dtr.RechargeTransactionRepository;
24542 amit.gupta 98
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
24669 govind 99
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
24542 amit.gupta 100
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
24590 amit.gupta 101
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
24542 amit.gupta 102
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
23724 amit.gupta 103
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
24249 amit.gupta 104
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
24277 amit.gupta 105
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
24174 govind 106
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
23724 amit.gupta 107
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
24242 amit.gupta 108
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
24241 amit.gupta 109
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
23929 amit.gupta 110
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
24431 amit.gupta 111
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
24580 amit.gupta 112
import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;
24587 amit.gupta 113
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
24542 amit.gupta 114
import com.spice.profitmandi.dao.repository.user.AddressRepository;
24337 amit.gupta 115
import com.spice.profitmandi.service.PartnerInvestmentService;
23929 amit.gupta 116
import com.spice.profitmandi.service.inventory.InventoryService;
24431 amit.gupta 117
import com.spice.profitmandi.service.pricing.PriceDropService;
23724 amit.gupta 118
import com.spice.profitmandi.service.recharge.provider.OxigenRechargeProviderService;
119
import com.spice.profitmandi.service.recharge.provider.ThinkWalnutDigitalRechargeProviderService;
120
import com.spice.profitmandi.service.scheme.SchemeService;
24121 govind 121
import com.spice.profitmandi.service.slab.TargetSlabService;
23929 amit.gupta 122
import com.spice.profitmandi.service.transaction.TransactionService;
123
import com.spice.profitmandi.service.user.RetailerService;
23739 amit.gupta 124
import com.spice.profitmandi.service.wallet.WalletService;
23723 amit.gupta 125
 
24197 amit.gupta 126
import in.shop2020.model.v1.order.WalletReferenceType;;
23739 amit.gupta 127
 
23723 amit.gupta 128
@Component
23724 amit.gupta 129
@Transactional(rollbackFor = Throwable.class)
23723 amit.gupta 130
public class ScheduledTasks {
131
 
24533 govind 132
	private static final String Escalate_TICKET = "Dear {0},Your Ticket created by {1} is escalated and assigned to {2}. Regards \nSmartdukaan";
133
 
23724 amit.gupta 134
	@Value("${oxigen.recharge.transaction.url}")
135
	private String oxigenRechargeTransactionUrl;
23723 amit.gupta 136
 
23724 amit.gupta 137
	@Value("${oxigen.recharge.enquiry.url}")
138
	private String oxigenRechargeEnquiryUrl;
24533 govind 139
 
24431 amit.gupta 140
	@Autowired
141
	private PriceDropService priceDropService;
23723 amit.gupta 142
 
23724 amit.gupta 143
	@Value("${oxigen.recharge.auth.key}")
144
	private String oxigenRechargeAuthKey;
145
 
146
	@Value("${oxigen.recharge.validation.url}")
147
	private String oxigenRechargeValidationUrl;
148
 
149
	@Value("${oxigen.recharge.validation.auth.key}")
150
	private String oxigenRechargeValidationAuthKey;
151
 
152
	@Value("${think.walnut.digital.recharge.transaction.mobile.url}")
153
	private String thinkWalnutDigitalRechargeTransactionMobileUrl;
154
 
155
	@Value("${think.walnut.digital.recharge.transaction.dth.url}")
156
	private String thinkWalnutDigitalRechargeTransactionDthUrl;
157
 
158
	@Value("${think.walnut.digital.recharge.enquiry.url}")
159
	private String thinkWalnutDigitalRechargeEnquiryUrl;
160
 
161
	@Value("${think.walnut.digital.recharge.balance.url}")
162
	private String thinkWalnutDigitalRechargeBalanceUrl;
163
 
164
	@Value("${think.walnut.digital.recharge.username}")
165
	private String thinkWalnutDigitalRechargeUserName;
166
 
167
	@Value("${think.walnut.digital.recharge.password}")
168
	private String thinkWalnutDigitalRechargePassword;
169
 
170
	@Value("${think.walnut.digital.recharge.auth.key}")
171
	private String thinkWalnutDigitalRechargeAuthKey;
172
 
23723 amit.gupta 173
	@Autowired
23724 amit.gupta 174
	private PurchaseRepository purchaseRepository;
175
 
176
	@Autowired
177
	private SchemeService schemeService;
178
 
179
	@Autowired
24337 amit.gupta 180
	private PartnerInvestmentService partnerInvestmentService;
181
 
182
	@Autowired
24542 amit.gupta 183
	private FofoOrderItemRepository fofoOrderItemRepository;
184
 
185
	@Autowired
24277 amit.gupta 186
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
187
 
188
	@Autowired
24241 amit.gupta 189
	private SchemeInOutRepository schemeInOutRepository;
190
 
191
	@Autowired
23724 amit.gupta 192
	private RechargeTransactionRepository rechargeTransactionRepository;
193
 
194
	@Autowired
24542 amit.gupta 195
	private CustomerAddressRepository customerAddressRepository;
196
 
197
	@Autowired
23724 amit.gupta 198
	private RechargeProviderCreditWalletHistoryRepository rechargeProviderCreditWalletHistoryRepository;
199
 
200
	@Autowired
24590 amit.gupta 201
	private FofoLineItemRepository fofoLineItemRepository;
202
 
203
	@Autowired
23724 amit.gupta 204
	private FofoOrderRepository fofoOrderRepository;
24587 amit.gupta 205
 
24580 amit.gupta 206
	@Autowired
207
	private UserWalletHistoryRepository userWalletHistoryRepository;
24250 amit.gupta 208
 
24249 amit.gupta 209
	@Autowired
24587 amit.gupta 210
	private UserWalletRepository userWalletRepository;
211
 
212
	@Autowired
24249 amit.gupta 213
	private InventoryItemRepository inventoryItemRepository;
23929 amit.gupta 214
 
23739 amit.gupta 215
	@Autowired
216
	private WalletService walletService;
23724 amit.gupta 217
 
218
	@Autowired
219
	private ThinkWalnutDigitalRechargeProviderService thinkWalnutDigitalRechargeProviderService;
220
 
221
	@Autowired
222
	private OxigenRechargeProviderService oxigenRechargeProviderService;
223
 
224
	@Autowired
225
	private RechargeProviderRepository rechargeProviderRepository;
226
 
227
	@Autowired
24242 amit.gupta 228
	private ScanRecordRepository scanRecordRepository;
229
 
230
	@Autowired
23724 amit.gupta 231
	private DailyRechargeRepository dailyRechargeRepository;
232
 
23929 amit.gupta 233
	@Autowired
234
	private FofoStoreRepository fofoStoreRepository;
24177 govind 235
 
24121 govind 236
	@Autowired
237
	private TargetSlabService targetService;
23929 amit.gupta 238
 
23724 amit.gupta 239
	@Value("${prod}")
240
	private boolean prod;
241
 
23929 amit.gupta 242
	@Autowired
243
	private RetailerService retailerService;
244
 
245
	@Autowired
246
	private TransactionService transactionService;
24250 amit.gupta 247
 
24249 amit.gupta 248
	@Autowired
249
	private ItemRepository itemRepository;
23929 amit.gupta 250
 
251
	@Autowired
252
	private OrderRepository orderRepository;
253
 
254
	@Autowired
24241 amit.gupta 255
	private SchemeRepository schemeRepository;
256
 
257
	@Autowired
23929 amit.gupta 258
	private JavaMailSender mailSender;
24177 govind 259
 
24174 govind 260
	@Autowired
24431 amit.gupta 261
	private PriceDropRepository priceDropRepository;
262
 
263
	@Autowired
24174 govind 264
	private PartnerTargetRepository partnerTargetRepository;
24002 amit.gupta 265
 
266
	@Autowired
267
	@Qualifier(value = "googleMailSender")
23932 amit.gupta 268
	private JavaMailSender googleMailSender;
23929 amit.gupta 269
 
270
	@Autowired
271
	private InventoryService inventoryService;
272
 
24533 govind 273
	@Autowired
274
	private TicketRepository ticketRepository;
275
 
276
	@Autowired
277
	private TicketAssignedRepository ticketAssignedRepository;
278
 
279
	@Autowired
280
	private AuthRepository authRepository;
281
 
24542 amit.gupta 282
	@Autowired
283
	private AddressRepository addressRepository;
284
 
285
	@Autowired
286
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
287
 
24653 govind 288
	@Autowired
289
	private TicketSubCategoryRepository ticketSubCategoryRepository;
290
 
291
	@Autowired
292
	private Mongo mongoClient;
24669 govind 293
 
294
	@Autowired
295
	private UserAccountRepository userAccountRepository;
24653 govind 296
 
23755 amit.gupta 297
	private static final Logger LOGGER = LogManager.getLogger(ScheduledTasks.class);
23724 amit.gupta 298
 
299
	public void generateDailyRecharge() {
300
		List<RechargeProviderCreditWalletHistory> allCreditHistory = rechargeProviderCreditWalletHistoryRepository
301
				.selectAll(0, 2000);
302
		List<RechargeProvider> rechargeProviders = rechargeProviderRepository.selectAll();
303
		rechargeProviders.stream().forEach(x -> x.setAmount(0));
304
 
305
		rechargeProviders.stream().forEach(x -> {
306
			Map<LocalDate, List<RechargeProviderCreditWalletHistory>> dateWiseProviderCreditsMap = allCreditHistory
307
					.stream().filter(z -> z.getProviderId() == x.getId())
308
					.collect(Collectors.groupingBy(x1 -> x1.getReceiveTimestamp().toLocalDate()));
309
 
310
			LOGGER.info("dateWiseProviderCreditsMap -- {}", dateWiseProviderCreditsMap);
311
			LocalDate endDate = LocalDate.now().plusDays(1);
312
			float previousDayClosing = 0;
313
			LocalDate date = LocalDate.of(2018, 4, 6);
314
			while (date.isBefore(endDate)) {
315
				List<RechargeTransaction> dateWiseRechargeTransactions = rechargeTransactionRepository
316
						.selectAllBetweenTimestamp(Arrays.asList(RechargeStatus.values()), date.atStartOfDay(),
317
								date.plusDays(1).atStartOfDay());
318
 
319
				List<RechargeTransaction> successfulTransactions = dateWiseRechargeTransactions.stream()
320
						.filter(y -> y.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());
321
 
322
				float dailyAmount = 0;
323
				float totalCommission = 0;
324
				for (RechargeTransaction rechargeTransaction : successfulTransactions) {
325
					if (rechargeTransaction.getProviderId() == x.getId()) {
326
						dailyAmount += rechargeTransaction.getAmount();
327
						totalCommission += rechargeTransaction.getCommission();
328
					}
329
				}
330
 
331
				List<RechargeProviderCreditWalletHistory> rechargeHistoryList = dateWiseProviderCreditsMap.get(date);
332
				float dailyWalletRecharge = 0;
333
				if (rechargeHistoryList != null) {
334
					for (RechargeProviderCreditWalletHistory rechargeProviderCreditWalletHistory : rechargeHistoryList) {
335
						if (rechargeProviderCreditWalletHistory.getProviderId() == x.getId()) {
336
							dailyWalletRecharge += rechargeProviderCreditWalletHistory.getAmount();
337
						}
338
					}
339
				}
340
				if (dailyAmount > 0 || dailyWalletRecharge > 0) {
341
					DailyRecharge dailyRecharge = null;
342
					try {
343
						dailyRecharge = dailyRechargeRepository.selectByProviderIdAndCreateDate(x.getId(), date);
344
					} catch (Exception e) {
345
						LOGGER.info("Could not find Recharge entry");
346
					}
347
					if (dailyRecharge == null) {
348
						dailyRecharge = new DailyRecharge();
349
						dailyRecharge.setCreateDate(date);
350
					}
351
					dailyRecharge.setOpeningBalance(previousDayClosing);
352
					dailyRecharge.setProviderId(x.getId());
353
					dailyRecharge.setWalletRechargeAmount(dailyWalletRecharge);
354
					dailyRecharge.setTotalAmount(dailyAmount);
355
					dailyRecharge.setTotalCommission(totalCommission);
356
					float closingBalance = dailyRecharge.getOpeningBalance() + dailyWalletRecharge - dailyAmount;
357
					dailyRecharge.setClosingBalance(closingBalance);
358
					dailyRechargeRepository.persist(dailyRecharge);
359
					x.setAmount(x.getAmount() + dailyRecharge.getClosingBalance() - dailyRecharge.getOpeningBalance());
360
					previousDayClosing = dailyRecharge.getClosingBalance();
361
				}
362
				date = date.plusDays(1);
363
			}
364
			rechargeProviderRepository.persist(x);
365
		});
23761 amit.gupta 366
		LOGGER.info("finished generating daily recharge");
23724 amit.gupta 367
	}
368
 
23738 amit.gupta 369
	public void reconcileRecharge() throws Exception {
23724 amit.gupta 370
		LocalDateTime fromDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).minusDays(30);
371
		LocalDateTime toDate = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
372
		List<RechargeStatus> nonSuccessRechargeStatuses = new ArrayList<>(Arrays.asList(RechargeStatus.values()));
373
		LOGGER.info("nonSuccessRechargeStatuses {} ", nonSuccessRechargeStatuses);
374
		nonSuccessRechargeStatuses.remove(RechargeStatus.SUCCESS);
375
		nonSuccessRechargeStatuses.remove(RechargeStatus.FAILED);
376
		RechargeCredential thinkWalnutDigitalRechargeEnquiryCredential = new RechargeCredential();
377
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUrl(thinkWalnutDigitalRechargeEnquiryUrl);
378
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeUserName(thinkWalnutDigitalRechargeUserName);
379
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargePassword(thinkWalnutDigitalRechargePassword);
380
		thinkWalnutDigitalRechargeEnquiryCredential.setRechargeAuthKey(thinkWalnutDigitalRechargeAuthKey);
381
		Map<String, RechargeStatus> requestRechargeStatusChanged = new HashMap<>();
382
		List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository
383
				.selectAllBetweenTimestamp(nonSuccessRechargeStatuses, fromDate, toDate);
384
		for (RechargeTransaction rechargeTransaction : rechargeTransactions) {
385
			try {
386
				int providerId = rechargeTransaction.getProviderId();
387
				if (providerId == 1) {
388
					oxigenRechargeProviderService.doCheckStatusRequest(oxigenRechargeEnquiryUrl, oxigenRechargeAuthKey,
389
							rechargeTransaction);
390
				} else if (providerId == 2) {
391
					thinkWalnutDigitalRechargeProviderService
392
							.doCheckStatusRequest(thinkWalnutDigitalRechargeEnquiryCredential, rechargeTransaction);
393
				}
394
				if (rechargeTransaction.getStatus().equals(RechargeStatus.SUCCESS)
395
						|| rechargeTransaction.getStatus().equals(RechargeStatus.FAILED)) {
396
					requestRechargeStatusChanged.put(rechargeTransaction.getRequestId(),
397
							rechargeTransaction.getStatus());
398
				}
399
			} catch (Exception e) {
400
				LOGGER.info("Could not check status for Request {}", rechargeTransaction.getRequestId());
401
			}
402
		}
23738 amit.gupta 403
		LOGGER.info("Reconcile recharge ran successfully");
23724 amit.gupta 404
	}
24240 amit.gupta 405
 
406
	// TemporaryMethod
24237 amit.gupta 407
	public void migrateInvoice() {
408
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(LocalDateTime.now().minusDays(3));
409
		Map<Integer, List<FofoOrder>> partnerOrdersMap = new HashMap<>();
24241 amit.gupta 410
		partnerOrdersMap = fofoOrders.stream()
411
				.collect(Collectors.groupingBy(FofoOrder::getFofoId, Collectors.toList()));
24237 amit.gupta 412
		for (List<FofoOrder> orderList : partnerOrdersMap.values()) {
24240 amit.gupta 413
			int sequence = 0;
414
			String prefix = "";
24241 amit.gupta 415
			List<FofoOrder> sortedList = orderList.stream().sorted((x1, x2) -> x1.getId() - x2.getId())
416
					.collect(Collectors.toList());
417
			for (FofoOrder order : sortedList) {
418
 
24240 amit.gupta 419
				LOGGER.info("Order Id is {}, partner Id is {}", order.getId(), order.getFofoId());
24241 amit.gupta 420
				if (!order.getInvoiceNumber().contains("SEC")) {
24240 amit.gupta 421
					sequence = Integer.parseInt(order.getInvoiceNumber().split("/")[1]);
422
					prefix = order.getInvoiceNumber().split("/")[0];
423
				} else {
424
					sequence += 1;
24241 amit.gupta 425
					String invoiceNumber = prefix + "/" + sequence;
24240 amit.gupta 426
					order.setInvoiceNumber(invoiceNumber);
427
					fofoOrderRepository.persist(order);
428
				}
429
			}
24241 amit.gupta 430
 
24237 amit.gupta 431
		}
432
	}
23724 amit.gupta 433
 
24241 amit.gupta 434
	// Temporary Method
24252 amit.gupta 435
	public void evaluateExcessSchemeOut() throws Exception {
24244 amit.gupta 436
		Map<Integer, String> userNameMap = retailerService.getAllFofoRetailerIdNameMap();
437
		Map<Integer, Float> userAmountMap = new HashMap<>();
24252 amit.gupta 438
 
24592 amit.gupta 439
		List<List<?>> rows = new ArrayList<>();
24271 amit.gupta 440
		List<String> headers = Arrays.asList("Scheme", "Item", "Partner", "Amount", "Credited On", "Invoice Number",
441
				"Sale On", "Scheme Start", "Scheme End", "Active On", "Expired On");
24241 amit.gupta 442
		schemeRepository.selectAll().stream().forEach(x -> {
24250 amit.gupta 443
			if (x.getType().equals(SchemeType.OUT)) {
444
				List<SchemeInOut> sioList = schemeInOutRepository
445
						.selectBySchemeIds(new HashSet<>(Arrays.asList(x.getId())));
446
				if (x.getActiveTimestamp() != null) {
447
					LocalDateTime endDateTime = x.getEndDateTime();
448
					if (x.getExpireTimestamp() != null && x.getExpireTimestamp().isBefore(x.getEndDateTime())) {
449
						endDateTime = x.getExpireTimestamp();
24249 amit.gupta 450
					}
24250 amit.gupta 451
					for (SchemeInOut sio : sioList) {
452
						InventoryItem inventoryItem = null;
24266 amit.gupta 453
						inventoryItem = inventoryItemRepository.selectById(sio.getInventoryItemId());
24271 amit.gupta 454
						FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndSerialNumber(
455
								inventoryItem.getFofoId(), inventoryItem.getSerialNumber(), null, null, 0, 1).get(0);
24250 amit.gupta 456
						Optional<ScanRecord> record = scanRecordRepository
457
								.selectByInventoryItemId(sio.getInventoryItemId()).stream()
458
								.filter(y -> y.getType().equals(ScanType.SALE)).findFirst();
459
						if (record.isPresent()) {
460
							int fofoId = record.get().getFofoId();
461
							if (record.get().getCreateTimestamp().isAfter(endDateTime)
462
									|| record.get().getCreateTimestamp().isBefore(x.getStartDateTime())) {
463
								if (!userAmountMap.containsKey(fofoId)) {
464
									userAmountMap.put(fofoId, 0f);
465
								}
466
								userAmountMap.put(fofoId, sio.getAmount() + userAmountMap.get(fofoId));
467
								try {
24252 amit.gupta 468
									rows.add(Arrays.asList(x.getDescription(),
24250 amit.gupta 469
											itemRepository.selectById(inventoryItem.getItemId()).getItemDescription(),
24252 amit.gupta 470
											userNameMap.get(fofoId), sio.getAmount(),
24253 amit.gupta 471
											FormattingUtils.formatDate(sio.getCreateTimestamp()),
472
											fofoOrder.getInvoiceNumber(),
473
											FormattingUtils.formatDate(record.get().getCreateTimestamp()),
474
											FormattingUtils.formatDate(x.getStartDateTime()),
475
											FormattingUtils.formatDate(x.getEndDateTime()),
476
											FormattingUtils.formatDate(x.getActiveTimestamp()),
477
											FormattingUtils.formatDate(x.getExpireTimestamp())));
24250 amit.gupta 478
								} catch (Exception e) {
479
									e.printStackTrace();
480
								}
24242 amit.gupta 481
							}
24241 amit.gupta 482
						}
483
					}
484
				}
485
			}
486
		});
24246 amit.gupta 487
		userAmountMap.entrySet().stream()
488
				.forEach(x -> LOGGER.info("{} to be deducted from {}({}) for wrongly disbursed due to technical error.",
489
						x.getValue(), userNameMap.get(x.getKey())));
24241 amit.gupta 490
 
24252 amit.gupta 491
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
24271 amit.gupta 492
		Utils.sendMailWithAttachment(googleMailSender,
493
				new String[] { "amit.gupta@shop2020.in", "adeel.yazdani@smartdukaan.com" }, null,
494
				"Partner Excess Amount", "PFA", "ListofSchemes.csv", new ByteArrayResource(baos.toByteArray()));
24252 amit.gupta 495
 
24241 amit.gupta 496
	}
24271 amit.gupta 497
 
24256 amit.gupta 498
	public void processScheme(int offset) throws Exception {
24462 amit.gupta 499
		LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(offset);
24259 amit.gupta 500
		LocalDateTime endDate = startDate.plusDays(30);
24258 amit.gupta 501
		processScheme(startDate, endDate);
24256 amit.gupta 502
	}
24533 govind 503
 
24461 amit.gupta 504
	public void processScheme(int offset, int durationDays) throws Exception {
24462 amit.gupta 505
		LocalDateTime startDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(offset);
24461 amit.gupta 506
		LocalDateTime endDate = startDate.plusDays(durationDays);
507
		processScheme(startDate, endDate);
508
	}
24271 amit.gupta 509
 
23738 amit.gupta 510
	public void processScheme() throws Exception {
24256 amit.gupta 511
		LocalDateTime fromDate = LocalDateTime.now().minusDays(30);
512
		processScheme(fromDate, LocalDateTime.now());
513
	}
24271 amit.gupta 514
 
24256 amit.gupta 515
	public void processScheme(LocalDateTime startDate, LocalDateTime endDate) throws Exception {
23724 amit.gupta 516
		LOGGER.info("Started execution at {}", LocalDateTime.now());
24561 amit.gupta 517
		try {
24587 amit.gupta 518
			List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
519
			for (Purchase purchase : purchases) {
520
				schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
521
			}
24271 amit.gupta 522
 
24587 amit.gupta 523
			List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
524
			for (FofoOrder fofoOrder : fofoOrders) {
525
				schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
526
			}
527
		} catch (Exception e) {
24561 amit.gupta 528
			e.printStackTrace();
24565 amit.gupta 529
			throw e;
24561 amit.gupta 530
		}
23724 amit.gupta 531
		LOGGER.info("Schemes process successfully.");
532
	}
23929 amit.gupta 533
 
23739 amit.gupta 534
	public void processRechargeCashback() throws Throwable {
23761 amit.gupta 535
		LocalDateTime cashbackTime = LocalDateTime.now();
23929 amit.gupta 536
		int referenceId = (int) Timestamp.valueOf(cashbackTime).getTime() / 1000;
537
		List<RechargeTransaction> pendingTransactions = rechargeTransactionRepository
538
				.getPendingCashBackRehargeTransactions();
539
		Map<Object, Double> totalRetailerCashbacks = pendingTransactions.stream().collect(
540
				Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingDouble(x -> x.getCommission())));
541
		for (Map.Entry<Object, Double> totalRetailerCashback : totalRetailerCashbacks.entrySet()) {
542
			int retailerId = (Integer) totalRetailerCashback.getKey();
23739 amit.gupta 543
			float amount = totalRetailerCashback.getValue().floatValue();
23929 amit.gupta 544
			if (Math.round(amount) > 0) {
545
				walletService.addAmountToWallet(retailerId, referenceId, WalletReferenceType.CASHBACK,
546
						"Recharge Cashback", Math.round(amount));
23762 amit.gupta 547
			}
23739 amit.gupta 548
		}
23929 amit.gupta 549
		for (RechargeTransaction rt : pendingTransactions) {
23761 amit.gupta 550
			rt.setCashbackTimestamp(cashbackTime);
551
			rt.setCashbackReference(referenceId);
552
			rechargeTransactionRepository.persist(rt);
553
		}
23739 amit.gupta 554
		LOGGER.info("Cashbacks for Recharge processed Successfully");
555
	}
23724 amit.gupta 556
 
24271 amit.gupta 557
	public void sendPartnerInvestmentDetails(List<String> sendTo) throws Exception {
24277 amit.gupta 558
		LocalDate yesterDay = LocalDate.now().minusDays(1);
23929 amit.gupta 559
		List<FofoStore> fofoStores = fofoStoreRepository.selectAll();
560
		Map<Integer, CustomRetailer> customRetailerMap = retailerService
561
				.getFofoRetailers(fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList()));
562
 
24271 amit.gupta 563
		List<String> headers = Arrays.asList("Code", "StoreName", "Email", "Mobile", "Wallet Amount",
564
				"Yesterday's Sale", "In Stock Amount", "Return In Transit Stock", "Unbilled Amount",
565
				"Grn Pending Amount", "Min Investment", "Investment Amount", "Investment Short");
24592 amit.gupta 566
		List<List<?>> rows = new ArrayList<>();
24002 amit.gupta 567
		for (FofoStore fofoStore : fofoStores) {
568
			CustomRetailer retailer = customRetailerMap.get(fofoStore.getId());
569
			if (retailer == null) {
570
				LOGGER.info("Could not find retailer with retailer Id {}", fofoStore.getId());
571
				continue;
572
			}
24533 govind 573
			PartnerDailyInvestment partnerDailyInvestment = partnerInvestmentService.getInvestment(fofoStore.getId(),
574
					1);
24337 amit.gupta 575
			partnerDailyInvestment.setDate(yesterDay);
576
			partnerDailyInvestmentRepository.persist(partnerDailyInvestment);
24533 govind 577
 
24002 amit.gupta 578
			List<Object> row = Arrays.asList(fofoStore.getCode(), retailer.getBusinessName(), retailer.getEmail(),
24337 amit.gupta 579
					retailer.getMobileNumber(), partnerDailyInvestment.getWalletAmount(),
580
					partnerDailyInvestment.getSalesAmount(), partnerDailyInvestment.getInStockAmount(), 0,
24415 amit.gupta 581
					partnerDailyInvestment.getUnbilledAmount(), partnerDailyInvestment.getGrnPendingAmount(),
24533 govind 582
					partnerDailyInvestment.getMinInvestment(), partnerDailyInvestment.getTotalInvestment(),
583
					partnerDailyInvestment.getShortInvestment());
24002 amit.gupta 584
			rows.add(row);
585
 
23929 amit.gupta 586
		}
24271 amit.gupta 587
		String fileName = "InvestmentSummary-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
24002 amit.gupta 588
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
24271 amit.gupta 589
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
590
 
591
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Partner Investment Summary", "PFA", fileName,
592
				new ByteArrayResource(baos.toByteArray()));
593
 
23929 amit.gupta 594
	}
24177 govind 595
 
24271 amit.gupta 596
	public void sendPartnerInvestmentDetails() throws Exception {
597
		List<String> sendTo = Arrays.asList("adeel.yazdani@smartdukaan.com", "amandeep.singh@smartdukaan.com",
598
				"tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com", "dhruv.kathpal@smartdukaan.com",
599
				"neeraj.gupta@smartdukaan.com");
600
		this.sendPartnerInvestmentDetails(sendTo);
601
 
602
	}
603
 
24177 govind 604
	private void sendMailWithAttachments(String[] email, String[] ccEmails, String body, String subject,
24187 govind 605
			Map<String, InputStream> inputStreams)
24177 govind 606
			throws MessagingException, ProfitMandiBusinessException, IOException {
24121 govind 607
		MimeMessage message = mailSender.createMimeMessage();
24177 govind 608
		MimeMessageHelper helper = new MimeMessageHelper(message, true, CharEncoding.UTF_8);
609
		helper.setSubject(subject);
610
		helper.setText(body);
611
		if (ccEmails != null) {
612
			helper.setCc(ccEmails);
613
		}
24240 amit.gupta 614
		for (String attachment : inputStreams.keySet()) {
615
			helper.addAttachment(attachment + "_" + LocalDate.now() + ".xls",
616
					new ByteArrayResource(IOUtils.toByteArray(inputStreams.get(attachment))));
24187 govind 617
		}
24177 govind 618
		helper.setTo(email);
24195 govind 619
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
24177 govind 620
		helper.setFrom(senderAddress);
621
		mailSender.send(message);
24135 govind 622
	}
24240 amit.gupta 623
 
624
	private void sendMailWithAttachmentsForPartners(String email, String body, String subject, InputStream is)
24184 govind 625
			throws MessagingException, ProfitMandiBusinessException, IOException {
626
		MimeMessage message = mailSender.createMimeMessage();
627
		MimeMessageHelper helper = new MimeMessageHelper(message, true, CharEncoding.UTF_8);
628
		helper.setSubject(subject);
629
		helper.setText(body);
24240 amit.gupta 630
		helper.addAttachment("DailySaleTargetReports_" + LocalDate.now() + ".xls",
631
				new ByteArrayResource(IOUtils.toByteArray(is)));
24184 govind 632
		helper.setTo(email);
24195 govind 633
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
24184 govind 634
		helper.setFrom(senderAddress);
635
		mailSender.send(message);
636
	}
24177 govind 637
 
638
	public void sendMailToSalesHeadAboutTargetAndSales(SaleHeadDetails salesHeadDetail)
639
			throws MessagingException, ProfitMandiBusinessException, IOException {
640
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
641
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
642
		Map<String, InputStream> inputStreams = new HashMap<>();
643
		for (PartnerTargetDetails partnerTargetDetail : partnerTargetDetails) {
644
			InputStream is = targetService.getDailySaleReportVsTargetForSaleHead(partnerTargetDetail,
645
					salesHeadDetail.getName());
24240 amit.gupta 646
 
24177 govind 647
			inputStreams.put(partnerTargetDetail.getTargetName(), is);
648
 
24174 govind 649
		}
24240 amit.gupta 650
		// String[] ccEmails = null;
24271 amit.gupta 651
		if (partnerTargetDetails.size() > 0) {
24254 govind 652
			String[] ccEmails = { "Tarun.verma@smartdukaan.com", "Kamini.sharma@smartdukaan.com",
653
					"chaitnaya.vats@smartdukaan.com", "dhruv.kathpal@smartdukaan.com" };
654
			String subject = "Daily Sales Report ";
655
			String message = MessageFormat.format("Sale Target summary for {0}", LocalDate.now());
656
			LOGGER.info("message" + message);
657
			if (salesHeadDetail.getName().equals("Kamal")) {
658
				LOGGER.info("salesHeadDetail.getName()" + salesHeadDetail.getName());
659
				String[] to = { salesHeadDetail.getEmail(), "mohinder.mutreja@smartdukaan.com" };
24177 govind 660
 
24271 amit.gupta 661
				this.sendMailWithAttachments(to, ccEmails, message, subject, inputStreams);
24177 govind 662
 
24271 amit.gupta 663
			} else {
664
				LOGGER.info("salesHeadDetail.getName()" + salesHeadDetail.getName());
665
				String[] to = { salesHeadDetail.getEmail() };
666
				this.sendMailWithAttachments(to, ccEmails, message, subject, inputStreams);
667
			}
24177 govind 668
		}
24121 govind 669
	}
24177 govind 670
 
24240 amit.gupta 671
	public void sendMailToPartnerAboutTargetAndSales() throws ProfitMandiBusinessException, MessagingException,
672
			IOException, EncryptedDocumentException, InvalidFormatException {
24177 govind 673
		List<Integer> fofoIds = targetService.getfofoIdsFromfofoStore();
674
		Map<Integer, CustomRetailer> fofoIdsAndCustomRetailer = retailerService
675
				.getFofoRetailers(new ArrayList<>(fofoIds));
24240 amit.gupta 676
		List<InputStream> input = new ArrayList<>();
24177 govind 677
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
678
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
679
		for (Integer fofoId : fofoIds) {
24240 amit.gupta 680
			InputStream is = targetService.getDailySaleReportVsTargetForPartner(fofoId, partnerTargetDetails);
681
			LOGGER.info("is" + is);
682
			if (is == null) {
24192 govind 683
				continue;
684
			}
24240 amit.gupta 685
			LOGGER.info("fofoId" + fofoId);
686
 
24177 govind 687
			LOGGER.info(fofoIdsAndCustomRetailer.get(fofoId).getEmail());
24240 amit.gupta 688
			String subject = "Daily Sales Report";
689
			String message = MessageFormat.format("Sale Target summary for {0}", LocalDate.now());
24177 govind 690
			LOGGER.info(message);
24240 amit.gupta 691
			this.sendMailWithAttachmentsForPartners(fofoIdsAndCustomRetailer.get(fofoId).getEmail(), message, subject,
692
					is);
693
 
24174 govind 694
		}
695
	}
24533 govind 696
 
697
	public void moveImeisToPriceDropImeis() throws Exception {
24431 amit.gupta 698
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24533 govind 699
		for (PriceDrop priceDrop : priceDrops) {
24431 amit.gupta 700
			priceDropService.priceDropStatus(priceDrop.getId());
701
		}
702
	}
23929 amit.gupta 703
 
24542 amit.gupta 704
	public void walletmismatch() throws Exception {
705
		LocalDate curDate = LocalDate.now();
24553 amit.gupta 706
		List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
24552 amit.gupta 707
		System.out.println(pdis.size());
24542 amit.gupta 708
		for (PartnerDailyInvestment pdi : pdis) {
24549 amit.gupta 709
			int fofoId = pdi.getFofoId();
24542 amit.gupta 710
			for (PartnerDailyInvestment investment : Lists
711
					.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
24552 amit.gupta 712
				float statementAmount = walletService.getOpeningTill(fofoId,
24555 amit.gupta 713
						investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
24552 amit.gupta 714
				CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
24561 amit.gupta 715
				LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), investment.getDate().toString(),
716
						investment.getWalletAmount(), statementAmount);
24551 amit.gupta 717
 
24542 amit.gupta 718
			}
24549 amit.gupta 719
		}
24542 amit.gupta 720
 
721
	}
722
 
24533 govind 723
	public void escalateTicket() throws ProfitMandiBusinessException {
24653 govind 724
		List<Ticket> tickets = ticketRepository.selectAllNotClosedTickets().stream()
725
				.filter(x -> x.getLastActivity() != ActivityType.RESOLVED).collect(Collectors.toList());
24571 amit.gupta 726
		LocalDateTime now = LocalDateTime.now();
24533 govind 727
		for (Ticket ticket : tickets) {
24571 amit.gupta 728
			if (ticket.getL2EscalationTimestamp().isBefore(now) && ticket.getL3EscalationTimestamp().isAfter(now)) {
24533 govind 729
				TicketAssigned ticketAssigned = ticketAssignedRepository
730
						.selectByAssigneeIdAndTicketId(ticket.getL2AuthUser(), ticket.getId());
731
				if (ticketAssigned == null) {
732
					ticketAssigned = new TicketAssigned();
733
					ticketAssigned.setAssineeId(ticket.getL2AuthUser());
734
					ticketAssigned.setTicketId(ticket.getId());
735
					ticketAssignedRepository.persist(ticketAssigned);
736
					String subject = "Escalated Ticket";
737
					LOGGER.info(subject);
738
 
739
					String message = MessageFormat.format(Escalate_TICKET,
740
							authRepository.selectById(ticket.getL1AuthUser()).getFirstName(),
741
							retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName(),
742
							authRepository.selectById(ticket.getL2AuthUser()).getFirstName());
743
					LOGGER.info(message);
744
 
745
					String[] cc = { authRepository.selectById(ticket.getL2AuthUser()).getEmailId() };
746
					LOGGER.info(cc[0]);
747
 
748
					String to = authRepository.selectById(ticket.getL1AuthUser()).getEmailId();
749
					LOGGER.info(to);
750
 
751
					this.sendEscaltedTicketMail(to, subject, message, cc);
752
					LOGGER.info(subject + " " + message + " " + to + " " + cc[0]);
753
				}
24571 amit.gupta 754
			} else if (ticket.getL3EscalationTimestamp().isBefore(now)
755
					&& ticket.getLastEscalationTimestamp().isAfter(now)) {
24533 govind 756
				TicketAssigned ticketAssigned = ticketAssignedRepository
757
						.selectByAssigneeIdAndTicketId(ticket.getL3AuthUser(), ticket.getId());
758
				if (ticketAssigned == null) {
759
					ticketAssigned = new TicketAssigned();
760
					ticketAssigned.setAssineeId(ticket.getL3AuthUser());
761
					ticketAssigned.setTicketId(ticket.getId());
762
					ticketAssignedRepository.persist(ticketAssigned);
763
					String subject = "Escalated Ticket";
764
					String message = MessageFormat.format(Escalate_TICKET,
765
							authRepository.selectById(ticket.getL2AuthUser()).getFirstName(),
766
							retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName(),
767
							authRepository.selectById(ticket.getL3AuthUser()).getFirstName());
768
					LOGGER.info(subject);
769
					LOGGER.info(message);
770
					String[] cc = { authRepository.selectById(ticket.getL3AuthUser()).getEmailId() };
771
					LOGGER.info(cc[0]);
772
 
773
					String to = authRepository.selectById(ticket.getL2AuthUser()).getEmailId();
774
					LOGGER.info(to);
775
					this.sendEscaltedTicketMail(to, subject, message, cc);
776
					LOGGER.info(subject);
777
				}
778
			}
779
		}
780
	}
781
 
782
	private void sendEscaltedTicketMail(String to, String subject, String message, String[] cc)
783
			throws ProfitMandiBusinessException {
784
		try {
785
			Utils.sendMailWithAttachments(mailSender, to, cc, subject, message, null);
786
			LOGGER.info("mail send successfully");
787
		} catch (Exception e) {
788
			throw new ProfitMandiBusinessException("Escalated Ticket", to, "Could not send Escalated ticket mail");
789
		}
790
	}
791
 
24542 amit.gupta 792
	public void gst() throws Exception {
24548 amit.gupta 793
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2019, 1, 26).atStartOfDay(),
794
				LocalDate.of(2019, 1, 27).atTime(LocalTime.MAX));
795
		for (FofoOrder fofoOrder : fofoOrders) {
796
			int retailerAddressId = retailerRegisteredAddressRepository
797
					.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24542 amit.gupta 798
 
799
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
800
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
801
			Integer stateId = null;
802
			if (customerAddress.getState().equals(retailerAddress.getState())) {
803
				try {
804
					stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
805
				} catch (Exception e) {
806
					LOGGER.error("Unable to get state rates");
807
				}
808
			}
809
			Map<Integer, GstRate> itemIdStateTaxRateMap = null;
810
			Map<Integer, Float> itemIdIgstTaxRateMap = null;
24548 amit.gupta 811
 
812
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
813
			Set<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
24542 amit.gupta 814
			if (stateId != null) {
815
				itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemIds), stateId);
816
			} else {
817
				itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemIds));
818
			}
819
 
24548 amit.gupta 820
			for (FofoOrderItem foi : fofoOrderItems) {
24542 amit.gupta 821
				if (stateId == null) {
822
					foi.setIgstRate(itemIdIgstTaxRateMap.get(foi.getItemId()));
823
				} else {
824
					foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
825
					foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
826
				}
827
				fofoOrderItemRepository.persist(foi);
828
			}
829
		}
24548 amit.gupta 830
 
24542 amit.gupta 831
	}
832
 
24580 amit.gupta 833
	public void schemewalletmismatch() {
834
		LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
24587 amit.gupta 835
		while (dateToReconcile.isBefore(LocalDate.now())) {
24580 amit.gupta 836
			reconcileSchemes(dateToReconcile);
24587 amit.gupta 837
			// reconcileOrders(dateTime);
838
			// reconcileRecharges(dateTime);
24580 amit.gupta 839
			dateToReconcile = dateToReconcile.plusDays(1);
840
		}
841
	}
842
 
843
	private void reconcileSchemes(LocalDate date) {
844
		LocalDateTime startDate = date.atStartOfDay();
845
		LocalDateTime endDate = startDate.plusDays(1);
846
		List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
847
		List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
24587 amit.gupta 848
		double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
849
		double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
24580 amit.gupta 850
		double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
24587 amit.gupta 851
		List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN,
852
				WalletReferenceType.SCHEME_OUT);
853
		List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
854
				walletReferenceTypes);
855
		double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
856
		if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
24580 amit.gupta 857
			LOGGER.info("Scheme Amount mismatched for Date {}", date);
24587 amit.gupta 858
 
859
			Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(Collectors
860
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
861
 
862
			Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet())
863
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
864
							Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
865
 
866
			Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(Collectors
867
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
868
 
869
			Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository
870
					.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream()
871
					.collect(Collectors.groupingBy(x -> x.getFofoId(),
872
							Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
873
 
874
			Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
875
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeMap.entrySet()) {
876
			}
877
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
878
				if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
879
					finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
880
				} else {
881
					finalUserSchemeAmountMap.put(schemeAmount.getKey(),
882
							finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
883
				}
884
			}
24590 amit.gupta 885
			Map<Integer, Integer> userWalletMap = userWalletRepository
886
					.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream()
887
					.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
888
 
24587 amit.gupta 889
			Map<Integer, Double> walletAmountMap = history.stream().collect(Collectors.groupingBy(
890
					UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
891
			for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
892
				double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
893
				if (diff > 5) {
894
					LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
895
				}
896
			}
24580 amit.gupta 897
		}
24587 amit.gupta 898
 
24580 amit.gupta 899
	}
24590 amit.gupta 900
 
24592 amit.gupta 901
	public void dryRunSchemeReco() throws Exception {
24635 amit.gupta 902
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
903
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
904
 
24592 amit.gupta 905
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
906
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24635 amit.gupta 907
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
908
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
909
		Set<String> serialNumbersConsidered = new HashSet<>();
910
 
911
		LocalDateTime startDate = LocalDate.of(2018, 9, 1).atStartOfDay();
912
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
913
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
914
 
24670 amit.gupta 915
		Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap(); 
24635 amit.gupta 916
		purchases.stream().forEach(purchase -> {
917
			float amountToRollback = 0;
918
			String description = "Adjustment of Duplicate Scheme for Purchase Invoice "
919
					+ purchase.getPurchaseReference();
920
			Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId())
921
					.stream().filter(ii -> ii.getSerialNumber() != null)
922
					.collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
923
			if (inventorySerialNumberMap.size() > 0) {
924
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
925
					String serialNumber = inventorySerialNumberEntry.getValue();
926
					int inventoryItemId = inventorySerialNumberEntry.getKey();
927
					if (serialNumbersConsidered.contains(serialNumber)) {
928
						// This will rollback scheme for differenct orders for same serial
929
						List<SchemeInOut> sios = schemeInOutRepository
930
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
931
								.filter(x -> x.getRolledBackTimestamp() == null
932
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
933
								.collect(Collectors.toList());
934
						Collections.reverse(sios);
935
						for (SchemeInOut sio : sios) {
936
							sio.setRolledBackTimestamp(LocalDateTime.now());
937
							amountToRollback += sio.getAmount();
938
							// sio.setSchemeType(SchemeType.OUT);
939
							sio.setSerialNumber(serialNumber);
940
							rolledbackSios.add(sio);
941
						}
942
						description = description.concat(" " + serialNumber + " ");
943
					} else {
944
						serialNumbersConsidered.add(serialNumber);
945
						List<Integer> schemesConsidered = new ArrayList<>();
946
						List<SchemeInOut> sios = schemeInOutRepository
947
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
948
								.filter(x -> x.getRolledBackTimestamp() == null
949
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
950
								.collect(Collectors.toList());
951
						Collections.reverse(sios);
952
						for (SchemeInOut sio : sios) {
953
							if (!schemesConsidered.contains(sio.getSchemeId())) {
954
								schemesConsidered.add(sio.getSchemeId());
955
								continue;
956
							}
957
							sio.setRolledBackTimestamp(LocalDateTime.now());
958
							amountToRollback += sio.getAmount();
959
							// sio.setSchemeType(SchemeType.OUT);
960
							sio.setSerialNumber(serialNumber);
24670 amit.gupta 961
							sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
962
							sio.setReference(purchase.getId());
24635 amit.gupta 963
							rolledbackSios.add(sio);
964
						}
965
					}
966
 
967
				}
968
			}
969
			if (amountToRollback > 0) {
24670 amit.gupta 970
				//Address address = addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
24635 amit.gupta 971
				UserWalletHistory uwh = new UserWalletHistory();
972
				uwh.setAmount(Math.round(amountToRollback));
973
				uwh.setDescription(description);
974
				uwh.setTimestamp(LocalDateTime.now());
24670 amit.gupta 975
				uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
24635 amit.gupta 976
				uwh.setReference(purchase.getId());
977
				uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
978
				uwh.setFofoId(purchase.getFofoId());
24670 amit.gupta 979
				uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
24635 amit.gupta 980
				userWalletHistory.add(uwh);
981
			}
982
		});
983
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
984
				Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
985
						"Timestamp"),
986
				userWalletHistory.stream()
987
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
988
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
989
						.collect(Collectors.toList()));
990
 
991
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
24670 amit.gupta 992
				Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount", "Created",
24635 amit.gupta 993
						"Rolledback"),
994
				rolledbackSios.stream()
24670 amit.gupta 995
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(),
24635 amit.gupta 996
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
997
						.collect(Collectors.toList()));
998
 
999
		Utils.sendMailWithAttachments(googleMailSender,
1000
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24636 amit.gupta 1001
				"Partner Excess Amount Scheme In", "PFA",
24635 amit.gupta 1002
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
24636 amit.gupta 1003
						new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24635 amit.gupta 1004
 
1005
		throw new Exception();
1006
 
1007
	}
1008
 
1009
	public void dryRunOutSchemeReco() throws Exception {
1010
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1011
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24606 amit.gupta 1012
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1013
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24590 amit.gupta 1014
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1015
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
24631 amit.gupta 1016
		LocalDateTime startDate = LocalDate.of(2018, 9, 1).atStartOfDay();
24632 amit.gupta 1017
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
24631 amit.gupta 1018
		List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
1019
		// Collections.reverse(allOrders);
1020
		// List<FofoOrder> allOrders =
24653 govind 1021
		// List<FofoOrder> allOrders =
24631 amit.gupta 1022
		// Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
24625 amit.gupta 1023
		Set<String> serialNumbersConsidered = new HashSet<>();
24590 amit.gupta 1024
		allOrders.stream().forEach(fofoOrder -> {
24592 amit.gupta 1025
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
24598 amit.gupta 1026
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
24592 amit.gupta 1027
			float amountToRollback = 0;
24590 amit.gupta 1028
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1029
			orderItems.forEach(x -> {
24606 amit.gupta 1030
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
24598 amit.gupta 1031
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
24590 amit.gupta 1032
			});
24606 amit.gupta 1033
			if (inventorySerialNumberMap.size() > 0) {
24631 amit.gupta 1034
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1035
					String serialNumber = inventorySerialNumberEntry.getValue();
1036
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1037
					if (serialNumbersConsidered.contains(serialNumber)) {
1038
						// This will rollback scheme for differenct orders for same serial
1039
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1040
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1041
								.filter(x -> x.getRolledBackTimestamp() == null
1042
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1043
								.collect(Collectors.toList());
1044
						Collections.reverse(sios);
1045
						for (SchemeInOut sio : sios) {
1046
							sio.setRolledBackTimestamp(LocalDateTime.now());
1047
							amountToRollback += sio.getAmount();
1048
							// sio.setSchemeType(SchemeType.OUT);
1049
							sio.setSerialNumber(serialNumber);
1050
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
24670 amit.gupta 1051
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1052
							rolledbackSios.add(sio);
24623 amit.gupta 1053
						}
24635 amit.gupta 1054
						description = description.concat(" " + serialNumber + " ");
24631 amit.gupta 1055
					} else {
1056
						serialNumbersConsidered.add(serialNumber);
1057
						List<Integer> schemesConsidered = new ArrayList<>();
1058
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1059
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1060
								.filter(x -> x.getRolledBackTimestamp() == null
1061
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1062
								.collect(Collectors.toList());
1063
						Collections.reverse(sios);
1064
						for (SchemeInOut sio : sios) {
1065
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1066
								schemesConsidered.add(sio.getSchemeId());
1067
								continue;
1068
							}
1069
							sio.setRolledBackTimestamp(LocalDateTime.now());
1070
							amountToRollback += sio.getAmount();
1071
							// sio.setSchemeType(SchemeType.OUT);
24670 amit.gupta 1072
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1073
							sio.setSerialNumber(serialNumber);
1074
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1075
							rolledbackSios.add(sio);
1076
						}
24615 amit.gupta 1077
					}
24631 amit.gupta 1078
 
24604 amit.gupta 1079
				}
24590 amit.gupta 1080
			}
24631 amit.gupta 1081
			if (amountToRollback > 0) {
1082
				UserWalletHistory uwh = new UserWalletHistory();
1083
				uwh.setAmount(Math.round(amountToRollback));
1084
				uwh.setDescription(description);
1085
				uwh.setTimestamp(LocalDateTime.now());
1086
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1087
				uwh.setReference(fofoOrder.getId());
1088
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1089
				uwh.setFofoId(fofoOrder.getFofoId());
1090
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1091
				userWalletHistory.add(uwh);
1092
			}
24590 amit.gupta 1093
		});
24598 amit.gupta 1094
 
24592 amit.gupta 1095
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
24670 amit.gupta 1096
				Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
24615 amit.gupta 1097
						"Timestamp"),
1098
				userWalletHistory.stream()
1099
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1100
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24592 amit.gupta 1101
						.collect(Collectors.toList()));
1102
 
1103
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1104
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1105
						"Rolledback"),
1106
				rolledbackSios.stream()
1107
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1108
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1109
						.collect(Collectors.toList()));
1110
 
24623 amit.gupta 1111
		Utils.sendMailWithAttachments(googleMailSender,
1112
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24670 amit.gupta 1113
				"Partner Excess Amount Scheme Out", "PFA",
24598 amit.gupta 1114
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1115
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1116
 
24628 amit.gupta 1117
		throw new Exception();
24590 amit.gupta 1118
	}
24615 amit.gupta 1119
 
24611 amit.gupta 1120
	public void dryRunSchemeOutReco1() throws Exception {
24615 amit.gupta 1121
		List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
24611 amit.gupta 1122
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1123
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
1124
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1125
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1126
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1127
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1128
		references.stream().forEach(reference -> {
1129
			FofoOrder fofoOrder = null;
1130
			try {
1131
				fofoOrder = fofoOrderRepository.selectByOrderId(reference);
24615 amit.gupta 1132
			} catch (Exception e) {
1133
 
24611 amit.gupta 1134
			}
1135
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
1136
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
1137
			float amountToRollback = 0;
1138
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1139
			orderItems.forEach(x -> {
1140
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
1141
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
1142
			});
1143
			if (inventorySerialNumberMap.size() > 0) {
24615 amit.gupta 1144
				List<SchemeInOut> sios = schemeInOutRepository
1145
						.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream()
1146
						.filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24611 amit.gupta 1147
						.collect(Collectors.toList());
1148
				LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
1149
				UserWalletHistory uwh = new UserWalletHistory();
24615 amit.gupta 1150
				Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream()
1151
						.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
24611 amit.gupta 1152
				for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
1153
					List<SchemeInOut> outList = inventorySioEntry.getValue();
24615 amit.gupta 1154
					if (outList.size() > 1) {
1155
 
24611 amit.gupta 1156
					}
1157
				}
1158
				uwh.setAmount(Math.round(amountToRollback));
1159
				uwh.setDescription(description);
1160
				uwh.setTimestamp(LocalDateTime.now());
1161
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1162
				uwh.setReference(fofoOrder.getId());
1163
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1164
				uwh.setFofoId(fofoOrder.getFofoId());
1165
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1166
				userWalletHistory.add(uwh);
1167
			}
1168
		});
24615 amit.gupta 1169
 
24611 amit.gupta 1170
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1171
				Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"),
1172
				userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(),
1173
						x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24615 amit.gupta 1174
						.collect(Collectors.toList()));
1175
 
24611 amit.gupta 1176
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1177
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1178
						"Rolledback"),
1179
				rolledbackSios.stream()
24615 amit.gupta 1180
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1181
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1182
						.collect(Collectors.toList()));
1183
 
24623 amit.gupta 1184
		Utils.sendMailWithAttachments(googleMailSender,
1185
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24611 amit.gupta 1186
				"Partner Excess Amount", "PFA",
1187
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1188
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1189
 
24628 amit.gupta 1190
		throw new Exception();
24615 amit.gupta 1191
 
24611 amit.gupta 1192
	}
24615 amit.gupta 1193
 
24653 govind 1194
	public void alertforTicket() throws Exception {
1195
		List<Ticket> tickets = ticketRepository.selectAllNotClosedTickets();
1196
		Map<Integer, List<Ticket>> l1AuthUserAndTicketMap = new HashMap<>();
1197
		Map<Integer, List<Ticket>> l2AuthUserAndTicketMap = new HashMap<>();
1198
		Set<Integer> l1AuthUsers = tickets.stream().map(x -> x.getL1AuthUser()).collect(Collectors.toSet());
1199
		Set<Integer> l2AuthUsers = tickets.stream()
24665 govind 1200
				.filter(x -> x.getL2EscalationTimestamp().isBefore(LocalDateTime.now())).map(x -> x.getL2AuthUser())
24653 govind 1201
				.collect(Collectors.toSet());
1202
		for (Integer l1AuthUser : l1AuthUsers) {
1203
			List<Ticket> ticketsForl1AuthUser = tickets.stream().filter(ticket -> l1AuthUser == ticket.getL1AuthUser())
1204
					.collect(Collectors.toList());
1205
			l1AuthUserAndTicketMap.put(l1AuthUser, ticketsForl1AuthUser);
1206
		}
1207
		for (Integer l2AuthUser : l2AuthUsers) {
1208
			List<Ticket> ticketsForl2AuthUser = tickets.stream().filter(ticket -> l2AuthUser == ticket.getL2AuthUser())
1209
					.collect(Collectors.toList());
1210
			l2AuthUserAndTicketMap.put(l2AuthUser, ticketsForl2AuthUser);
1211
		}
1212
		for (Entry<Integer, List<Ticket>> entry : l1AuthUserAndTicketMap.entrySet()) {
1213
			List<Ticket> ticketsForAuthUser = entry.getValue();
1214
			AuthUser authUser = authRepository.selectById(entry.getKey());
1215
			String message = this.getMessageForAlertTicket(ticketsForAuthUser, EscalationType.L1);
1216
			this.sendMailOfHtmlFomat(authUser.getEmailId(), message, null, "Daily Pending Ticket");
1217
		}
1218
		for (Entry<Integer, List<Ticket>> entry : l2AuthUserAndTicketMap.entrySet()) {
1219
			List<Ticket> ticketsForAuthUser = entry.getValue();
1220
			AuthUser authUser = authRepository.selectById(entry.getKey());
1221
			String message = this.getMessageForAlertTicket(ticketsForAuthUser, EscalationType.L2);
1222
			this.sendMailOfHtmlFomat(authUser.getEmailId(), message, null, "Daily Pending Ticket");
1223
		}
1224
	}
1225
 
1226
	public String getMessageForAlertTicket(List<Ticket> tickets, EscalationType escalationType)
1227
			throws ProfitMandiBusinessException {
1228
		StringBuilder sb = new StringBuilder();
1229
		sb.append("<html><body><p>Your Pending Tickets</p><br/><table style='border:1px solid black ;padding: 5px';>");
1230
		sb.append("<tbody>\n" + "	    				<tr>\n"
1231
				+ "	    					<th style='border:1px solid black;padding: 5px'>Ticket Id</th>\n"
1232
				+ "	    					<th style='border:1px solid black;padding: 5px'>Partner</th>\n"
1233
				+ "	    					<th style='border:1px solid black;padding: 5px'>SubCategory</th>\n"
1234
				+ "	    					<th style='border:1px solid black;padding: 5px'>Remaining Time To Escalate</th>\n"
1235
				+ "	    					<th style='border:1px solid black;padding: 5px'>Escalated</th>\n"
1236
				+ "	    				</tr>");
1237
		for (Ticket ticket : tickets) {
1238
			sb.append("<tr>");
1239
			sb.append("<td style='border:1px solid black;padding: 5px'>" + ticket.getId() + "</td>");
1240
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1241
					+ retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName() + "</td>");
1242
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1243
					+ ticketSubCategoryRepository.selectById(ticket.getSubCategoryId()).getDescription() + "</td>");
1244
			if (escalationType == EscalationType.L1) {
1245
				if (ticket.getL2EscalationTimestamp().isBefore(LocalDateTime.now())) {
1246
					sb.append("<td style='border:1px solid black;padding: 5px'>" + 0 + "</td>");
1247
					sb.append("<td style='border:1px solid black;padding: 5px'>YES</td>");
1248
				} else {
1249
					Duration duration = Duration.between(LocalDateTime.now(), ticket.getL2EscalationTimestamp());
1250
					sb.append("<td style='border:1px solid black;padding: 5px'>" + duration.toHours() + "hrs</td>");
1251
					sb.append("<td style='border:1px solid black;padding: 5px'>NO</td>");
1252
				}
1253
			} else if (escalationType == EscalationType.L2) {
1254
				if (ticket.getL3EscalationTimestamp().isBefore(LocalDateTime.now())) {
1255
					Duration duration = Duration.between(ticket.getL3EscalationTimestamp(), LocalDateTime.now());
1256
					sb.append("<td style='border:1px solid black;padding: 5px'>" + duration.toHours() + " hrs</td>");
1257
					sb.append("<td style='border:1px solid black;padding: 5px'>YES</td>");
1258
				} else {
1259
					sb.append("<td style='border:1px solid black;padding: 5px'>NO</td>");
1260
				}
1261
			}
1262
			sb.append("</tr>");
1263
		}
1264
		sb.append("</tbody></table></body></html>");
1265
		return sb.toString();
1266
	}
1267
 
1268
	private void sendMailOfHtmlFomat(String email, String body, String cc[], String subject)
1269
			throws MessagingException, ProfitMandiBusinessException, IOException {
1270
		MimeMessage message = mailSender.createMimeMessage();
1271
		MimeMessageHelper helper = new MimeMessageHelper(message);
1272
		helper.setSubject(subject);
1273
		helper.setText(body, true);
1274
		helper.setTo(email);
24664 govind 1275
		if(cc!=null) {
24653 govind 1276
		helper.setCc(cc);
24664 govind 1277
		}
24653 govind 1278
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
1279
		helper.setFrom(senderAddress);
1280
		mailSender.send(message);
1281
	}
1282
 
1283
	public void sendDailySalesReportNotificationToPartner()
1284
			throws ProfitMandiBusinessException, MessagingException, IOException {
1285
		LocalDateTime now = LocalDateTime.now();
1286
		LocalDateTime from = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 00, 00);
1287
		Map<Integer, Double> salesByFofoIdMap = new HashMap<>();
1288
		List<Integer> fofoIds = targetService.getfofoIdsFromfofoStore();
1289
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
1290
				.selectAllGeEqAndLeEqStartDateAndEndDate(now);
1291
		DateTimeFormatter timeFormatter = DateTimeFormatter
1292
	            .ofPattern("h a");
1293
 
1294
		Map<Integer,Float> dailyTarget=new HashMap<>();
1295
		for (Integer fofoId : fofoIds) {
1296
			Map<Integer,Float> dailyAverageSale=null;
1297
			double sale = fofoOrderRepository.selectTotalSaleSumByFofoIdBrtweenDate(fofoId, from, now);
1298
			for (PartnerTargetDetails partnerTargetDetail : partnerTargetDetails) {
1299
				Map<Integer, Float> targetValues = targetService.getTargetValueByFofoIdAndTargetId(fofoId,
1300
						partnerTargetDetail.getId());
1301
				if (targetValues.size() == 0) {
1302
					continue;
1303
				} else {
1304
					List<Integer> partnerIds = new ArrayList<>();
1305
					partnerIds.add(fofoId);
1306
					dailyAverageSale = targetService.getDailyAverageSaleForCurrentForSingleFofoIdAndBrand(partnerIds,
1307
							targetValues, partnerTargetDetail.getStartDate(), partnerTargetDetail.getEndDate(),
1308
							partnerTargetDetail.getBrandName());
1309
					dailyTarget.put(fofoId, dailyAverageSale.get(fofoId));
1310
					break;
1311
				}
1312
			}
1313
			NotificationCampaigns notification = new NotificationCampaigns();
1314
			notification.setName("Today's Sale");
1315
			if(dailyAverageSale!=null && dailyAverageSale.get(fofoId)!=null) {
1316
				LOGGER.info("Your today sale till" + " " + now.format(timeFormatter) +" "+ "is" + " " + sale+" "+"vs" +" "+"daily target="+dailyAverageSale.get(fofoId));
1317
			notification.setTitle("Your today sale till" + " " + now.format(timeFormatter) +" "+ "is" + " " + sale+" "+"vs" +" "+"daily target="+dailyAverageSale.get(fofoId));
1318
			}
1319
			else
1320
			{
1321
				notification.setTitle("Your today sale till" + " " + now.format(timeFormatter) +" "+"is" + " " + sale+" "+"vs" +" "+"daily target = 0.0");
1322
				LOGGER.info("Your today sale till" + " " + now.format(timeFormatter) +" "+ "is" + " " + sale+" "+"vs" +" "+"daily target = 0.0");
1323
			}
1324
			// notification.setMessage("Your sale is "+salesbyfofoId.get(fofoId));
1325
			notification.setType("Url");
1326
			notification.setUrl("http://app.profitmandi.com/pages/home/dashboard");
24676 govind 1327
			LOGGER.info("UserID" +userAccountRepository.selectUserIdByRetailerId(fofoId));
24653 govind 1328
			notification
24676 govind 1329
					.setSql("SELECT distinct d1.user_id from devices d1 left join devices d2 on"
24653 govind 1330
							+ "(d1.imeinumber = d2.imeinumber and d1.created < d2.created) "
24676 govind 1331
							+ " where d2.id is null and d1.user_id = "+userAccountRepository.selectUserIdByRetailerId(175120474));
1332
			LOGGER.info("SELECT distinct d1.user_id from devices d1 left join devices d2 on"
1333
							+ "(d1.imeinumber = d2.imeinumber and d1.created < d2.created) "
1334
							+ " where d2.id is null and d1.user_id = "+userAccountRepository.selectUserIdByRetailerId(175120474));
24667 govind 1335
			notification.setExpiresat(LocalDateTime.now().plusDays(1).toEpochSecond(ZoneOffset.UTC) * 1000);
24653 govind 1336
			notification.setStatus("active");
1337
			notification.setSmsprocessed(0);
1338
			notification.setNotification_processed(0);
1339
			notification.setNotification_type("GENERAL_NOTIFICATION");
24657 govind 1340
			mongoClient.persistNotificationCmpInfo(notification);
24653 govind 1341
			salesByFofoIdMap.put(fofoId, sale);
1342
			LOGGER.info(sale);
1343
		}
1344
		String saleReport = this.getDailySalesReportByPartnerId(salesByFofoIdMap,dailyTarget);
1345
		LOGGER.info(saleReport);
1346
		String cc[] = { "Tarun.verma@smartdukaan.com", "Kamini.sharma@smartdukaan.com",
24654 govind 1347
				"chaitnaya.vats@smartdukaan.com","adeel.yazdani@smartdukaan.com","mohinder.mutreja@smartdukaan.com"};
24653 govind 1348
		String subject = "sale report till" + " " + now.format(timeFormatter);
24676 govind 1349
		//this.sendMailOfHtmlFomat("amod.sen@smartdukaan.com", saleReport, cc, subject);
24653 govind 1350
	}
1351
 
1352
	public String getDailySalesReportByPartnerId(Map<Integer, Double> salesByFofoIdMap,Map<Integer, Float> dailyTarget)
1353
			throws ProfitMandiBusinessException {
1354
		StringBuilder sb = new StringBuilder();
1355
		sb.append("<html><body><p>Sale Report:</p><br/><table style='border:1px solid black ;padding: 5px';>");
1356
		sb.append("<tbody>\n" + "	    				<tr>\n"
1357
				+ "	    					<th style='border:1px solid black;padding: 5px'>Partner</th>\n"
1358
				+ "	    					<th style='border:1px solid black;padding: 5px'>Daily Target</th>\n"
1359
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>\n"
1360
				+ "	    				</tr>");
1361
		for (Integer fofoId : salesByFofoIdMap.keySet()) {
1362
			sb.append("<tr>");
1363
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1364
					+ retailerService.getFofoRetailer(fofoId).getBusinessName() + "</td>");
1365
			if(dailyTarget!=null && dailyTarget.get(fofoId)!=null) {
1366
			sb.append("<td style='border:1px solid black;padding: 5px'>" + dailyTarget.get(fofoId) + "</td>");
1367
			}
1368
			else
1369
			{
1370
				sb.append("<td style='border:1px solid black;padding: 5px'>" +0.0+ "</td>");
1371
			}
1372
			sb.append("<td style='border:1px solid black;padding: 5px'>" + salesByFofoIdMap.get(fofoId) + "</td>");
1373
 
1374
			sb.append("</tr>");
1375
		}
1376
 
1377
		sb.append("</tbody></table></body></html>");
1378
		return sb.toString();
1379
	}
24587 amit.gupta 1380
}
24580 amit.gupta 1381
 
24587 amit.gupta 1382
/*
1383
 * public void processSchemeForModel(String string) { pricingService
1384
 * 
1385
 * }
1386
 */