Subversion Repositories SmartDukaan

Rev

Rev 24692 | Rev 24707 | 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");
24683 amit.gupta 705
		Attachment attachment = new Attachment(
24692 amit.gupta 706
				"aeging-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
24697 amit.gupta 707
		Utils.sendMailWithAttachments(googleMailSender, sendTo, null, "Stock Aeging Report", "PFA", attachment);
24681 amit.gupta 708
	}
24533 govind 709
 
24697 amit.gupta 710
	public void sendAgeingReport() throws Exception {
711
		sendAgeingReport("amod.sen@smartdukaan.com", "adeel.yazdani@smartdukaan.com", "kamini.sharma@smartdukaan.com",
712
				"tarun.verma@smartdukaan.com", "chaitnaya.vats@smartdukaan.com", "mohinder.mutreja@smartdukaan.com");
713
	}
714
 
24533 govind 715
	public void moveImeisToPriceDropImeis() throws Exception {
24431 amit.gupta 716
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24533 govind 717
		for (PriceDrop priceDrop : priceDrops) {
24431 amit.gupta 718
			priceDropService.priceDropStatus(priceDrop.getId());
719
		}
720
	}
23929 amit.gupta 721
 
24542 amit.gupta 722
	public void walletmismatch() throws Exception {
723
		LocalDate curDate = LocalDate.now();
24553 amit.gupta 724
		List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
24552 amit.gupta 725
		System.out.println(pdis.size());
24542 amit.gupta 726
		for (PartnerDailyInvestment pdi : pdis) {
24549 amit.gupta 727
			int fofoId = pdi.getFofoId();
24542 amit.gupta 728
			for (PartnerDailyInvestment investment : Lists
729
					.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
24552 amit.gupta 730
				float statementAmount = walletService.getOpeningTill(fofoId,
24555 amit.gupta 731
						investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
24552 amit.gupta 732
				CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
24561 amit.gupta 733
				LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), investment.getDate().toString(),
734
						investment.getWalletAmount(), statementAmount);
24551 amit.gupta 735
 
24542 amit.gupta 736
			}
24549 amit.gupta 737
		}
24542 amit.gupta 738
 
739
	}
740
 
24533 govind 741
	public void escalateTicket() throws ProfitMandiBusinessException {
24653 govind 742
		List<Ticket> tickets = ticketRepository.selectAllNotClosedTickets().stream()
743
				.filter(x -> x.getLastActivity() != ActivityType.RESOLVED).collect(Collectors.toList());
24571 amit.gupta 744
		LocalDateTime now = LocalDateTime.now();
24533 govind 745
		for (Ticket ticket : tickets) {
24571 amit.gupta 746
			if (ticket.getL2EscalationTimestamp().isBefore(now) && ticket.getL3EscalationTimestamp().isAfter(now)) {
24533 govind 747
				TicketAssigned ticketAssigned = ticketAssignedRepository
748
						.selectByAssigneeIdAndTicketId(ticket.getL2AuthUser(), ticket.getId());
749
				if (ticketAssigned == null) {
750
					ticketAssigned = new TicketAssigned();
751
					ticketAssigned.setAssineeId(ticket.getL2AuthUser());
752
					ticketAssigned.setTicketId(ticket.getId());
753
					ticketAssignedRepository.persist(ticketAssigned);
754
					String subject = "Escalated Ticket";
755
					LOGGER.info(subject);
756
 
757
					String message = MessageFormat.format(Escalate_TICKET,
758
							authRepository.selectById(ticket.getL1AuthUser()).getFirstName(),
759
							retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName(),
760
							authRepository.selectById(ticket.getL2AuthUser()).getFirstName());
761
					LOGGER.info(message);
762
 
763
					String[] cc = { authRepository.selectById(ticket.getL2AuthUser()).getEmailId() };
764
					LOGGER.info(cc[0]);
765
 
766
					String to = authRepository.selectById(ticket.getL1AuthUser()).getEmailId();
767
					LOGGER.info(to);
768
 
769
					this.sendEscaltedTicketMail(to, subject, message, cc);
770
					LOGGER.info(subject + " " + message + " " + to + " " + cc[0]);
771
				}
24571 amit.gupta 772
			} else if (ticket.getL3EscalationTimestamp().isBefore(now)
773
					&& ticket.getLastEscalationTimestamp().isAfter(now)) {
24533 govind 774
				TicketAssigned ticketAssigned = ticketAssignedRepository
775
						.selectByAssigneeIdAndTicketId(ticket.getL3AuthUser(), ticket.getId());
776
				if (ticketAssigned == null) {
777
					ticketAssigned = new TicketAssigned();
778
					ticketAssigned.setAssineeId(ticket.getL3AuthUser());
779
					ticketAssigned.setTicketId(ticket.getId());
780
					ticketAssignedRepository.persist(ticketAssigned);
781
					String subject = "Escalated Ticket";
782
					String message = MessageFormat.format(Escalate_TICKET,
783
							authRepository.selectById(ticket.getL2AuthUser()).getFirstName(),
784
							retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName(),
785
							authRepository.selectById(ticket.getL3AuthUser()).getFirstName());
786
					LOGGER.info(subject);
787
					LOGGER.info(message);
788
					String[] cc = { authRepository.selectById(ticket.getL3AuthUser()).getEmailId() };
789
					LOGGER.info(cc[0]);
790
 
791
					String to = authRepository.selectById(ticket.getL2AuthUser()).getEmailId();
792
					LOGGER.info(to);
793
					this.sendEscaltedTicketMail(to, subject, message, cc);
794
					LOGGER.info(subject);
795
				}
796
			}
797
		}
798
	}
