Subversion Repositories SmartDukaan

Rev

Rev 25602 | Rev 25604 | 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()) {
25603 amit.gupta 676
			/*
677
			 * List<List<? extends Serializable>> filteredRows =
678
			 * storeGuyEntry.getValue().stream() .map(x -> partnerRow.get(x)).filter(x -> x
679
			 * != null).collect(Collectors.toList());
680
			 */
25602 amit.gupta 681
			List<List<? extends Serializable>> filteredRows = new ArrayList<>();
25312 amit.gupta 682
			ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, filteredRows);
25603 amit.gupta 683
			// String[] sendToArray = new String[] {storeGuyEntry.getKey()};
684
			for (String storeGuyString : storeGuyEntry.getValue()) {
685
				String[] sendToArray = new String[] {storeGuyString};
686
				Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Partner Investment Summary", "PFA",
687
						fileName, new ByteArrayResource(baos.toByteArray()));
688
			}
25341 amit.gupta 689
		}
25312 amit.gupta 690
 
25603 amit.gupta 691
		/*
692
		 * ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
693
		 * String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
694
		 * Utils.sendMailWithAttachment(googleMailSender, sendToArray, null,
695
		 * "Partner Investment Summary", "PFA", fileName, new
696
		 * ByteArrayResource(baos.toByteArray()));
697
		 */
24271 amit.gupta 698
 
23929 amit.gupta 699
	}
24177 govind 700
 
25598 amit.gupta 701
	private Map<String, SaleRoles> getPartnerEmailSalesMap() {
702
		Map<String, SaleRoles> partnerEmailSalesMap = new HashMap<>();
703
 
704
		List<Position> positions = positionRepository
705
				.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
706
		Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream()
707
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
708
		Map<Integer, List<CustomRetailer>> positionIdRetailerMap = csService.getPositionCustomRetailerMap(positions);
709
		for (Position position : positions) {
710
			List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
25603 amit.gupta 711
			if (crList == null)
712
				continue;
25598 amit.gupta 713
			for (CustomRetailer cr : crList) {
714
				if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
715
					partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles());
716
				}
717
				SaleRoles saleRoles = partnerEmailSalesMap.get(cr.getEmail());
718
				AuthUser authUser = authUsersMap.get(position.getAuthUserId());
719
				String name = authUser.getFirstName() + " " + authUser.getLastName();
720
				if (position.getEscalationType().equals(EscalationType.L1)) {
721
					saleRoles.getL1().add(name);
722
				} else if (position.getEscalationType().equals(EscalationType.L2)) {
723
					saleRoles.getL2().add(name);
724
				}
725
			}
726
		}
727
		return partnerEmailSalesMap;
728
	}
729
 
24271 amit.gupta 730
	public void sendPartnerInvestmentDetails() throws Exception {
25565 amit.gupta 731
		this.sendPartnerInvestmentDetails(null);
24271 amit.gupta 732
 
733
	}
734
 
25312 amit.gupta 735
	public void sendTargetVsSalesReport(List<String> sendTo) throws Exception {
24177 govind 736
 
25312 amit.gupta 737
		if (sendTo == null) {
25341 amit.gupta 738
			sendTo = Arrays.asList("tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com",
25509 tejbeer 739
					"amit.gupta@shop2020.in", "amod.sen@smartdukaan.com");
25312 amit.gupta 740
		}
24177 govind 741
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
25373 amit.gupta 742
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now().minusDays(1));
25312 amit.gupta 743
		Map<String, List<? extends Serializable>> partnerSalesTargetRowsMap = new HashMap<>();
24177 govind 744
		for (PartnerTargetDetails partnerTargetDetail : partnerTargetDetails) {
25312 amit.gupta 745
			partnerSalesTargetRowsMap.putAll(targetService.getDailySaleReportVsTarget(partnerTargetDetail));
24174 govind 746
		}
25315 amit.gupta 747
		Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream()
748
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
749
 
25312 amit.gupta 750
		Map<Integer, CustomRetailer> customRetailerMap = retailerService
25315 amit.gupta 751
				.getFofoRetailers(new ArrayList<>(fofoStoresMap.keySet()));
24177 govind 752
 
25315 amit.gupta 753
		Map<String, CustomRetailer> customRetailerEmailMap = customRetailerMap.values().stream()
754
				.collect(Collectors.toMap(x -> x.getEmail(), x -> x));
25603 amit.gupta 755
 
25598 amit.gupta 756
		Map<String, SaleRoles> partnerEmailSalesMap = this.getPartnerEmailSalesMap();
25315 amit.gupta 757
 
25598 amit.gupta 758
		List<String> headers = Arrays.asList("Code", "Firm Name", "Store Name", "Current Category", "State Manager",
759
				"Teritory Manager", "Team Leader", "Targeted Category", "Targeted Value", "Target Achieved",
760
				"Achived Percentage", "Remaining Target", "Today's Target", "Today's achievement");
24177 govind 761
 
25312 amit.gupta 762
		List<List<? extends Serializable>> rows = new ArrayList<>();
763
		Map<String, List<Serializable>> partnerRowMap = new HashMap<>();
25315 amit.gupta 764
		for (Map.Entry<String, List<? extends Serializable>> partnerSalesTargetRowEntry : partnerSalesTargetRowsMap
765
				.entrySet()) {
766
			CustomRetailer retailer = customRetailerEmailMap.get(partnerSalesTargetRowEntry.getKey());
767
			FofoStore fofoStore = fofoStoresMap.get(retailer.getPartnerId());
25312 amit.gupta 768
			Serializable code = fofoStore.getCode();
25345 amit.gupta 769
			Serializable storeName = "SmartDukaan-" + fofoStore.getCode().replaceAll("[a-zA-Z]", "");
25314 amit.gupta 770
			Serializable businessName = retailer.getBusinessName();
25317 amit.gupta 771
			try {
25603 amit.gupta 772
				Serializable stateManager = StringUtils.join(partnerEmailSalesMap.get(retailer.getEmail()).getL2(),
773
						", ");
774
				Serializable territoryManager = StringUtils.join(partnerEmailSalesMap.get(retailer.getEmail()).getL1(),
775
						", ");
25317 amit.gupta 776
				List<Serializable> row = new ArrayList<>(
25598 amit.gupta 777
						Arrays.asList(code, businessName, storeName, stateManager, territoryManager));
25317 amit.gupta 778
				if (partnerSalesTargetRowsMap.get(retailer.getEmail()) != null) {
25323 amit.gupta 779
					row.addAll(partnerSalesTargetRowsMap.get(retailer.getEmail()));
25317 amit.gupta 780
					partnerRowMap.put(retailer.getEmail(), row);
781
					rows.add(row);
782
				}
25351 tejbeer 783
			} catch (Exception e) {
25317 amit.gupta 784
				LOGGER.warn("Could not find partner with email - {}", retailer.getEmail());
25315 amit.gupta 785
			}
25312 amit.gupta 786
 
24177 govind 787
		}
