Subversion Repositories SmartDukaan

Rev

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