799
 
800
	private void sendEscaltedTicketMail(String to, String subject, String message, String[] cc)
801
			throws ProfitMandiBusinessException {
802
		try {
803
			Utils.sendMailWithAttachments(mailSender, to, cc, subject, message, null);
804
			LOGGER.info("mail send successfully");
805
		} catch (Exception e) {
806
			throw new ProfitMandiBusinessException("Escalated Ticket", to, "Could not send Escalated ticket mail");
807
		}
808
	}
809
 
24542 amit.gupta 810
	public void gst() throws Exception {
24548 amit.gupta 811
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2019, 1, 26).atStartOfDay(),
812
				LocalDate.of(2019, 1, 27).atTime(LocalTime.MAX));
813
		for (FofoOrder fofoOrder : fofoOrders) {
814
			int retailerAddressId = retailerRegisteredAddressRepository
815
					.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24542 amit.gupta 816
 
817
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
818
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
819
			Integer stateId = null;
820
			if (customerAddress.getState().equals(retailerAddress.getState())) {
821
				try {
822
					stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
823
				} catch (Exception e) {
824
					LOGGER.error("Unable to get state rates");
825
				}
826
			}
827
			Map<Integer, GstRate> itemIdStateTaxRateMap = null;
828
			Map<Integer, Float> itemIdIgstTaxRateMap = null;
24548 amit.gupta 829
 
830
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
831
			Set<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
24542 amit.gupta 832
			if (stateId != null) {
833
				itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemIds), stateId);
834
			} else {
835
				itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemIds));
836
			}
837
 
24548 amit.gupta 838
			for (FofoOrderItem foi : fofoOrderItems) {
24542 amit.gupta 839
				if (stateId == null) {
840
					foi.setIgstRate(itemIdIgstTaxRateMap.get(foi.getItemId()));
841
				} else {
842
					foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
843
					foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
844
				}
845
				fofoOrderItemRepository.persist(foi);
846
			}
847
		}
24548 amit.gupta 848
 
24542 amit.gupta 849
	}
850
 
24580 amit.gupta 851
	public void schemewalletmismatch() {
852
		LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
24587 amit.gupta 853
		while (dateToReconcile.isBefore(LocalDate.now())) {
24580 amit.gupta 854
			reconcileSchemes(dateToReconcile);
24587 amit.gupta 855
			// reconcileOrders(dateTime);
856
			// reconcileRecharges(dateTime);
24580 amit.gupta 857
			dateToReconcile = dateToReconcile.plusDays(1);
858
		}
859
	}
860
 
861
	private void reconcileSchemes(LocalDate date) {
862
		LocalDateTime startDate = date.atStartOfDay();
863
		LocalDateTime endDate = startDate.plusDays(1);
864
		List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
865
		List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
24587 amit.gupta 866
		double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
867
		double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
24580 amit.gupta 868
		double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
24587 amit.gupta 869
		List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN,
870
				WalletReferenceType.SCHEME_OUT);
871
		List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
872
				walletReferenceTypes);
873
		double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
874
		if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
24580 amit.gupta 875
			LOGGER.info("Scheme Amount mismatched for Date {}", date);