25503 amit.gupta 788
 
25318 amit.gupta 789
		String fileName = "TargetVsSales-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
25597 amit.gupta 790
		for (Map.Entry<String, Set<String>> storeGuyEntry : csService.getAuthUserPartnerEmailMapping().entrySet()) {
25312 amit.gupta 791
			List<List<? extends Serializable>> filteredRows = storeGuyEntry.getValue().stream()
25351 tejbeer 792
					.map(x -> partnerRowMap.get(x)).filter(x -> x != null).collect(Collectors.toList());
25312 amit.gupta 793
			ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, filteredRows);
25595 amit.gupta 794
			String[] sendToArray = new String[] { storeGuyEntry.getKey() };
25312 amit.gupta 795
			Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Target vs Sales Summary", "PFA",
796
					fileName, new ByteArrayResource(baos.toByteArray()));
25341 amit.gupta 797
		}
24240 amit.gupta 798
 
25312 amit.gupta 799
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
800
		String[] sendToArray = sendTo.toArray(new String[sendTo.size()]);
801
		Utils.sendMailWithAttachment(googleMailSender, sendToArray, null, "Target vs Sales Summary", "PFA", fileName,
802
				new ByteArrayResource(baos.toByteArray()));
24174 govind 803
	}
24683 amit.gupta 804
 
24697 amit.gupta 805
	public void sendAgeingReport(String... sendTo) throws Exception {
24692 amit.gupta 806
 
807
		InputStreamSource isr = reporticoService.getReportInputStreamSource(ReporticoProject.WAREHOUSENEW,
808
				"itemstockageing.xml");
24708 amit.gupta 809
		InputStreamSource isr1 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
24754 amit.gupta 810
				"ItemwiseOverallPendingIndent.xml");
24683 amit.gupta 811
		Attachment attachment = new Attachment(
25445 amit.gupta 812
				"ageing-report-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr);
24707 amit.gupta 813
		Attachment attachment1 = new Attachment(
25445 amit.gupta 814
				"pending-indent-" + FormattingUtils.formatDate(LocalDateTime.now().minusDays(1)) + ".csv", isr1);
24841 govind 815
		Utils.sendMailWithAttachments(googleMailSender, sendTo, null, "Stock Aeging Report", "PFA", attachment,
816
				attachment1);
25418 amit.gupta 817
 
25598 amit.gupta 818
		// Reports to be sent to mapped partners
25597 amit.gupta 819
		Map<String, Set<String>> storeGuysMap = csService.getAuthUserPartnerEmailMapping();
25503 amit.gupta 820
 
25603 amit.gupta 821
		Utils.sendMailWithAttachments(googleMailSender, storeGuysMap.keySet().toArray(new String[0]), null,
822
				"Stock Aeging Report", "PFA", attachment);
25503 amit.gupta 823
 
824
		for (Map.Entry<String, Set<String>> storeGuyEntry : storeGuysMap.entrySet()) {
25418 amit.gupta 825
			Map<String, String> params = new HashMap<>();
25503 amit.gupta 826
			if (storeGuyEntry.getValue().size() == 0)
827
				continue;
25418 amit.gupta 828
			params.put("MANUAL_email", String.join(",", storeGuyEntry.getValue()));
829
			InputStreamSource isr3 = reporticoService.getReportInputStreamSource(ReporticoProject.FOCO,
830
					"focostockreport.xml", params);
831
			Attachment attache = new Attachment(
25445 amit.gupta 832
					"partner-stock-report" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv", isr3);
25584 amit.gupta 833
			System.out.println(storeGuyEntry.getValue());
25600 amit.gupta 834
			Utils.sendMailWithAttachments(googleMailSender, storeGuyEntry.getValue().toArray(new String[0]), null,
25503 amit.gupta 835
					"Partner Stock Report", "PFA", attache);
25418 amit.gupta 836
		}
25503 amit.gupta 837
 
24681 amit.gupta 838
	}
24533 govind 839
 
24697 amit.gupta 840
	public void sendAgeingReport() throws Exception {
25503 amit.gupta 841
		sendAgeingReport("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com",
25583 amit.gupta 842
				"chaitnaya.vats@smartdukaan.com", "amod.sen@smartdukaan.com");
24697 amit.gupta 843
	}
844
 
24533 govind 845
	public void moveImeisToPriceDropImeis() throws Exception {
24431 amit.gupta 846
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24533 govind 847
		for (PriceDrop priceDrop : priceDrops) {
24431 amit.gupta 848
			priceDropService.priceDropStatus(priceDrop.getId());
849
		}
850
	}
23929 amit.gupta 851
 
24542 amit.gupta 852
	public void walletmismatch() throws Exception {
853
		LocalDate curDate = LocalDate.now();
24553 amit.gupta 854
		List<PartnerDailyInvestment> pdis = partnerDailyInvestmentRepository.selectAll(curDate.minusDays(2));
24552 amit.gupta 855
		System.out.println(pdis.size());
24542 amit.gupta 856
		for (PartnerDailyInvestment pdi : pdis) {
24549 amit.gupta 857
			int fofoId = pdi.getFofoId();
24542 amit.gupta 858
			for (PartnerDailyInvestment investment : Lists
859
					.reverse(partnerDailyInvestmentRepository.selectAll(fofoId, null, null))) {
24552 amit.gupta 860
				float statementAmount = walletService.getOpeningTill(fofoId,
24555 amit.gupta 861
						investment.getDate().plusDays(1).atTime(LocalTime.of(4, 0)));
24552 amit.gupta 862
				CustomRetailer retailer = retailerService.getFofoRetailer(fofoId);
24841 govind 863
				LOGGER.info("{}\t{}\t{}\t{}\t{}", fofoId, retailer.getBusinessName(), retailer.getMobileNumber(),
864
						investment.getDate().toString(), investment.getWalletAmount(), statementAmount);
24551 amit.gupta 865
 
24542 amit.gupta 866
			}
24549 amit.gupta 867
		}
24542 amit.gupta 868
 
869
	}
870
 
871
	public void gst() throws Exception {
24548 amit.gupta 872
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectBetweenSaleDate(LocalDate.of(2019, 1, 26).atStartOfDay(),
873
				LocalDate.of(2019, 1, 27).atTime(LocalTime.MAX));
874
		for (FofoOrder fofoOrder : fofoOrders) {
875
			int retailerAddressId = retailerRegisteredAddressRepository
876
					.selectAddressIdByRetailerId(fofoOrder.getFofoId());
24542 amit.gupta 877
 
878
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
879
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
880
			Integer stateId = null;
881
			if (customerAddress.getState().equals(retailerAddress.getState())) {
882
				try {
883
					stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
884
				} catch (Exception e) {
885
					LOGGER.error("Unable to get state rates");
886
				}
887
			}
888
			Map<Integer, GstRate> itemIdStateTaxRateMap = null;
889
			Map<Integer, Float> itemIdIgstTaxRateMap = null;
24548 amit.gupta 890
 
891
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
892
			Set<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
24542 amit.gupta 893
			if (stateId != null) {
894
				itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemIds), stateId);
895
			} else {
896
				itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemIds));
