Subversion Repositories SmartDukaan

Rev

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