24587 amit.gupta 876
 
877
			Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(Collectors
878
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
879
 
880
			Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet())
881
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
882
							Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
883
 
884
			Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(Collectors
885
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
886
 
887
			Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository
888
					.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream()
889
					.collect(Collectors.groupingBy(x -> x.getFofoId(),
890
							Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
891
 
892
			Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
893
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeMap.entrySet()) {
894
			}
895
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
896
				if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
897
					finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
898
				} else {
899
					finalUserSchemeAmountMap.put(schemeAmount.getKey(),
900
							finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
901
				}
902
			}
24590 amit.gupta 903
			Map<Integer, Integer> userWalletMap = userWalletRepository
904
					.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream()
905
					.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
906
 
24587 amit.gupta 907
			Map<Integer, Double> walletAmountMap = history.stream().collect(Collectors.groupingBy(
908
					UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
909
			for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
910
				double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
911
				if (diff > 5) {
912
					LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
913
				}
914
			}
24580 amit.gupta 915
		}
24587 amit.gupta 916
 
24580 amit.gupta 917
	}
24590 amit.gupta 918
 
24592 amit.gupta 919
	public void dryRunSchemeReco() throws Exception {
24635 amit.gupta 920
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
921
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
922
 
24592 amit.gupta 923
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
924
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24635 amit.gupta 925
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
926
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
927
		Set<String> serialNumbersConsidered = new HashSet<>();
928
 
929
		LocalDateTime startDate = LocalDate.of(2018, 9, 1).atStartOfDay();
930
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
931
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
932
 
24683 amit.gupta 933
		Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
24635 amit.gupta 934
		purchases.stream().forEach(purchase -> {
935
			float amountToRollback = 0;
936
			String description = "Adjustment of Duplicate Scheme for Purchase Invoice "
937
					+ purchase.getPurchaseReference();
938
			Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId())
939
					.stream().filter(ii -> ii.getSerialNumber() != null)
940
					.collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
941
			if (inventorySerialNumberMap.size() > 0) {
942
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
943
					String serialNumber = inventorySerialNumberEntry.getValue();
944
					int inventoryItemId = inventorySerialNumberEntry.getKey();
945
					if (serialNumbersConsidered.contains(serialNumber)) {
946
						// This will rollback scheme for differenct orders for same serial
947
						List<SchemeInOut> sios = schemeInOutRepository
948
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
949
								.filter(x -> x.getRolledBackTimestamp() == null
950
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
951
								.collect(Collectors.toList());
952
						Collections.reverse(sios);
953
						for (SchemeInOut sio : sios) {
954
							sio.setRolledBackTimestamp(LocalDateTime.now());
955
							amountToRollback += sio.getAmount();
956
							// sio.setSchemeType(SchemeType.OUT);
957
							sio.setSerialNumber(serialNumber);
958
							rolledbackSios.add(sio);
959
						}
960
						description = description.concat(" " + serialNumber + " ");
961
					} else {
962
						serialNumbersConsidered.add(serialNumber);
963
						List<Integer> schemesConsidered = new ArrayList<>();
964
						List<SchemeInOut> sios = schemeInOutRepository
965
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
966
								.filter(x -> x.getRolledBackTimestamp() == null
967
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
968
								.collect(Collectors.toList());
969
						Collections.reverse(sios);
970
						for (SchemeInOut sio : sios) {
971
							if (!schemesConsidered.contains(sio.getSchemeId())) {
972
								schemesConsidered.add(sio.getSchemeId());
973
								continue;
974
							}
975
							sio.setRolledBackTimestamp(LocalDateTime.now());
976
							amountToRollback += sio.getAmount();
977
							// sio.setSchemeType(SchemeType.OUT);
978
							sio.setSerialNumber(serialNumber);
24681 amit.gupta 979
							sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
980
							sio.setReference(purchase.getId());
24635 amit.gupta 981
							rolledbackSios.add(sio);
982
						}
983
					}
984
 
985
				}
986
			}
987
			if (amountToRollback > 0) {
24683 amit.gupta 988
				// Address address =
989
				// addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
24635 amit.gupta 990
				UserWalletHistory uwh = new UserWalletHistory();
991
				uwh.setAmount(Math.round(amountToRollback));
992
				uwh.setDescription(description);
993
				uwh.setTimestamp(LocalDateTime.now());
24681 amit.gupta 994
				uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
24635 amit.gupta 995
				uwh.setReference(purchase.getId());
996
				uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
997
				uwh.setFofoId(purchase.getFofoId());
24681 amit.gupta 998
				uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
24635 amit.gupta 999
				userWalletHistory.add(uwh);
1000
			}
1001
		});
1002
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1003
				Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
1004
						"Timestamp"),