897
			}
898
 
24548 amit.gupta 899
			for (FofoOrderItem foi : fofoOrderItems) {
24542 amit.gupta 900
				if (stateId == null) {
901
					foi.setIgstRate(itemIdIgstTaxRateMap.get(foi.getItemId()));
902
				} else {
903
					foi.setCgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getCgstRate());
904
					foi.setSgstRate(itemIdStateTaxRateMap.get(foi.getItemId()).getSgstRate());
905
				}
906
				fofoOrderItemRepository.persist(foi);
907
			}
908
		}
24548 amit.gupta 909
 
24542 amit.gupta 910
	}
911
 
24580 amit.gupta 912
	public void schemewalletmismatch() {
913
		LocalDate dateToReconcile = LocalDate.of(2018, 4, 1);
24587 amit.gupta 914
		while (dateToReconcile.isBefore(LocalDate.now())) {
24580 amit.gupta 915
			reconcileSchemes(dateToReconcile);
24587 amit.gupta 916
			// reconcileOrders(dateTime);
917
			// reconcileRecharges(dateTime);
24580 amit.gupta 918
			dateToReconcile = dateToReconcile.plusDays(1);
919
		}
920
	}
921
 
922
	private void reconcileSchemes(LocalDate date) {
923
		LocalDateTime startDate = date.atStartOfDay();
924
		LocalDateTime endDate = startDate.plusDays(1);
925
		List<SchemeInOut> siosCreated = schemeInOutRepository.selectAllByCreateDate(startDate, endDate);
926
		List<SchemeInOut> siosRefunded = schemeInOutRepository.selectAllByRefundDate(startDate, endDate);
24587 amit.gupta 927
		double totalSchemeDisbursed = siosCreated.stream().mapToDouble(x -> x.getAmount()).sum();
928
		double totalSchemeRolledback = siosRefunded.stream().mapToDouble(x -> x.getAmount()).sum();
24580 amit.gupta 929
		double netSchemeDisbursed = totalSchemeDisbursed - totalSchemeRolledback;
24587 amit.gupta 930
		List<WalletReferenceType> walletReferenceTypes = Arrays.asList(WalletReferenceType.SCHEME_IN,
931
				WalletReferenceType.SCHEME_OUT);
932
		List<UserWalletHistory> history = userWalletHistoryRepository.selectAllByDateType(startDate, endDate,
933
				walletReferenceTypes);
934
		double schemeAmountWalletTotal = history.stream().mapToDouble(x -> x.getAmount()).sum();
935
		if (Math.abs(netSchemeDisbursed - schemeAmountWalletTotal) > 10d) {
24580 amit.gupta 936
			LOGGER.info("Scheme Amount mismatched for Date {}", date);
24587 amit.gupta 937
 
938
			Map<Integer, Double> inventoryItemSchemeIO = siosCreated.stream().collect(Collectors
939
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
940
 
941
			Map<Integer, Double> userSchemeMap = inventoryItemRepository.selectByIds(inventoryItemSchemeIO.keySet())
942
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
943
							Collectors.summingDouble(x -> inventoryItemSchemeIO.get(x.getId()))));
944
 
945
			Map<Integer, Double> inventoryItemSchemeIORefunded = siosRefunded.stream().collect(Collectors
946
					.groupingBy(x -> x.getInventoryItemId(), Collectors.summingDouble(SchemeInOut::getAmount)));
947
 
948
			Map<Integer, Double> userSchemeRefundedMap = inventoryItemRepository
949
					.selectByIds(inventoryItemSchemeIORefunded.keySet()).stream()
950
					.collect(Collectors.groupingBy(x -> x.getFofoId(),
951
							Collectors.summingDouble(x -> inventoryItemSchemeIORefunded.get(x.getId()))));
952
 
953
			Map<Integer, Double> finalUserSchemeAmountMap = new HashMap<>();
954
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeMap.entrySet()) {
955
			}
956
			for (Map.Entry<Integer, Double> schemeAmount : userSchemeRefundedMap.entrySet()) {
957
				if (!finalUserSchemeAmountMap.containsKey(schemeAmount.getKey())) {
958
					finalUserSchemeAmountMap.put(schemeAmount.getKey(), schemeAmount.getValue());
959
				} else {
960
					finalUserSchemeAmountMap.put(schemeAmount.getKey(),
961
							finalUserSchemeAmountMap.get(schemeAmount.getKey()) + schemeAmount.getValue());
962
				}
963
			}
