Subversion Repositories SmartDukaan

Rev

Rev 24691 | Rev 24697 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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