1005
				userWalletHistory.stream()
1006
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1007
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
1008
						.collect(Collectors.toList()));
1009
 
1010
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
24683 amit.gupta 1011
				Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount",
1012
						"Created", "Rolledback"),
24635 amit.gupta 1013
				rolledbackSios.stream()
24681 amit.gupta 1014
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(),
24635 amit.gupta 1015
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1016
						.collect(Collectors.toList()));
1017
 
1018
		Utils.sendMailWithAttachments(googleMailSender,
1019
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24636 amit.gupta 1020
				"Partner Excess Amount Scheme In", "PFA",
24635 amit.gupta 1021
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
24636 amit.gupta 1022
						new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24635 amit.gupta 1023
 
1024
		throw new Exception();
1025
 
1026
	}
1027
 
1028
	public void dryRunOutSchemeReco() throws Exception {
1029
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1030
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24606 amit.gupta 1031
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1032
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24590 amit.gupta 1033
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1034
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
24631 amit.gupta 1035
		LocalDateTime startDate = LocalDate.of(2018, 9, 1).atStartOfDay();
24632 amit.gupta 1036
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
24631 amit.gupta 1037
		List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
1038
		// Collections.reverse(allOrders);
1039
		// List<FofoOrder> allOrders =
24653 govind 1040
		// List<FofoOrder> allOrders =
24631 amit.gupta 1041
		// Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
24625 amit.gupta 1042
		Set<String> serialNumbersConsidered = new HashSet<>();
24590 amit.gupta 1043
		allOrders.stream().forEach(fofoOrder -> {
24592 amit.gupta 1044
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
24598 amit.gupta 1045
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
24592 amit.gupta 1046
			float amountToRollback = 0;
24590 amit.gupta 1047
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1048
			orderItems.forEach(x -> {
24606 amit.gupta 1049
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
24598 amit.gupta 1050
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
24590 amit.gupta 1051
			});
24606 amit.gupta 1052
			if (inventorySerialNumberMap.size() > 0) {
24631 amit.gupta 1053
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1054
					String serialNumber = inventorySerialNumberEntry.getValue();
1055
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1056
					if (serialNumbersConsidered.contains(serialNumber)) {
1057
						// This will rollback scheme for differenct orders for same serial
1058
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1059
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1060
								.filter(x -> x.getRolledBackTimestamp() == null
1061
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1062
								.collect(Collectors.toList());
1063
						Collections.reverse(sios);
1064
						for (SchemeInOut sio : sios) {
1065
							sio.setRolledBackTimestamp(LocalDateTime.now());
1066
							amountToRollback += sio.getAmount();
1067
							// sio.setSchemeType(SchemeType.OUT);
1068
							sio.setSerialNumber(serialNumber);
1069
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
24681 amit.gupta 1070
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1071
							rolledbackSios.add(sio);
24623 amit.gupta 1072
						}
24635 amit.gupta 1073
						description = description.concat(" " + serialNumber + " ");
24631 amit.gupta 1074
					} else {
1075
						serialNumbersConsidered.add(serialNumber);
1076
						List<Integer> schemesConsidered = new ArrayList<>();
1077
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1078
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1079
								.filter(x -> x.getRolledBackTimestamp() == null
1080
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1081
								.collect(Collectors.toList());
1082
						Collections.reverse(sios);
1083
						for (SchemeInOut sio : sios) {
1084
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1085
								schemesConsidered.add(sio.getSchemeId());
1086
								continue;
1087
							}
1088
							sio.setRolledBackTimestamp(LocalDateTime.now());
1089
							amountToRollback += sio.getAmount();
1090
							// sio.setSchemeType(SchemeType.OUT);
24681 amit.gupta 1091
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1092
							sio.setSerialNumber(serialNumber);
1093
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1094
							rolledbackSios.add(sio);
1095
						}
24615 amit.gupta 1096
					}
24631 amit.gupta 1097
 
24604 amit.gupta 1098
				}
24590 amit.gupta 1099
			}
24631 amit.gupta 1100
			if (amountToRollback > 0) {
1101
				UserWalletHistory uwh = new UserWalletHistory();
1102
				uwh.setAmount(Math.round(amountToRollback));
1103
				uwh.setDescription(description);
1104
				uwh.setTimestamp(LocalDateTime.now());
1105
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1106
				uwh.setReference(fofoOrder.getId());
1107
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1108
				uwh.setFofoId(fofoOrder.getFofoId());
1109
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1110
				userWalletHistory.add(uwh);
1111
			}
24590 amit.gupta 1112
		});
24598 amit.gupta 1113
 
24592 amit.gupta 1114
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
24681 amit.gupta 1115
				Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
24615 amit.gupta 1116
						"Timestamp"),