24590 amit.gupta 964
			Map<Integer, Integer> userWalletMap = userWalletRepository
965
					.selectByRetailerIds(finalUserSchemeAmountMap.keySet()).stream()
966
					.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
967
 
24587 amit.gupta 968
			Map<Integer, Double> walletAmountMap = history.stream().collect(Collectors.groupingBy(
969
					UserWalletHistory::getWalletId, Collectors.summingDouble((UserWalletHistory::getAmount))));
970
			for (Map.Entry<Integer, Double> userAmount : walletAmountMap.entrySet()) {
971
				double diff = Math.abs(finalUserSchemeAmountMap.get(userAmount.getKey()) - userAmount.getValue());
972
				if (diff > 5) {
973
					LOGGER.info("Partner scheme mismatched for Userid {}", userWalletMap.get(userAmount.getKey()));
974
				}
975
			}
24580 amit.gupta 976
		}
24587 amit.gupta 977
 
24580 amit.gupta 978
	}
24590 amit.gupta 979
 
24592 amit.gupta 980
	public void dryRunSchemeReco() throws Exception {
24635 amit.gupta 981
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
982
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
983
 
24592 amit.gupta 984
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
985
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24635 amit.gupta 986
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
987
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
988
		Set<String> serialNumbersConsidered = new HashSet<>();
989
 
25096 amit.gupta 990
		LocalDateTime startDate = LocalDate.of(2018, 3, 1).atStartOfDay();
24635 amit.gupta 991
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
992
		List<Purchase> purchases = purchaseRepository.selectAllBetweenPurchaseDate(startDate, endDate);
993
 
24683 amit.gupta 994
		Map<Integer, String> storeNameMap = fofoStoreRepository.getStoresMap();
24635 amit.gupta 995
		purchases.stream().forEach(purchase -> {
996
			float amountToRollback = 0;
997
			String description = "Adjustment of Duplicate Scheme for Purchase Invoice "
998
					+ purchase.getPurchaseReference();
999
			Map<Integer, String> inventorySerialNumberMap = inventoryItemRepository.selectByPurchaseId(purchase.getId())
1000
					.stream().filter(ii -> ii.getSerialNumber() != null)
1001
					.collect(Collectors.toMap(InventoryItem::getId, InventoryItem::getSerialNumber));
1002
			if (inventorySerialNumberMap.size() > 0) {
1003
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1004
					String serialNumber = inventorySerialNumberEntry.getValue();
1005
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1006
					if (serialNumbersConsidered.contains(serialNumber)) {
1007
						// This will rollback scheme for differenct orders for same serial
1008
						List<SchemeInOut> sios = schemeInOutRepository
1009
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1010
								.filter(x -> x.getRolledBackTimestamp() == null
1011
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1012
								.collect(Collectors.toList());
1013
						Collections.reverse(sios);
1014
						for (SchemeInOut sio : sios) {
1015
							sio.setRolledBackTimestamp(LocalDateTime.now());
1016
							amountToRollback += sio.getAmount();
1017
							// sio.setSchemeType(SchemeType.OUT);
1018
							sio.setSerialNumber(serialNumber);
1019
							rolledbackSios.add(sio);
1020
						}
1021
						description = description.concat(" " + serialNumber + " ");
1022
					} else {
1023
						serialNumbersConsidered.add(serialNumber);
1024
						List<Integer> schemesConsidered = new ArrayList<>();
1025
						List<SchemeInOut> sios = schemeInOutRepository
1026
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
1027
								.filter(x -> x.getRolledBackTimestamp() == null
1028
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.IN))
1029
								.collect(Collectors.toList());
1030
						Collections.reverse(sios);
1031
						for (SchemeInOut sio : sios) {
1032
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1033
								schemesConsidered.add(sio.getSchemeId());
1034
								continue;
1035
							}
1036
							sio.setRolledBackTimestamp(LocalDateTime.now());
1037
							amountToRollback += sio.getAmount();
1038
							// sio.setSchemeType(SchemeType.OUT);
1039
							sio.setSerialNumber(serialNumber);
24681 amit.gupta 1040
							sio.setStoreCode(storeNameMap.get(purchase.getFofoId()));
1041
							sio.setReference(purchase.getId());
24635 amit.gupta 1042
							rolledbackSios.add(sio);
1043
						}
1044
					}
1045
 
1046
				}
1047
			}
1048
			if (amountToRollback > 0) {
24683 amit.gupta 1049
				// Address address =
1050
				// addressRepository.selectAllByRetailerId(purchase.getFofoId(), 0, 10).get(0);
24635 amit.gupta 1051
				UserWalletHistory uwh = new UserWalletHistory();
1052
				uwh.setAmount(Math.round(amountToRollback));
1053
				uwh.setDescription(description);
1054
				uwh.setTimestamp(LocalDateTime.now());
24681 amit.gupta 1055
				uwh.setReferenceType(WalletReferenceType.SCHEME_IN);
24635 amit.gupta 1056
				uwh.setReference(purchase.getId());
1057
				uwh.setWalletId(userWalletMap.get(purchase.getFofoId()));
1058
				uwh.setFofoId(purchase.getFofoId());
24681 amit.gupta 1059
				uwh.setStoreCode(storeNameMap.get(purchase.getFofoId()));
24635 amit.gupta 1060
				userWalletHistory.add(uwh);
1061
			}
1062
		});
1063
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1064
				Arrays.asList("User Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
1065
						"Timestamp"),
1066
				userWalletHistory.stream()
1067
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1068
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
1069
						.collect(Collectors.toList()));
1070
 
1071
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
24683 amit.gupta 1072
				Arrays.asList("Scheme ID", "SchemeType", "Reference", "Store Code", "Serial Number", "Amount",
1073
						"Created", "Rolledback"),
24635 amit.gupta 1074
				rolledbackSios.stream()
