Subversion Repositories SmartDukaan

Rev

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