1117
				userWalletHistory.stream()
1118
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1119
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24592 amit.gupta 1120
						.collect(Collectors.toList()));
1121
 
1122
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1123
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1124
						"Rolledback"),
1125
				rolledbackSios.stream()
1126
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1127
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1128
						.collect(Collectors.toList()));
1129
 
24623 amit.gupta 1130
		Utils.sendMailWithAttachments(googleMailSender,
1131
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24681 amit.gupta 1132
				"Partner Excess Amount Scheme Out", "PFA",
24598 amit.gupta 1133
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1134
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1135
 
24628 amit.gupta 1136
		throw new Exception();
24590 amit.gupta 1137
	}
24615 amit.gupta 1138
 
24611 amit.gupta 1139
	public void dryRunSchemeOutReco1() throws Exception {
24615 amit.gupta 1140
		List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
24611 amit.gupta 1141
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1142
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
1143
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1144
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1145
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1146
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1147
		references.stream().forEach(reference -> {
1148
			FofoOrder fofoOrder = null;
1149
			try {
1150
				fofoOrder = fofoOrderRepository.selectByOrderId(reference);
24615 amit.gupta 1151
			} catch (Exception e) {
1152
 
24611 amit.gupta 1153
			}
1154
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
1155
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
1156
			float amountToRollback = 0;
1157
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1158
			orderItems.forEach(x -> {
1159
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
1160
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
1161
			});
1162
			if (inventorySerialNumberMap.size() > 0) {
24615 amit.gupta 1163
				List<SchemeInOut> sios = schemeInOutRepository
1164
						.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream()
1165
						.filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24611 amit.gupta 1166
						.collect(Collectors.toList());
1167
				LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
1168
				UserWalletHistory uwh = new UserWalletHistory();
24615 amit.gupta 1169
				Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream()
1170
						.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
24611 amit.gupta 1171
				for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
1172
					List<SchemeInOut> outList = inventorySioEntry.getValue();
24615 amit.gupta 1173
					if (outList.size() > 1) {
1174
 
24611 amit.gupta 1175
					}
1176
				}
1177
				uwh.setAmount(Math.round(amountToRollback));
1178
				uwh.setDescription(description);
1179
				uwh.setTimestamp(LocalDateTime.now());
1180
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1181
				uwh.setReference(fofoOrder.getId());
1182
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1183
				uwh.setFofoId(fofoOrder.getFofoId());
1184
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1185
				userWalletHistory.add(uwh);
1186
			}
1187
		});
24615 amit.gupta 1188
 
24611 amit.gupta 1189
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1190
				Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"),
1191
				userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(),
1192
						x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24615 amit.gupta 1193
						.collect(Collectors.toList()));
1194
 
24611 amit.gupta 1195
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1196
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1197
						"Rolledback"),
1198
				rolledbackSios.stream()
24615 amit.gupta 1199
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1200
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1201
						.collect(Collectors.toList()));
1202
 
24623 amit.gupta 1203
		Utils.sendMailWithAttachments(googleMailSender,
1204
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24611 amit.gupta 1205
				"Partner Excess Amount", "PFA",
1206
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1207
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1208
 
24628 amit.gupta 1209
		throw new Exception();
24615 amit.gupta 1210
 
24611 amit.gupta 1211
	}
24615 amit.gupta 1212
 