24681 amit.gupta 1075
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getReference(), x.getStoreCode(),
24635 amit.gupta 1076
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1077
						.collect(Collectors.toList()));
1078
 
25043 amit.gupta 1079
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24636 amit.gupta 1080
				"Partner Excess Amount Scheme In", "PFA",
24635 amit.gupta 1081
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
24636 amit.gupta 1082
						new Attachment("SchemeInRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24635 amit.gupta 1083
 
25096 amit.gupta 1084
		throw new Exception();
24635 amit.gupta 1085
 
1086
	}
1087
 
1088
	public void dryRunOutSchemeReco() throws Exception {
1089
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1090
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
24606 amit.gupta 1091
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1092
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
24590 amit.gupta 1093
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1094
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
25028 amit.gupta 1095
		LocalDateTime startDate = LocalDate.of(2019, 5, 1).atStartOfDay();
24632 amit.gupta 1096
		LocalDateTime endDate = LocalDate.now().atStartOfDay();
24631 amit.gupta 1097
		List<FofoOrder> allOrders = fofoOrderRepository.selectBetweenSaleDate(startDate, endDate);
1098
		// Collections.reverse(allOrders);
1099
		// List<FofoOrder> allOrders =
24653 govind 1100
		// List<FofoOrder> allOrders =
24631 amit.gupta 1101
		// Arrays.asList(fofoOrderRepository.selectByInvoiceNumber("UPGZ019/25"));
24625 amit.gupta 1102
		Set<String> serialNumbersConsidered = new HashSet<>();
24590 amit.gupta 1103
		allOrders.stream().forEach(fofoOrder -> {
24592 amit.gupta 1104
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
24598 amit.gupta 1105
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
24592 amit.gupta 1106
			float amountToRollback = 0;
24590 amit.gupta 1107
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1108
			orderItems.forEach(x -> {
24606 amit.gupta 1109
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
24598 amit.gupta 1110
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
24590 amit.gupta 1111
			});
24606 amit.gupta 1112
			if (inventorySerialNumberMap.size() > 0) {
24631 amit.gupta 1113
				for (Map.Entry<Integer, String> inventorySerialNumberEntry : inventorySerialNumberMap.entrySet()) {
1114
					String serialNumber = inventorySerialNumberEntry.getValue();
1115
					int inventoryItemId = inventorySerialNumberEntry.getKey();
1116
					if (serialNumbersConsidered.contains(serialNumber)) {
1117
						// This will rollback scheme for differenct orders for same serial
1118
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1119
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1120
								.filter(x -> x.getRolledBackTimestamp() == null
1121
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1122
								.collect(Collectors.toList());
1123
						Collections.reverse(sios);
1124
						for (SchemeInOut sio : sios) {
1125
							sio.setRolledBackTimestamp(LocalDateTime.now());
1126
							amountToRollback += sio.getAmount();
1127
							// sio.setSchemeType(SchemeType.OUT);
1128
							sio.setSerialNumber(serialNumber);
1129
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
24681 amit.gupta 1130
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1131
							rolledbackSios.add(sio);
24623 amit.gupta 1132
						}
24635 amit.gupta 1133
						description = description.concat(" " + serialNumber + " ");
24631 amit.gupta 1134
					} else {
1135
						serialNumbersConsidered.add(serialNumber);
1136
						List<Integer> schemesConsidered = new ArrayList<>();
1137
						List<SchemeInOut> sios = schemeInOutRepository
24633 amit.gupta 1138
								.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItemId))).stream()
24635 amit.gupta 1139
								.filter(x -> x.getRolledBackTimestamp() == null
1140
										&& schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24631 amit.gupta 1141
								.collect(Collectors.toList());
1142
						Collections.reverse(sios);
1143
						for (SchemeInOut sio : sios) {
1144
							if (!schemesConsidered.contains(sio.getSchemeId())) {
1145
								schemesConsidered.add(sio.getSchemeId());
1146
								continue;
1147
							}
1148
							sio.setRolledBackTimestamp(LocalDateTime.now());
1149
							amountToRollback += sio.getAmount();
1150
							// sio.setSchemeType(SchemeType.OUT);
24681 amit.gupta 1151
							sio.setReference(fofoOrder.getId());
24631 amit.gupta 1152
							sio.setSerialNumber(serialNumber);
1153
							sio.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1154
							rolledbackSios.add(sio);
1155
						}
24615 amit.gupta 1156
					}
24631 amit.gupta 1157
 
24604 amit.gupta 1158
				}
24590 amit.gupta 1159
			}
24631 amit.gupta 1160
			if (amountToRollback > 0) {
1161
				UserWalletHistory uwh = new UserWalletHistory();
1162
				uwh.setAmount(Math.round(amountToRollback));
1163
				uwh.setDescription(description);
1164
				uwh.setTimestamp(LocalDateTime.now());
1165
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1166
				uwh.setReference(fofoOrder.getId());
1167
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1168
				uwh.setFofoId(fofoOrder.getFofoId());
1169
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1170
				userWalletHistory.add(uwh);
1171
			}
24590 amit.gupta 1172
		});
24598 amit.gupta 1173
 
24592 amit.gupta 1174
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
24681 amit.gupta 1175
				Arrays.asList("Wallet Id", "Store Code", "Reference Type", "Reference", "Amount", "Description",
24615 amit.gupta 1176
						"Timestamp"),
1177
				userWalletHistory.stream()
1178
						.map(x -> Arrays.asList(x.getWalletId(), x.getStoreCode(), x.getReferenceType(),
1179
								x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24592 amit.gupta 1180
						.collect(Collectors.toList()));
1181
 
1182
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1183
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1184
						"Rolledback"),
1185
				rolledbackSios.stream()
1186
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1187
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1188
						.collect(Collectors.toList()));
1189
 
25043 amit.gupta 1190
		Utils.sendMailWithAttachments(googleMailSender, new String[] { "amit.gupta@shop2020.in" }, null,
24681 amit.gupta 1191
				"Partner Excess Amount Scheme Out", "PFA",
24598 amit.gupta 1192
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1193
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1194
 
25267 amit.gupta 1195
		throw new Exception();
24590 amit.gupta 1196
	}
