Subversion Repositories SmartDukaan

Rev

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