Subversion Repositories SmartDukaan

Rev

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