24615 amit.gupta 1197
 
24611 amit.gupta 1198
	public void dryRunSchemeOutReco1() throws Exception {
24615 amit.gupta 1199
		List<Integer> references = Arrays.asList(6744, 7347, 8320, 8891, 9124, 9217, 9263, 9379);
24611 amit.gupta 1200
		List<UserWalletHistory> userWalletHistory = new ArrayList<>();
1201
		List<SchemeInOut> rolledbackSios = new ArrayList<>();
1202
		Map<Integer, Integer> userWalletMap = userWalletRepository.selectAll().stream()
1203
				.collect(Collectors.toMap(UserWallet::getUserId, UserWallet::getId));
1204
		Map<Integer, SchemeType> schemeTypeMap = schemeRepository.selectAll().stream()
1205
				.collect(Collectors.toMap(Scheme::getId, Scheme::getType));
1206
		references.stream().forEach(reference -> {
1207
			FofoOrder fofoOrder = null;
1208
			try {
1209
				fofoOrder = fofoOrderRepository.selectByOrderId(reference);
24615 amit.gupta 1210
			} catch (Exception e) {
1211
 
24611 amit.gupta 1212
			}
1213
			String description = "Adjustment of Duplicate Scheme for Sale Invoice " + fofoOrder.getInvoiceNumber();
1214
			Map<Integer, String> inventorySerialNumberMap = new HashMap<>();
1215
			float amountToRollback = 0;
1216
			List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1217
			orderItems.forEach(x -> {
1218
				inventorySerialNumberMap.putAll(x.getFofoLineItems().stream().filter(li -> li.getSerialNumber() != null)
1219
						.collect(Collectors.toMap(FofoLineItem::getInventoryItemId, FofoLineItem::getSerialNumber)));
1220
			});
1221
			if (inventorySerialNumberMap.size() > 0) {
24615 amit.gupta 1222
				List<SchemeInOut> sios = schemeInOutRepository
1223
						.selectByInventoryItemIds(inventorySerialNumberMap.keySet()).stream()
1224
						.filter(x -> schemeTypeMap.get(x.getSchemeId()).equals(SchemeType.OUT))
24611 amit.gupta 1225
						.collect(Collectors.toList());
1226
				LOGGER.info("Found {} duplicate schemeouts for Orderid {}", sios.size(), fofoOrder.getId());
1227
				UserWalletHistory uwh = new UserWalletHistory();
24615 amit.gupta 1228
				Map<Integer, List<SchemeInOut>> inventoryIdSouts = sios.stream()
1229
						.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId, Collectors.toList()));
24611 amit.gupta 1230
				for (Map.Entry<Integer, List<SchemeInOut>> inventorySioEntry : inventoryIdSouts.entrySet()) {
1231
					List<SchemeInOut> outList = inventorySioEntry.getValue();
24615 amit.gupta 1232
					if (outList.size() > 1) {
1233
 
24611 amit.gupta 1234
					}
1235
				}
1236
				uwh.setAmount(Math.round(amountToRollback));
1237
				uwh.setDescription(description);
1238
				uwh.setTimestamp(LocalDateTime.now());
1239
				uwh.setReferenceType(WalletReferenceType.SCHEME_OUT);
1240
				uwh.setReference(fofoOrder.getId());
1241
				uwh.setWalletId(userWalletMap.get(fofoOrder.getFofoId()));
1242
				uwh.setFofoId(fofoOrder.getFofoId());
1243
				uwh.setStoreCode(fofoOrder.getInvoiceNumber().split("/")[0]);
1244
				userWalletHistory.add(uwh);
1245
			}
1246
		});
24615 amit.gupta 1247
 
24611 amit.gupta 1248
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1249
				Arrays.asList("User Id", "Reference Type", "Reference", "Amount", "Description", "Timestamp"),
1250
				userWalletHistory.stream().map(x -> Arrays.asList(x.getWalletId(), x.getReferenceType(),
1251
						x.getReference(), x.getAmount(), x.getDescription(), x.getTimestamp()))
24615 amit.gupta 1252
						.collect(Collectors.toList()));
1253
 
24611 amit.gupta 1254
		ByteArrayOutputStream baosOuts = FileUtil.getCSVByteStream(
1255
				Arrays.asList("Scheme ID", "SchemeType", "Store Code", "Serial Number", "Amount", "Created",
1256
						"Rolledback"),
1257
				rolledbackSios.stream()
24615 amit.gupta 1258
						.map(x -> Arrays.asList(x.getSchemeId(), x.getSchemeType(), x.getStoreCode(),
1259
								x.getSerialNumber(), x.getAmount(), x.getCreateTimestamp(), x.getRolledBackTimestamp()))
1260
						.collect(Collectors.toList()));
1261
 
24623 amit.gupta 1262
		Utils.sendMailWithAttachments(googleMailSender,
1263
				new String[] { "amit.gupta@shop2020.in", "neeraj.gupta@smartdukaan.com" }, null,
24611 amit.gupta 1264
				"Partner Excess Amount", "PFA",
1265
				new Attachment[] { new Attachment("WalletSummary.csv", new ByteArrayResource(baos.toByteArray())),
1266
						new Attachment("SchemeOutRolledback.csv", new ByteArrayResource(baosOuts.toByteArray())) });
24631 amit.gupta 1267
 
24628 amit.gupta 1268
		throw new Exception();
24615 amit.gupta 1269
 
24611 amit.gupta 1270
	}
24615 amit.gupta 1271
 
24855 amit.gupta 1272
	public void sendDailySalesReportNotificationToPartner(Integer fofoIdInt)
24653 govind 1273
			throws ProfitMandiBusinessException, MessagingException, IOException {
1274
		LocalDateTime now = LocalDateTime.now();
1275
		LocalDateTime from = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 00, 00);
1276
		Map<Integer, Double> salesByFofoIdMap = new HashMap<>();
24855 amit.gupta 1277
		List<Integer> fofoIds = null;
25043 amit.gupta 1278
		if (fofoIdInt == null) {
1279
			fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).map(x -> x.getId())