24653 govind 1213
	public void alertforTicket() throws Exception {
1214
		List<Ticket> tickets = ticketRepository.selectAllNotClosedTickets();
1215
		Map<Integer, List<Ticket>> l1AuthUserAndTicketMap = new HashMap<>();
1216
		Map<Integer, List<Ticket>> l2AuthUserAndTicketMap = new HashMap<>();
1217
		Set<Integer> l1AuthUsers = tickets.stream().map(x -> x.getL1AuthUser()).collect(Collectors.toSet());
1218
		Set<Integer> l2AuthUsers = tickets.stream()
24665 govind 1219
				.filter(x -> x.getL2EscalationTimestamp().isBefore(LocalDateTime.now())).map(x -> x.getL2AuthUser())
24653 govind 1220
				.collect(Collectors.toSet());
1221
		for (Integer l1AuthUser : l1AuthUsers) {
1222
			List<Ticket> ticketsForl1AuthUser = tickets.stream().filter(ticket -> l1AuthUser == ticket.getL1AuthUser())
1223
					.collect(Collectors.toList());
1224
			l1AuthUserAndTicketMap.put(l1AuthUser, ticketsForl1AuthUser);
1225
		}
1226
		for (Integer l2AuthUser : l2AuthUsers) {
1227
			List<Ticket> ticketsForl2AuthUser = tickets.stream().filter(ticket -> l2AuthUser == ticket.getL2AuthUser())
1228
					.collect(Collectors.toList());
1229
			l2AuthUserAndTicketMap.put(l2AuthUser, ticketsForl2AuthUser);
1230
		}
1231
		for (Entry<Integer, List<Ticket>> entry : l1AuthUserAndTicketMap.entrySet()) {
1232
			List<Ticket> ticketsForAuthUser = entry.getValue();
1233
			AuthUser authUser = authRepository.selectById(entry.getKey());
1234
			String message = this.getMessageForAlertTicket(ticketsForAuthUser, EscalationType.L1);
1235
			this.sendMailOfHtmlFomat(authUser.getEmailId(), message, null, "Daily Pending Ticket");
1236
		}
1237
		for (Entry<Integer, List<Ticket>> entry : l2AuthUserAndTicketMap.entrySet()) {
1238
			List<Ticket> ticketsForAuthUser = entry.getValue();
1239
			AuthUser authUser = authRepository.selectById(entry.getKey());
1240
			String message = this.getMessageForAlertTicket(ticketsForAuthUser, EscalationType.L2);
1241
			this.sendMailOfHtmlFomat(authUser.getEmailId(), message, null, "Daily Pending Ticket");
1242
		}
1243
	}
1244
 
1245
	public String getMessageForAlertTicket(List<Ticket> tickets, EscalationType escalationType)
1246
			throws ProfitMandiBusinessException {
1247
		StringBuilder sb = new StringBuilder();
1248
		sb.append("<html><body><p>Your Pending Tickets</p><br/><table style='border:1px solid black ;padding: 5px';>");
1249
		sb.append("<tbody>\n" + "	    				<tr>\n"
1250
				+ "	    					<th style='border:1px solid black;padding: 5px'>Ticket Id</th>\n"
1251
				+ "	    					<th style='border:1px solid black;padding: 5px'>Partner</th>\n"
1252
				+ "	    					<th style='border:1px solid black;padding: 5px'>SubCategory</th>\n"
1253
				+ "	    					<th style='border:1px solid black;padding: 5px'>Remaining Time To Escalate</th>\n"
1254
				+ "	    					<th style='border:1px solid black;padding: 5px'>Escalated</th>\n"
1255
				+ "	    				</tr>");
1256
		for (Ticket ticket : tickets) {
1257
			sb.append("<tr>");
1258
			sb.append("<td style='border:1px solid black;padding: 5px'>" + ticket.getId() + "</td>");
1259
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1260
					+ retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName() + "</td>");
1261
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1262
					+ ticketSubCategoryRepository.selectById(ticket.getSubCategoryId()).getDescription() + "</td>");
1263
			if (escalationType == EscalationType.L1) {
1264
				if (ticket.getL2EscalationTimestamp().isBefore(LocalDateTime.now())) {
1265
					sb.append("<td style='border:1px solid black;padding: 5px'>" + 0 + "</td>");
1266
					sb.append("<td style='border:1px solid black;padding: 5px'>YES</td>");
1267
				} else {
1268
					Duration duration = Duration.between(LocalDateTime.now(), ticket.getL2EscalationTimestamp());
1269
					sb.append("<td style='border:1px solid black;padding: 5px'>" + duration.toHours() + "hrs</td>");
1270
					sb.append("<td style='border:1px solid black;padding: 5px'>NO</td>");
1271
				}
1272
			} else if (escalationType == EscalationType.L2) {
1273
				if (ticket.getL3EscalationTimestamp().isBefore(LocalDateTime.now())) {
1274
					Duration duration = Duration.between(ticket.getL3EscalationTimestamp(), LocalDateTime.now());
1275
					sb.append("<td style='border:1px solid black;padding: 5px'>" + duration.toHours() + " hrs</td>");
1276
					sb.append("<td style='border:1px solid black;padding: 5px'>YES</td>");
1277
				} else {
1278
					sb.append("<td style='border:1px solid black;padding: 5px'>NO</td>");
1279
				}
1280
			}
