Subversion Repositories SmartDukaan

Rev

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