1280
					.collect(Collectors.toList());
24856 amit.gupta 1281
		} else {
24855 amit.gupta 1282
			fofoIds = Arrays.asList(fofoIdInt);
1283
		}
24653 govind 1284
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
1285
				.selectAllGeEqAndLeEqStartDateAndEndDate(now);
24683 amit.gupta 1286
		DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h a");
1287
 
1288
		Map<Integer, Float> dailyTarget = new HashMap<>();
24653 govind 1289
		for (Integer fofoId : fofoIds) {
24683 amit.gupta 1290
			Map<Integer, Float> dailyAverageSale = null;
24653 govind 1291
			double sale = fofoOrderRepository.selectTotalSaleSumByFofoIdBrtweenDate(fofoId, from, now);
1292
			for (PartnerTargetDetails partnerTargetDetail : partnerTargetDetails) {
1293
				Map<Integer, Float> targetValues = targetService.getTargetValueByFofoIdAndTargetId(fofoId,
1294
						partnerTargetDetail.getId());
1295
				if (targetValues.size() == 0) {
1296
					continue;
1297
				} else {
1298
					List<Integer> partnerIds = new ArrayList<>();
1299
					partnerIds.add(fofoId);
1300
					dailyAverageSale = targetService.getDailyAverageSaleForCurrentForSingleFofoIdAndBrand(partnerIds,
1301
							targetValues, partnerTargetDetail.getStartDate(), partnerTargetDetail.getEndDate(),
1302
							partnerTargetDetail.getBrandName());
1303
					dailyTarget.put(fofoId, dailyAverageSale.get(fofoId));
1304
					break;
1305
				}
1306
			}
1307
			NotificationCampaigns notification = new NotificationCampaigns();
24847 amit.gupta 1308
			notification.setName("Daily Sales");
1309
			notification.setTitle("Daily Sale Update");
24683 amit.gupta 1310
			if (dailyAverageSale != null && dailyAverageSale.get(fofoId) != null) {
24864 amit.gupta 1311
				notification.setMessage(String.format("Rs.%.0f till %s. Today's Target is Rs.%.0f", sale,
24847 amit.gupta 1312
						now.format(timeFormatter), dailyAverageSale.get(fofoId)));
24683 amit.gupta 1313
			} else {
25043 amit.gupta 1314
				notification.setMessage(String.format("Rs.%.0f till %s", sale, now.format(timeFormatter)));
24653 govind 1315
			}
24683 amit.gupta 1316
			// notification.setMessage("Your sale is "+salesbyfofoId.get(fofoId));
24989 tejbeer 1317
			notification.setType("url");
24863 govind 1318
			notification.setUrl("http://app.profitmandi.com/pages/home/notifications");
24683 amit.gupta 1319
			LOGGER.info("UserID" + userAccountRepository.selectUserIdByRetailerId(fofoId));
1320
			notification.setSql("SELECT distinct d1.user_id from devices d1 left join devices d2 on"
1321
					+ "(d1.imeinumber = d2.imeinumber and d1.created < d2.created) "
1322
					+ " where d2.id is null and d1.user_id = "
1323
					+ userAccountRepository.selectUserIdByRetailerId(fofoId));
24676 govind 1324
			LOGGER.info("SELECT distinct d1.user_id from devices d1 left join devices d2 on"
24683 amit.gupta 1325
					+ "(d1.imeinumber = d2.imeinumber and d1.created < d2.created) "
1326
					+ " where d2.id is null and d1.user_id = "
1327
					+ userAccountRepository.selectUserIdByRetailerId(fofoId));
24667 govind 1328
			notification.setExpiresat(LocalDateTime.now().plusDays(1).toEpochSecond(ZoneOffset.UTC) * 1000);
24653 govind 1329
			notification.setStatus("active");
1330
			notification.setSmsprocessed(0);
1331
			notification.setNotification_processed(0);
1332
			notification.setNotification_type("GENERAL_NOTIFICATION");
24657 govind 1333
			mongoClient.persistNotificationCmpInfo(notification);
24653 govind 1334
			salesByFofoIdMap.put(fofoId, sale);
1335
			LOGGER.info(sale);
1336
		}
24683 amit.gupta 1337
		String saleReport = this.getDailySalesReportByPartnerId(salesByFofoIdMap, dailyTarget);
24653 govind 1338
		LOGGER.info(saleReport);
1339
		String cc[] = { "Tarun.verma@smartdukaan.com", "Kamini.sharma@smartdukaan.com",
24697 amit.gupta 1340
				"chaitnaya.vats@smartdukaan.com", "adeel.yazdani@smartdukaan.com", "mohinder.mutreja@smartdukaan.com" };
24653 govind 1341
		String subject = "sale report till" + " " + now.format(timeFormatter);
24677 govind 1342
		this.sendMailOfHtmlFomat("amod.sen@smartdukaan.com", saleReport, cc, subject);
24653 govind 1343
	}
1344
 
24683 amit.gupta 1345
	public String getDailySalesReportByPartnerId(Map<Integer, Double> salesByFofoIdMap, Map<Integer, Float> dailyTarget)
