Subversion Repositories SmartDukaan

Rev

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