1281
			sb.append("</tr>");
1282
		}
1283
		sb.append("</tbody></table></body></html>");
1284
		return sb.toString();
1285
	}
1286
 
1287
	private void sendMailOfHtmlFomat(String email, String body, String cc[], String subject)
1288
			throws MessagingException, ProfitMandiBusinessException, IOException {
1289
		MimeMessage message = mailSender.createMimeMessage();
1290
		MimeMessageHelper helper = new MimeMessageHelper(message);
1291
		helper.setSubject(subject);
1292
		helper.setText(body, true);
1293
		helper.setTo(email);
24683 amit.gupta 1294
		if (cc != null) {
1295
			helper.setCc(cc);
24664 govind 1296
		}
24653 govind 1297
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
1298
		helper.setFrom(senderAddress);
1299
		mailSender.send(message);
1300
	}
1301
 
1302
	public void sendDailySalesReportNotificationToPartner()
1303
			throws ProfitMandiBusinessException, MessagingException, IOException {
1304
		LocalDateTime now = LocalDateTime.now();
1305
		LocalDateTime from = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 00, 00);
1306
		Map<Integer, Double> salesByFofoIdMap = new HashMap<>();
1307
		List<Integer> fofoIds = targetService.getfofoIdsFromfofoStore();
1308
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
1309
				.selectAllGeEqAndLeEqStartDateAndEndDate(now);
24683 amit.gupta 1310
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h a");
1311
 
1312
		Map<Integer, Float> dailyTarget = new HashMap<>();
24653 govind 1313
		for (Integer fofoId : fofoIds) {
24683 amit.gupta 1314
			Map<Integer, Float> dailyAverageSale = null;
24653 govind 1315
			double sale = fofoOrderRepository.selectTotalSaleSumByFofoIdBrtweenDate(fofoId, from, now);
1316
			for (PartnerTargetDetails partnerTargetDetail : partnerTargetDetails) {
1317
				Map<Integer, Float> targetValues = targetService.getTargetValueByFofoIdAndTargetId(fofoId,
1318
						partnerTargetDetail.getId());
1319
				if (targetValues.size() == 0) {
1320
					continue;
1321
				} else {
1322
					List<Integer> partnerIds = new ArrayList<>();
1323
					partnerIds.add(fofoId);
1324
					dailyAverageSale = targetService.getDailyAverageSaleForCurrentForSingleFofoIdAndBrand(partnerIds,
1325
							targetValues, partnerTargetDetail.getStartDate(), partnerTargetDetail.getEndDate(),
1326
							partnerTargetDetail.getBrandName());
1327
					dailyTarget.put(fofoId, dailyAverageSale.get(fofoId));
1328
					break;
1329
				}
1330
			}
1331
			NotificationCampaigns notification = new NotificationCampaigns();
1332
			notification.setName("Today's Sale");
24683 amit.gupta 1333
			if (dailyAverageSale != null && dailyAverageSale.get(fofoId) != null) {
1334
				LOGGER.info("Your today sale till" + " " + now.format(timeFormatter) + " " + "is" + " " + sale + " "
1335
						+ "vs" + " " + "daily target=" + dailyAverageSale.get(fofoId));
1336
				notification.setTitle("Your today sale till" + " " + now.format(timeFormatter) + " " + "is" + " " + sale
1337
						+ " " + "vs" + " " + "daily target=" + dailyAverageSale.get(fofoId));
1338
			} else {
1339
				notification.setTitle("Your today sale till" + " " + now.format(timeFormatter) + " " + "is" + " " + sale
1340
						+ " " + "vs" + " " + "daily target = 0.0");
1341
				LOGGER.info("Your today sale till" + " " + now.format(timeFormatter) + " " + "is" + " " + sale + " "
1342
						+ "vs" + " " + "daily target = 0.0");
24653 govind 1343
			}
24683 amit.gupta 1344
			// notification.setMessage("Your sale is "+salesbyfofoId.get(fofoId));
24653 govind 1345
			notification.setType("Url");
1346
			notification.setUrl("http://app.profitmandi.com/pages/home/dashboard");
24683 amit.gupta 1347
			LOGGER.info("UserID" + userAccountRepository.selectUserIdByRetailerId(fofoId));
1348
			notification.setSql("SELECT distinct d1.user_id from devices d1 left join devices d2 on"
1349
					+ "(d1.imeinumber = d2.imeinumber and d1.created < d2.created) "
1350
					+ " where d2.id is null and d1.user_id = "
1351
					+ userAccountRepository.selectUserIdByRetailerId(fofoId));
24676 govind 1352
			LOGGER.info("SELECT distinct d1.user_id from devices d1 left join devices d2 on"
24683 amit.gupta 1353
					+ "(d1.imeinumber = d2.imeinumber and d1.created < d2.created) "
1354
					+ " where d2.id is null and d1.user_id = "
1355
					+ userAccountRepository.selectUserIdByRetailerId(fofoId));
24667 govind 1356
			notification.setExpiresat(LocalDateTime.now().plusDays(1).toEpochSecond(ZoneOffset.UTC) * 1000);
24653 govind 1357
			notification.setStatus("active");
1358
			notification.setSmsprocessed(0);
1359
			notification.setNotification_processed(0);
1360
			notification.setNotification_type("GENERAL_NOTIFICATION");
24657 govind 1361
			mongoClient.persistNotificationCmpInfo(notification);
24653 govind 1362
			salesByFofoIdMap.put(fofoId, sale);
1363
			LOGGER.info(sale);
1364
		}