24653 govind 1346
			throws ProfitMandiBusinessException {
1347
		StringBuilder sb = new StringBuilder();
1348
		sb.append("<html><body><p>Sale Report:</p><br/><table style='border:1px solid black ;padding: 5px';>");
1349
		sb.append("<tbody>\n" + "	    				<tr>\n"
1350
				+ "	    					<th style='border:1px solid black;padding: 5px'>Partner</th>\n"
1351
				+ "	    					<th style='border:1px solid black;padding: 5px'>Daily Target</th>\n"
1352
				+ "	    					<th style='border:1px solid black;padding: 5px'>Sale</th>\n"
1353
				+ "	    				</tr>");
1354
		for (Integer fofoId : salesByFofoIdMap.keySet()) {
25043 amit.gupta 1355
			try {
1356
				String PartnerName = retailerService.getFofoRetailer(fofoId).getBusinessName();
1357
				sb.append("<tr>");
1358
				sb.append("<td style='border:1px solid black;padding: 5px'>" + PartnerName + "</td>");
1359
				if (dailyTarget != null && dailyTarget.get(fofoId) != null) {
1360
					sb.append("<td style='border:1px solid black;padding: 5px'>" + dailyTarget.get(fofoId) + "</td>");
1361
				} else {
1362
					sb.append("<td style='border:1px solid black;padding: 5px'>" + 0.0 + "</td>");
1363
				}
1364
				sb.append("<td style='border:1px solid black;padding: 5px'>" + salesByFofoIdMap.get(fofoId) + "</td>");
24653 govind 1365
 
25043 amit.gupta 1366
				sb.append("</tr>");
1367
			} catch (Exception e) {
24842 govind 1368
				e.printStackTrace();
1369
			}
25043 amit.gupta 1370
 
24653 govind 1371
		}
24683 amit.gupta 1372
 
24653 govind 1373
		sb.append("</tbody></table></body></html>");
1374
		return sb.toString();
1375
	}
24841 govind 1376
 
1377
	private void sendMailOfHtmlFomat(String email, String body, String cc[], String subject)
1378
			throws MessagingException, ProfitMandiBusinessException, IOException {
1379
		MimeMessage message = mailSender.createMimeMessage();
1380
		MimeMessageHelper helper = new MimeMessageHelper(message);
1381
		helper.setSubject(subject);
1382
		helper.setText(body, true);
1383
		helper.setTo(email);
1384
		if (cc != null) {
1385
			helper.setCc(cc);
1386
		}
1387
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smart Dukaan");
1388
		helper.setFrom(senderAddress);
1389
		mailSender.send(message);
1390
	}
25300 tejbeer 1391
 
25351 tejbeer 1392
	public void sendNotification() throws Exception {
25300 tejbeer 1393
		List<PushNotifications> pushNotifications = pushNotificationRepository.selectAllByTimestamp();
1394
		if (!pushNotifications.isEmpty()) {
1395
			for (PushNotifications pushNotification : pushNotifications) {
25351 tejbeer 1396
				Device device = deviceRepository.selectById(pushNotification.getDeviceId());
25300 tejbeer 1397
				NotificationCampaign notificationCampaign = notificationCampaignRepository
1398
						.selectById(pushNotification.getNotificationCampaignid());
1399
				Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
1400
						.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();
1401
 
1402
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1403
						SimpleCampaignParams.class);
1404
				Campaign campaign = new SimpleCampaign(scp);
25351 tejbeer 1405
				String result_url = campaign.getUrl() + "&user_id=" + device.getUser_id();
25300 tejbeer 1406
				JSONObject json = new JSONObject();
25351 tejbeer 1407
				json.put("to", device.getFcmId());
25300 tejbeer 1408
				JSONObject jsonObj = new JSONObject();
1409
				jsonObj.put("message", campaign.getMessage());
1410
				jsonObj.put("title", campaign.getTitle());
1411
				jsonObj.put("type", campaign.getType());
1412
				jsonObj.put("url", result_url);
1413
				jsonObj.put("time_to_live", campaign.getExpireTimestamp());
1414
				jsonObj.put("image", campaign.getImageUrl());
1415
				jsonObj.put("largeIcon", "large_icon");
1416
				jsonObj.put("smallIcon", "small_icon");
1417
				jsonObj.put("vibrate", 1);
1418
				jsonObj.put("pid", pushNotification.getId());
1419
				jsonObj.put("sound", 1);
1420
				jsonObj.put("priority", "high");
1421
				json.put("data", jsonObj);
25351 tejbeer 1422
				try {
1423
					CloseableHttpClient client = HttpClients.createDefault();
1424
					HttpPost httpPost = new HttpPost(FCM_URL);
25300 tejbeer 1425
 
25351 tejbeer 1426
					httpPost.setHeader("Content-Type", "application/json; utf-8");
1427
					httpPost.setHeader("authorization", "key=" + FCM_API_KEY);
1428
					StringEntity entity = new StringEntity(json.toString());
1429
					httpPost.setEntity(entity);
1430
					CloseableHttpResponse response = client.execute(httpPost);
1431
					LOGGER.info("response" + response);
25300 tejbeer 1432
 
25351 tejbeer 1433
					if (response.getStatusLine().getStatusCode() == 200) {
1434
						pushNotification.setSentTimestamp(LocalDateTime.now());
1435
					} else {
25356 tejbeer 1436
						pushNotification.setSentTimestamp(LocalDateTime.of(1970, 1, 1, 00, 00));
25351 tejbeer 1437
						LOGGER.info("message" + "not sent");
1438
					}
25300 tejbeer 1439
 
25351 tejbeer 1440
				} catch (Exception e) {
1441
					e.printStackTrace();
25300 tejbeer 1442
					LOGGER.info("message" + "not sent");
1443
				}
1444
			}
1445
		}
1446
	}
1447
 
25553 amit.gupta 1448
	public void grouping() throws Exception {
25598 amit.gupta 1449
		/*
1450
		 * for (FofoStore fofoStore : fofoStoreRepository.selectAll()) {
1451
		 * LOGGER.info("{}, {}", fofoStore.getId(),
1452
		 * partnerTypeChangeService.getTypeOnDate(fofoStore.getId(),
1453
		 * LocalDate.now().plusDays(1))); UserWallet userWallet =
1454
		 * userWalletRepository.selectByRetailerId(fofoStore.getId());
1455
		 * if(userWallet==null) continue;
1456
		 * System.out.printf("Store Code %s, Wallet amount %d, Sum amount %f%n",
1457
		 * fofoStore.getCode(), userWallet.getAmount(),
1458
		 * walletService.getWalletAmount(fofoStore.getId())); }
1459
		 */
25597 amit.gupta 1460
		for (Map.Entry<String, Set<String>> storeGuyEntry : csService.getAuthUserPartnerEmailMapping().entrySet()) {
25590 amit.gupta 1461
			System.out.println(storeGuyEntry.getKey() + " = " + storeGuyEntry.getValue());
25503 amit.gupta 1462
		}
1463
	}
24587 amit.gupta 1464
}