Subversion Repositories SmartDukaan

Rev

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

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