24683 amit.gupta 1365
		String saleReport = this.getDailySalesReportByPartnerId(salesByFofoIdMap, dailyTarget);
24653 govind 1366
		LOGGER.info(saleReport);
1367
		String cc[] = { "Tarun.verma@smartdukaan.com", "Kamini.sharma@smartdukaan.com",
24697 amit.gupta 1368
				"chaitnaya.vats@smartdukaan.com", "adeel.yazdani@smartdukaan.com", "mohinder.mutreja@smartdukaan.com" };
24653 govind 1369
		String subject = "sale report till" + " " + now.format(timeFormatter);
24677 govind 1370
		this.sendMailOfHtmlFomat("amod.sen@smartdukaan.com", saleReport, cc, subject);
24653 govind 1371
	}
1372
 
24683 amit.gupta 1373
	public String getDailySalesReportByPartnerId(Map<Integer, Double> salesByFofoIdMap, Map<Integer, Float> dailyTarget)
24653 govind 1374
			throws ProfitMandiBusinessException {
1375
		StringBuilder sb = new StringBuilder();
1376
		sb.append("<html><body><p>Sale Report:</p><br/><table style='border:1px solid black ;padding: 5px';>");
1377
		sb.append("<tbody>\n" + "	    				<tr>\n"
1378
				+ "	    					<th style='border:1px solid black;padding: 5px'>Partner</th>\n"
1379
				+ "	    					<th style='border:1px solid black;padding: 5px'>Daily Target</th>\n"
1380
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>\n"
1381
				+ "	    				</tr>");
1382
		for (Integer fofoId : salesByFofoIdMap.keySet()) {
1383
			sb.append("<tr>");
1384
			sb.append("<td style='border:1px solid black;padding: 5px'>"
1385
					+ retailerService.getFofoRetailer(fofoId).getBusinessName() + "</td>");
24683 amit.gupta 1386
			if (dailyTarget != null && dailyTarget.get(fofoId) != null) {
1387
				sb.append("<td style='border:1px solid black;padding: 5px'>" + dailyTarget.get(fofoId) + "</td>");
1388
			} else {
1389
				sb.append("<td style='border:1px solid black;padding: 5px'>" + 0.0 + "</td>");
24653 govind 1390
			}
1391
			sb.append("<td style='border:1px solid black;padding: 5px'>" + salesByFofoIdMap.get(fofoId) + "</td>");
1392
 
1393
			sb.append("</tr>");
1394
		}
24683 amit.gupta 1395
 
24653 govind 1396
		sb.append("</tbody></table></body></html>");
1397
		return sb.toString();
1398
	}
24587 amit.gupta 1399
}
24580 amit.gupta 1400
 
24587 amit.gupta 1401
/*
1402
 * public void processSchemeForModel(String string) { pricingService
1403
 * 
1404
 * }
1405
 */