Subversion Repositories SmartDukaan

Rev

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